ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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 Solution:

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

Program:

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.