Help needed with understanding the code

If i put "cout<<a<<"\n";" in the penultimate line instead of "cout<<n<<"\n";", this code prints out 0. Can someone explain why is that so because I hardly get it?

#include <iostream>
#include <cstdlib>

using namespace std;

int main ()
{
int a=123456;
int n=0;
for (; a>0 ;)
{
a=a/10;
n++;
}
cout<<n<<"\n";
}
n is counting how many for loops are executed.

every loop you make a smaller by a factor of 10 (a = a/10) and so you eventually end up at 0.

try printing out a during the loop:

1
2
3
4
5
6
123456
12345
1234
123
12
1


On the final loop you have 1/10 and so the loop does not execute again as a>0 is false
Last edited on
Topic archived. No new replies allowed.