
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum of Alphabetical Values of Characters in C++
In this problem, we are given an array of string str[]. Our task is to find the score of all strings in the array. The score is defined as the product of the position of the string with the sum of the alphabetical values of the characters of the string.
Let’s take an example to understand the problem,
Input
str[] = {“Learn”, “programming”, “tutorials”, “point” }
Explanation
Position of “Learn” − 1 →
sum = 12 + 5 + 1 + 18 + 14 = 50. Score = 50
Position of “programming” − 2 →
sum = 16 + 18 + 15 + 7 + 18 + 1 + 13 + 13 + 9 + 14 + 7 = 131 Score = 262
Position of “tutorials” − 1 →
sum = 20 + 21 + 20 + 15 + 18 + 9 + 1 + 12 + 19 = 135 Score = 405
Position of “point” − 1 →
sum = 16 + 15 + 9 + 14 + 20 = 74 Score = 296
To solve this problem, a simple approach will be iterating over all strings of the array. For each string, store the position and find the sum of alphabetical values of the string. The multiple position and sum and return the product.
Algorithm
Step 1 − Iterate over the string and store the position and for each string follow step 2 and 3 −
Step 2 − Calculate the sum of the alphabets of the string.
Step 3 − print the product of position and sum.
Example
Program to illustrate the working of the above solution,
#include <iostream> using namespace std; int strScore(string str[], string s, int n, int index){ int score = 0; for (int j = 0; j < s.length(); j++) score += s[j] - 'a' + 1; score *= index; return score; } int main(){ string str[] = { "learn", "programming", "tutorials", "point" }; int n = sizeof(str) / sizeof(str[0]); string s = str[0]; for(int i = 0; i<n; i++){ s = str[i]; cout<<"The score of string ' "<<str[i]<<" ' is "<<strScore(str, s, n, i+1)<<endl; } return 0; }
Output
The score of string ' learn ' is 50 The score of string ' programming ' is 262 The score of string ' tutorials ' is 405 The score of string ' point ' is 296