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.
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.
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer