I’m learning C and I am having a hard time understanding loops and the usage of modulo. I know Loops are used to shorten up the program and Modulo’s are used to get out the remainder. My assignment was to “Write a C program to find the sum of an individual positive integer”.
I just spent few hours trying to understand this problem. I experimented too.
int n,d=0,s=0;
printf("\nEnter a number\n\n");
scanf("%d",&n);
while(n>0)
{
d = n%10;
s = s+d;
n = n/10;
}
printf("\n sum of the individual digits = %d",s);
My questions are:
Can anyone help me understand the flow of this program? Why is Modulo being used? and Why is there a n = n/10
Experiements I’ve done:
When I removed d = n%10; line the output prints out the digits seperatley. thus it’s not calculating.
i.e 123 = 6 –> It’s giving me 136
When I removed the line n = n/10 It’s not showing me an output. The printf statement has a parameter ‘s’
Thanks in Advance!
Taking the modulo in
d = n % 10makesdequal to the last digit ofnin base 10.n = n / 10removes the last digit fromn.Modulo is essentially taking the remainder, so let’s say
n = 123. Thenn / 10is12andn % 10is3.Removing the
n = n / 10means thatndoesn’t change between each run of the loop, so the loop conditionn > 0is always true and therefore the loop keeps going until you manually kill the program.Here is a trace of the program with
n = 123. Initiallydandsare both zero.