Explain this C Code: Calculate Sun of 5 digits

/* 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

  • Kaustubh Katdare
    Kaustubh Katdare
    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
    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
    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
    it would be good if we use for loop in this program

You are reading an archived discussion.

Related Posts

I have been working in a small company as a manual tester. I want to be an automated engineer so want to learn automation testing. I don't know have much...
Researchers have found out that turning off your mobile phone can lead to some greater happiness in your life. This 'staying connected' thing is directly turning into unhappiness in people's...
similarly if a transformer is given DC what will happen?
So what are blueprints ? and how do they differ from an engineering drawing ? are these things the same thing, with the exception that the former is printed on...
Auto rickshaws have one wheel in the front and two in the rear. now here is a crazy idea : how about a car with two wheels in the front...