C Program to Find the Sum of ASCII values of all Characters in a String

«
»

This is a C Program to find the sum of ascii values of all characters in a string.

Problem Description

This C Program finds the sum of the ASCII values of all characters that were used in a string.

Problem Solution

Take input from the user and extract ascii values in the given string as shown in the program below.

advertisement
Program/Source Code

Here is a source code of the C program to find the sum of the ASCII values of all characters that were used in a string. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 * C Program to Find the Sum of ASCII values of all Characters 
 * in a String
 */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
 
int sumascii(char [], int);
 
int main()
{
    char str1[30];
    int sum;
 
    printf("Enter a string: ");
    scanf("%s", str1);
    sum = sumascii(str1, 0);
    printf("The sum of all ascii values in '%s' is %d.\n", str1, sum);
 
    return 0;
}
 
int sumascii(char str[], int num)
{
    if (num < strlen(str))
    {
        return (str[num] + sumascii(str, num + 1));
    }
 
    return 0;
}
Program Explanation

In this C program, reading the value of string using ‘string1’ variable. Compute the length of the string using strlen() function. For loop is used to compute the sum of ASCII values of all characters in a given string.

advertisement

Initialize the value of ‘i’ variable value as 0 and check the value of ‘i’ variable is less than the value of ‘len’ variable. If the condition is true then execute the statement and compute the summation of the value of ‘sum’ variable with the value of string1[] array variable. Print the sum of ASCII values of all characters in a given string.

Runtime Test Cases
 
$ gcc asciisum.c 
$ ./a.out
Enter a string: education
The sum of all ascii values in 'education' is 956.

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement

Here’s the list of Best Reference Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn