0
Sololearn challenge
Am not that smart but đ đ Int n = 5 While (n--) { if (n % 2 == 0){ Cout << "0" ; } else{ Cout << n ; } } The answer is 03010 Can anyone break down this code just a brief explaination will do đ?...
2 RĂ©ponses
+ 3
while(n--)
1st loop => n = 4 => prints 0
2nd loop => n = 3 => prints 3
3rd loop => n = 2 => prints 0
4th loop => n = 1 => prints 1
5th loop => n = 0 => prints 0
6th loop => while(0) => false => loop won't run.
+ 1
'while (n--)' use post decrementation, meaning that first the value of n is tested, then n is assigned n-1...
at start n == 5
loop start, n is evaluated to true (as 5 != 0) so first execution of loop body... with n == 4
n % 2 == 0 is true (0 == 0) so 'if' statement is executed, not 'else':
output => 0
n is tested and evaluated to true (4 != 0)... again loop body... with n == 3
n % 2 == 0 is false (1 != 0) so 'else' statement is executed not 'if':
output => 3
n is true (3 != 0), so n == 2 and 'if' executed:
output => 0
n is true (2 != 0), so n == 1 and 'else' executed:
output => 1
n is true (1 != 0), so n == 0 and 'if' executed:
output => 0
n is false (0==0), so loop ends
final whole done output => 03010