×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to find the sum of all digits in the alphanumeric string

Here, we are going to learn how to find the sum of all digits in the alphanumeric string in C programming language?
Submitted by Nidhi, on July 18, 2021

Problem statement

Read an alphanumeric string from the user, then find the sum of all digits present in the string using C program.

C program to find the sum of all digits in the alphanumeric string

The source code to find the sum of all digits in the alphanumeric string is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to find the sum of all digits
// in alphanumeric string

#include <stdio.h>

int main()
{
    char str[64];
    int i = 0;
    int sum = 0;

    printf("Enter alphanumeric string: ");
    scanf("%[^\n]s", str);

    while (str[i] != 0) {
        if ((str[i] >= '0') && (str[i] <= '9'))
            sum += (str[i] - 0x30);
        i++;
    }
    printf("Sum of all digits is: %d\n", sum);

    return 0;
}

Output

RUN 1:
Enter alphanumeric string: Hello I am 27. And, I live at 219 First Floor.
Sum of all digits is: 21

RUN 2:
Enter alphanumeric string: ABC1D35R
Sum of all digits is: 9

Explanation

In the main() function, we read the value of string str from the user. Then we found the digits in string and calculate the sum of all digits. After that, we printed the result on the console screen.

C String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.