C++ Program to find Sum of ASCII values in a Character Array

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 Sum of ASCII values in a Character Array 1

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;
}
Please Enter any Name 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 All ASCII Value in a Given Array hello = 532

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;
}
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 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 all characters  = 1638