Home > database >  How does this program in C sum all the digits in the string?
How does this program in C sum all the digits in the string?

Time:12-16

I went to this website: https://www.sanfoundry.com/c-program-sum-all-digits-string/

and they have a funciton that adds up all the digits in a string array. I'm wondering how it's doing this.

/*
 * C program to find the sum of all digits present in the string
 */
#include <stdio.h>
void main()
{
    char string[80];
    int count, nc = 0, sum = 0;
 
    printf("Enter the string containing both digits and alphabet \n");
    scanf("%s", string);
    for (count = 0; string[count] != '\0'; count  )
    {
        if ((string[count] >= '0') && (string[count] <= '9'))
        {
            nc  = 1;
            sum  = (string[count] - '0');
        }
    }
    printf("NO. of Digits in the string = %d\n", nc);
    printf("Sum of all digits = %d\n", sum);
}

This is the program^ So, correct me if I am wrong, but the for loop is going through each element in the string array until the null character appears, using count to represent the element number, right? And the if statement is doing this: if the element is a number between 0 and 9... But, I genuinely don't understand what this line does: sum = (string[count] - '0');

so that line is basically: sum = sum (string[count] - '0'); but what does this part do: (string[count] - '0'); Why do you subtract 0 from the digit in the string array? Or am I looking at this wrong?

CodePudding user response:

sum  = (string[count] - '0');

This is a trick to convert a single character digit like '5' into the integer 5.

'0' is the character for 0. All characters are numbers interpreted as characters; you can just use them as numbers. If we look at an ASCII table we see that '0' is the number 48. '1' is 49, '2' is 50... up to '9' at 57. They're all in order and one can take advantage of this. So '9' - '0' is 57 - 48 which is... 9!

Similarly, if you want to know the position of a letter in the alphabet (starting from 0) you can do letter - 'a' or letter - 'A' depending on if it's lower or upper case. (There are some character sets where this is not true but you are very unlikely to encounter these.)

  • Related