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.
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
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.
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 */
}