+ 4

Why the output of this code is 9?

int n,f,s; n=18; while (n>0) { f=n%10; n=n/10; s+=f; } cout<<s;

30th Nov 2018, 1:19 PM
Juan David Padilla Diaz
Juan David Padilla Diaz - avatar
7 Antworten
+ 8
Debugging tip for beginners: Don't give yourself a headache! Just print each cycle of the loop like so #include <iostream> using namespace std; int main() { int n,f,s = 0; n=18; while (n > 0) { cout << "Cycle: " << n << ", "; f = n % 10; cout << f << ", "; n = n / 10; cout << n << ", "; s += f; cout << s << "\n"; } cout << s; } Output: Cycle: 18, 8, 1, 8 Cycle: 1, 1, 0, 9 9
30th Nov 2018, 1:26 PM
Babak
Babak - avatar
+ 12
● After 1st cycle of loop : f=8 , n=1 (as int/int gives int & decimal part is removed) , s=8(adding value of f to it) ● After 2nd cycle of loop : f=1 , n=0 , s=9 (adding f to 8)
30th Nov 2018, 1:29 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 8
first iteration (while) f = 8 n = 1 s = 8 second (last) iteration: f = 1 n = 0 s = 1 + 8 or s = 9 remember % takes the remainder of int division. and s+=f have the same effect compared with s = s + f
30th Nov 2018, 1:28 PM
Anya
Anya - avatar
+ 2
While loop runs 2 times For first time: n=18 f=n%10 = 18%10 = 8 n=n/10 = 18/10 = 1 s=s+f = 0+8 = 8 For the second time: n=1 f=n%10 = 1%10 = 1 n=n/10 =1/10 = 0 s=s+f = 8+1 = 9
30th Nov 2018, 1:36 PM
Rishi Anand
Rishi Anand - avatar
+ 1
The code op posted can potentially cause problems if s isn't initialised to zero. Since you're adding something to s, and it isn't initialised, it's going to use the value stored at the 4 bytes it is given, which is going to ultimately return some garbage value.
1st Dec 2018, 1:06 PM
Soham Kar
Soham Kar - avatar
+ 1
first loop : f=18%10=8 n=18/10=1 s=0+8=8 s=8 store second loop: 1>0 true f=1%10=1 n=1/10=0 s=8+1=9. s=9 stored third loop: 0>0 false output: 9
1st Dec 2018, 1:08 PM
Nirav Satani
Nirav Satani - avatar
0
Because s != 0! s it’s nil(or null, I don’t know). It’s right code: #include <iostream> using namespace std; int main() { int n=18,f,s=0; while(n>0) { f=n%10; n/=10; s+=f; } cout<<s; }
30th Nov 2018, 3:02 PM
Искандер
Искандер - avatar