Write a C++ Program to find the Sum of ASCII values in a Character Array with an example. In this C++ code, we allow the user to enter a character array and used for loop (for(i = 0; name[i] != ‘\0’; i++) ) to iterate values from 0 to character array length.
Within that, we are adding the ASCII value of each character in the name array to ASCII_Sum (ASCII_Sum = ASCII_Sum + name[i]). Here, cout << “\nThe ASCII Value of “<< name[i] << ” = ” << (int)name[i] statement prints the character arrays ASCII values.
#include<iostream>
using namespace std;
int main()
{
int i, ASCII_Sum = 0;
char name[20];
cout << "Please Enter any Name you want = ";
cin.getline(name, 20);
for(i = 0; name[i] != '\0'; i++)
{
cout << "\nThe ASCII Value of "<< name[i] << " = " << (int)name[i];
ASCII_Sum = ASCII_Sum + name[i];
}
cout << "\nThe Sum of All ASCII Value in a Given Array "<< name << " = " << ASCII_Sum;
return 0;
}
C++ Program to find the Sum of ASCII values in a Character Array using a While loop
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
int i = 0, ASCII_Sum = 0;
char name[20];
cout << "Please Enter any Name you want = ";
cin.getline(name, 20);
while(i < strlen(name))
{
cout << "\nThe ASCII Value of "<< name[i] << " = " << (int)name[i];
ASCII_Sum = ASCII_Sum + name[i];
i++;
}
cout << "\n\nThe Sum of All ASCII Value in a Given Array "<< name << " = " << ASCII_Sum;
return 0;
}
It is another C++ example to calculate the sum of ASCII values in a Character Array using a While loop.
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int i, sum = 0;
char name[20];
cout << "Please Enter the Name = ";
cin.getline(name, 20);
while(name[i]!='\0')
{
cout << "\nThe ASCII Value of "<< name[i] << " = " << (int)name[i];
sum = sum + name [i];
i++;
}
cout << "\n\nThe Sum of all characters = "<< sum;
return 0;
}