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.

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
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.

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

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

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
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 & discussions at Telegram SanfoundryClasses.