I just started with competitive programming and have been using a loop like the one below to define the number of test cases in most of the practice problems.
for(int i=1;i<=t;i++)
{
...
}
However, I have seen people using a while loop which just has the condition
(t--)
which runs perfectly okay too. Can someone explain to me how this condition actually works? Is it the same as while(t!=0)
, but instead of a decrement in the value of later in the loop, we are doing it here?
Yes.
int t = 5;
while(t--){...}
runs the loop until t
is 0
during checking it's value, since 0
is equally to false
in a logical context.
Because t--
is the post decremental operator on t
, the value of it will be modified after the while
checks it, so it will be -1 in the end. Therefore, the values of t
inside the loop will be: 4,3,2,1,0.
But it creates an additional variable outside the loop scope - so I do prefer the for
loop.
The body of the while
loop is executed repeatedly until the value of its condition becomes false (note that if the condition is initially false, the loop will not execute at all). The condition test takes place before each execution of the loop's body. Now, let's say you have this:
int x = 5;
while(x--)
{
cout << x;
}
Each iteration the condition of the while loop will be evaluated and checked for false
. Since we use postfix decrement, x
will first be used (i.e. checked for false
to break the loop), and then decreased, which means the loop above will print 43210
, and then finish.
It's worth noting that after the loop finishes, the value of x
will be -1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With