C++ Program to Find the Sum of ASCII Value of All Characters in the String


This is a C++ Program to Find the Sum of ASCII Value of all Elements in a String.

Problem Description

The program takes a string and prints the sum ASCII values of all the characters.

Problem Solution

1. The program takes a string.
2. Using a for loop, the ASCII equivalent of each character is added.
3. The resultant sum is printed.
4. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Find the Sum of ASCII Value of all Elements in a String. The program output is shown below.

  1. #include<iostream>
  2. using namespace std;
  3. int main ()
  4. {
  5.     char str[50];
  6.     int i, sum = 0; 
  7.     cout << "Enter a string : ";
  8.     gets(str);
  9.     for (i = 0; str[i] != '\0'; i++)
  10.         sum = sum + str[i];
  11.     cout << "Sum of all characters : " << sum;
  12.     return 0;
  13. }
Program Explanation

1. The user is asked to enter a string. It is stored in ‘str’.
2. A variable ‘sum’ is initialized as 0.
3. Using a for loop, ASCII value of every character in the string is added to sum.
4. The total sum of the characters is then printed.

Note: Join free Sanfoundry classes at Telegram or Youtube
Runtime Test Cases
Case 1 :
Enter a string : found
Sum of all characters : 540
Case 2 :
Enter a string : 24
Sum of all characters : 102
Case 3 :
Enter a string : a
Sum of all characters : 97

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

Take C++ Programming Practice Tests - Chapterwise!
Start the Test Now: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.