Vaibhav Vasant
Vaibhav Vasant

Reputation: 55

Why the output in following code stops at 0?

#include<iostream>
using namespace std;
main()
{
   int test =3;
   while(test--)
   {
      cout<<test;
   }
}

The above code shows output 210.My question is that why it stop at 0??Why it can't go beyond 0?

Upvotes: 0

Views: 78

Answers (3)

dd_
dd_

Reputation: 146

you set the condition in while loop to test--, and it will be executed 3 times. When test is 1, it's equal to while(1) or while(true) and it continue while loop. When test is 0, it's equal to while(0) or while(false) and it stops while loop .. Why 210? Because you print it whit no "new line" between prints.

Upvotes: 1

Razib
Razib

Reputation: 11163

In c and c++ any non zero is evaluated to true and zero is evaluated to false. Thats why its stop at 0. The fact is true for for loop too.

For this reason may sometimes found -

while(1){
  //do something 
  if(some_condition) break;
}   

It means its a infinite loop - runs always.

Upvotes: 3

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

"The above code shows output 210.My question is that why it stop at 0??Why it can't go beyond 0?"

Because a int value of 0 evaluates to false in a boolean expression, and the while() loop stops at a false in the condition.

Upvotes: 1

Related Questions