Explain this C Code: Calculate Sun of 5 digits

gsk_ssit

gsk_ssit

@gsk-ssit-KY7Fvw Oct 26, 2024

/* To calculate sum of five digits*/
int num,a,n;
int sum=0;
system("cls");
printf("Enter a five digit number\n");
scanf("%d",&num);
a=num%10;
n=num/10;
sum=sum+a;
a=n%10;
n=n/10;
sum=sum+a;
a=n%10;
n=n/10;
sum=sum+a;
a=n%10;
n=n/10;
sum=sum+a;
a=n%10;
sum=sum+a;
printf("The sum of the five digits of %d is %d\n",num,sum);

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • Kaustubh Katdare

    Kaustubh Katdare

    @thebigk Jan 28, 2013

    Which part of the above do you find difficult to understand? I think it is the part where it says -

    a= num%10;
    n= num/10;

    Am I right?

    First part of understanding the code would be to understand what the % operator does.

  • Anoop Kumar

    Anoop Kumar

    @anoop-kumar-GDGRCn Jan 28, 2013

    Check this out simpler program:

    int num,sum=0;
    printf("Enter a number\n");
    scanf("%d",&num);
     
    while(num >0){
             
                sum=sum+num%10;
                num=num/10;
             
            }
     
    printf("The sum of the digits of %d is    %d\n",num,sum);

    It will return you sum of any digit number.
    % operator is also called as modulo, That means it will return the reminder of operation.
    ps: I wrote this program in java. I hope it good in syntax wise for C.

  • Jeffrey Arulraj

    Jeffrey Arulraj

    @jeffrey-xA7lUP Jan 30, 2013

    It does not find sum of 5 numbers But it finds the sum of the digits of a five digit number

  • ashwin sarangula

    ashwin sarangula

    @ashwin-sarangula-Eb5r0N Jan 30, 2013

    it would be good if we use for loop in this program