How to find the sum of alphabetical order of characters in a string in C++

Given string S of size N, the task is to find the sum of the alphabet value of each character in the given string.

Examples:

 

Input: S = “geek”

Output:  28

Explanation:
The value obtained by the sum order of alphabets is 7 + 5 + 5 + 11 = 28.


Input: S = “GeeksforGeeks”

Output:  133

Approach: 

  • Traverse all the characters present in the given string S.
  • For each lowercase character, add the value (S[i] – ‘a’ + 1) to the final answer, or if it is an uppercase character, add (S[i] – ‘A’ + 1) to the final answer.

Below is the implementation of the above approach:

C++

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;

int findTheSum(string alpha)
{
	// Stores the sum of order of values
	int score = 0;

	for (int i = 0; i < alpha.length(); i++)
	{
		// Find the score
		if (alpha[i] >= 'A' && alpha[i] <= 'Z')
			score += alpha[i] - 'A' + 1;
		else
			score += alpha[i] - 'a' + 1;
	}
	// Return the resultant sum
	return score;
}

// Driver Code
int main()
{
	string S = "GeeksforGeeks";
	cout << findTheSum(S);
	return 0;
}

Output

133

 

Submit Your Programming Assignment Details