The output is 6 but Idk hw plzz help!! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

The output is 6 but Idk hw plzz help!!

int n=15, s=0, x; for(int i=0; i<=n ; i++ ){ x = n%10 ; s=s + x; n = n/10; } System.out.print(s);

10th May 2017, 5:38 PM
Hasrat Wadsariya
Hasrat Wadsariya - avatar
3 Answers
+ 10
This is an algorithm to calculate the sum of all digits in an integer, e.g. n = 1234 // outputs 1+2+3+4 In this case, n = 15. You may try tracking the variable values in the loops. E.g. // first loop x = n%10 ; // x stores 5 s = s + x; // s stores 5 n = n/10; // n becomes 1 // second loop x = n%10 ; // x stores 1 s = s + x; // s stores 6 n = n/10; // n becomes 0 System.out.print(s); // prints 6
10th May 2017, 5:48 PM
Hatsy Rei
Hatsy Rei - avatar
+ 9
Additional to the explanations of Rei and Szabo: https://code.sololearn.com/cKvNWLB4wqnz/?ref=app
10th May 2017, 5:55 PM
Tashi N
Tashi N - avatar
+ 1
1.iteration: i = 0 x = 15%10 = 5 s = 0+5 = 5 n = 15/10 = 1 because is int. 2.iteration i = 1 x = 1%10 = 1 s = 5 + 1 = 6 n = 1 /10 = 0 i <= n (2 < 0) false, so no more iteration. s = 6
10th May 2017, 5:51 PM
Szabó Gábor
Szabó Gábor - avatar