In C++, every character has an internal ASCII value. In this C++ program, we find the sum of ASCII Values in a given string. In this C++ code, we used for loop (for(int i = 0; i < txt.size(); i++)) to iterate values from 0 to string length. Within that, we are adding the ASCII value of each character in a string to txtASCII_Sum (txtASCII_Sum = txtASCII_Sum + txt[I];). Here, cout << “\nThe ASCII Value of “<< txt[i] << ” = ” << (int)txt[i]; statement prints the ASCII value of each string character.
#include<iostream> #include<string.h> using namespace std; int main() { int txtASCII_Sum = 0; string txt; cout << "Please Enter any String you want = "; getline(cin, txt); for(int i = 0; i < txt.size(); i++) { cout << "\nThe ASCII Value of "<< txt[i] << " = " << (int)txt[i]; txtASCII_Sum = txtASCII_Sum + txt[i]; } cout << "\n\nThe Sum of ASCII Value in "<< txt << " String = " << txtASCII_Sum; return 0; }
C++ Program to find Sum of ASCII values in a String using a While loop
#include<iostream> #include<string.h> using namespace std; int main() { int i = 0, txtASCII_Sum = 0; string txt; cout << "Please Enter any String you want = "; getline(cin, txt); while(i < txt.length()) { cout << "\nThe ASCII Value of "<< txt[i] << " = " << (int)txt[i]; txtASCII_Sum = txtASCII_Sum + txt[i]; i++; } cout << "\n\nThe Sum of ASCII Value in "<< txt << " String = " << txtASCII_Sum; return 0; }
Please Enter any String you want = tutorial gateway
The ASCII Value of t = 116
The ASCII Value of u = 117
The ASCII Value of t = 116
The ASCII Value of o = 111
The ASCII Value of r = 114
The ASCII Value of i = 105
The ASCII Value of a = 97
The ASCII Value of l = 108
The ASCII Value of = 32
The ASCII Value of g = 103
The ASCII Value of a = 97
The ASCII Value of t = 116
The ASCII Value of e = 101
The ASCII Value of w = 119
The ASCII Value of a = 97
The ASCII Value of y = 121
The Sum of ASCII Value in tutorial gateway String = 1670
C++ Program to find Sum of ASCII values in a String using For loop and functions.
#include<iostream> #include<string.h> using namespace std; int sumOfASCIIValuesinaString(string txt) { int txtASCII_Sum = 0; for(int i = 0; i < txt.size(); i++) { cout << "\nThe ASCII Value of "<< txt[i] << " = " << (int)txt[i]; txtASCII_Sum = txtASCII_Sum + txt[i]; } return txtASCII_Sum; } int main() { int Sum = 0; string txt; cout << "Please Enter any String you want = "; getline(cin, txt); Sum = sumOfASCIIValuesinaString(txt); cout << "\n\nThe Sum of ASCII Value in "<< txt << " String = " << Sum; return 0; }
Please Enter any String you want = hello
The ASCII Value of h = 104
The ASCII Value of e = 101
The ASCII Value of l = 108
The ASCII Value of l = 108
The ASCII Value of o = 111
The Sum of ASCII Value in hello String = 532