0

Please explain this code,,i dont understand while(n!=0) loop

Sum of its digits #include <stdio.h> int main() { int n, sum = 0, remainder; printf("Enter an integer\n"); scanf("%d", &n); while (n != 0) { remainder = n % 10; sum = sum + remainder; n = n / 10; } printf("Sum of digits is = %d\n", sum); return 0; }

12th Nov 2018, 10:23 AM
Zothansanga Renthlei
Zothansanga Renthlei - avatar
3 Answers
+ 2
n != 0 means the while loop will execute till the number not become 0 so it goes like this ex:- n =123 So n != 0 Goes in loop 123%10=3 It goes in sum = 0+3 =3 Now 123/10=12 Now new number is n =12 Now 12 != 0 so Goes in loop again 12%10=2 Sum =3+2=5 Then 12 / 10= 1 Now n=1 So 1 !=0 So 1%10= 1 Then Sum = 5+1 =6 And 1/ 10 = 0 so n=0 Now while loop condition is 0!=0 is false so loop stop and print the sum which is 6
12th Nov 2018, 10:37 AM
MsJ
MsJ - avatar
+ 3
Loop will work until 'n' is = 0. At end of every loop you divide 'n' by 10, so it will finally become 0.
12th Nov 2018, 10:39 AM
Aleksander Szczepura
Aleksander Szczepura - avatar
+ 1
thanks bro.... i understood... thank you
12th Nov 2018, 10:40 AM
Zothansanga Renthlei
Zothansanga Renthlei - avatar