HPSmash77
HPSmash77

Reputation: 21

code for adding up the digits of a number in C not working

Here is the code

#include <stdio.h>

void main() {

    int num,a;
    a = 0;
    num = 0;
    scanf("%d", &num);
    int i;
    i = 0;
    while (i > 5){

        a = a + num % 10;
        num = num/10 ;
        i = i + 1;

    }

    printf("sum : %d\n", a);

}

the output

11111

sum : 0

I am using gcc preinstalled on ubuntu 20.04 LTS

edit : sorry i forgot to mention that initially a only wanted to add the digits of a five digit number, that is where the 5 came from, sorry edit : sorry again I had to bother you guys for such a silly mistake, I typed greater than (>) instead of less than (<)

Upvotes: 0

Views: 57

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

The condition of the while loop evaluates at once to false because the variable i was initialized by 0.

i = 0;
while (i > 5){

Also it is unclear why there is used the magic number 5.

You could just write for example

while ( num != 0 ){
    a = a + num % 10;
    num = num/10 ;
}

However your approach will work only for non-negative numbers. A more general approach can look for example the following way

while ( num != 0 ){
    a = a + ( num < 0  ? -( num % 10 ) : num % 10 );
    num = num/10 ;
}

Pay attention to that according to the C Standard the function main without parameters shall be declared like

int main( void )

Here is a demonstrative program.

#include <stdio.h>

int main(void) 
{
    while ( 1 )
    {
        const int Base = 10;
        int num = 0;
    
        printf( "Enter an integer number (0 - exit): " );
        
        if ( scanf( "%d", &num ) != 1 || num == 0 ) break;
    
        int sum = 0;
    
        while ( num != 0 )
        {
            sum += num < 0 ? -( num % Base ) : ( num % Base );
            num /= Base;
        }
        
        printf( "The sum of digits of the entered number is %d\n", sum );
    }
    
    return 0;
}

The program output might look like

Enter an integer number (0 - exit): 12345
The sum of digits of the entered number is 15
Enter an integer number (0 - exit): -12345
The sum of digits of the entered number is 15
Enter an integer number (0 - exit): 0

Upvotes: 3

Antonin GAVREL
Antonin GAVREL

Reputation: 11219

You don't need i and loop condition should be num > 0 (or != 0 if you want to handle negative digits with some other modifications):

#include <stdio.h>

int main(void) {

    int num,a;
    a = 0;
    num = 0;
    scanf("%d", &num);
    while (num > 0){
        a += num % 10;
        num /= 10;
    }

    printf("sum : %d\n", a);

}

Upvotes: 1

Related Questions