Will my while loop execute if the condition is false at the start?

0
10
Asked By CoolGiraffe42 On

I have a C++ code snippet that's similar to this: `int exampleVar = 0;` and `while (exampleVar > 0) { exampleVar -= 1; }`. I'm trying to understand if the while loop will run at least once if the condition is already false before it starts. In this case, I'm curious about what the final value of `exampleVar` will be — will it be -1 or 0?

3 Answers

Answered By TechWhiz17 On

That's correct! A while loop checks the condition before it runs. If the condition is false at the start, like in your case, it won't execute the loop body even once. If you wanted it to run at least once regardless of the condition, you could look into using a do-while loop instead.

Answered By CodeNinja91 On

In your example, the condition `exampleVar > 0` is false from the get-go, so the `while` loop won't run at all. Since nothing happens inside the loop, `exampleVar` will remain 0. So, the final value of `exampleVar` is 0.

Answered By DevMaster34 On

Right! Just to clarify, the do-while loop will run the code inside once before checking the condition, while the regular while loop checks it first. So, the value of `exampleVar` would stay at 0 for a while loop, but a do-while could set it to -1 after one execution.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.