Difference between while loop and if statement

I've been working quite a lot with while loops and if statements and I want to know what exacly are the differences beetwen theese two. My code runs if I use while loops but won't work properly with if statements. So what are the diferences between theese two?

PS. I did't post my code because it is really long and hard to understand. :wink:

My answer would be really long and hard to understand if I posted it.

If an "if" statement's condition is not met, the code skips to the next instruction. If a "while" statement's condition is not met, the code stays inside the while loop until the condition is met.
--Michael

2 Likes

'If' is a branch - it makes a decision and executes certain code based on that decision.

'while' is a loop - it keeps executing a certain bit of code as long as the condition is met.

Oops. Thanks for the correction. I described the while loop backward...
--Michael

jug5525:
I've been working quite a lot with while loops and if statements and I want to know what exacly are the differences beetwen theese two. My code runs if I use while loops but won't work properly with if statements. So what are the diferences between theese two?

PS. I did't post my code because it is really long and hard to understand. :wink:

Typically, a while loop will run over and over again until the test condition becomes false. For example:

unsigned long int count = 100000;

while (count--) {
    /* stuff inside here gets done over and over again 100,000 times */
}

You see? Count decrements each time around, starting at 99,999, 99,998, 99,997.....3, 2, 1, 0
At 0, the value of count is false and the while loop ends (and what's below it now gets to run).

Now, an IF statement:

unsigned long int count = 100000;

if (count > 100) {
   /* count is greater than 100 so this code runs once */
}

if (count < 100) {
    /* this code doesn't run because "count less than 100" is false */
}

Make sense?

1 Like

Ok thank you :smiley: I understand it now