How it can be 6 ? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 1

How it can be 6 ?

Is anybody can explain this again to me ?? How this code works ?? int x = 123; int sum = 0; while(x>0){ sum += x%10; x=(x-x%10)/10;} cout << sum;

28th Dec 2016, 6:00 AM
Sofyan Maulana
Sofyan Maulana - avatar
4 Réponses
+ 7
1st time: sum=123%10=3, x=(123-3)/10=12 2nd time: sum=3+(12%10)=3+2=5, x=(12-2)/10=1 3rd time: sum=5+(1%10)=5+1=6, x=(1-1)/10=0, Now since x is not greater than 0 so the loop stops and the last calculated value of sum =6.
28th Dec 2016, 6:25 AM
Saumya
Saumya - avatar
+ 2
Thanks saumya, now i know how the loop is works. I'm forget if there is a loop (while) function on it. hehe
28th Dec 2016, 6:31 AM
Sofyan Maulana
Sofyan Maulana - avatar
+ 1
Sorry for not write the code :v Output of the code will be 6. please help
28th Dec 2016, 6:03 AM
Sofyan Maulana
Sofyan Maulana - avatar
0
????
28th Dec 2016, 6:01 AM
Dago VF
Dago VF - avatar