+ 1

Actually, I cannot understand.. Why the output is 12?

int f=1,i=2 while(++i<5) { f*=i; } cout<<f; //output=12

17th Dec 2019, 5:35 AM
Mantaqa Mansib
Mantaqa Mansib - avatar
5 Answers
+ 5
so f=1,i=2 while(++i<5)//here i becomes 3 { f*=i; //f=f*i; i.e f=1*3=3 } Now in next iteration i becomes 4 and f*=i; So 4*3=12 Next iteration i becomes 5 and loop stops execution as condition is false
17th Dec 2019, 6:31 AM
$hardul B
$hardul B - avatar
+ 4
First iteration i = 2, f = 1 while(++i < 5) -----> while(3 < 5) True f *= i ---> 1 *= 3 f = 3 Second iteration i = 3, f = 3 while(++i < 5) -----> while(4 < 5) True f *= i ---> 3 *= 4 f = 12 Third iteration i = 2, f = 1 while(++i < 5) -----> while(5 < 5) False Loop terminates, final value of f = 12
17th Dec 2019, 6:32 AM
blACk sh4d0w
blACk sh4d0w - avatar
+ 3
You had a greater than symbol inside while and I tried to point it out, so atleast address it so that others would not think what I mentioned earlier is irrelevant.
17th Dec 2019, 7:58 AM
Avinesh
Avinesh - avatar
+ 2
Is your question right? Is that "<" or ">"
17th Dec 2019, 5:46 AM
Avinesh
Avinesh - avatar
+ 1
first entry to the loop before f*=i, because of ++i. i = 3 and f =1 so f*=i ; is equivalent to f = 3 *1 f = 3 second iteration before f*=i, i = 4 and f = 3 f*=i; is equivalent to f = 3 *4 f = 12 i < 5 becomes false and exists the loop. leaving f = 12. when you don't understand something like that plug in a "cout" to print the values and watch their changes. i. e add this before f*=i ; cout << i << " * " << f << endl ; it's a cheap way to debug but it works on small code 😄
17th Dec 2019, 6:40 AM
Bahha┣
Bahha┣ - avatar