for loop syntax

can someone explain the difference between these two syntax?

for(int r= 0; r< 5; r++) and for (int r=0 r<=5; r++)
what is the difference between these two? what does the equal sign add or what does it take out?
thank you in advance!

that is math 101. < means less than. <= means less than or equal. This would mean the first one starts at 0 and continues while it is less than 5 incrementing by one each time. The second one says that it starts at 0 and continues while it is less than or equal to 5 incrementing by one each time. Therefor loop 1 = 0 , 1 , 2 , 3 , 4 and loop 2 = 0 , 1 , 2 , 3 , 4 , 5.
For loops are structured as follows:

1
2
3
4
for( initialization; condition; increment )
{
    body
}


The loop operates like so:
1) initialization happens first
2) condition is checked. If it's false, exit the loop, otherwise proceed to #3
3) body is performed
4) increment is performed
5) go to step 2


What this means for your typical for loop example:
for(int r= 0; r< 5; r++)

Is that the loop will run 5 times. Each time, the variable 'r' will contain a different value.
0, 1, 2, 3, 4

Once r increments to 5, the condition is no longer true and therefore the loop exits.


Compare that to this:
for (int r=0 r<=5; r++)

Which will run six times because the condition runs as long as r<=5. <= is "less than or equal to" vs. < which is just "less than". So r will have the below values:
0, 1, 2, 3, 4, 5

Once r increments to 6, the condition is no longer true and the loop exits.


EDIT: ninja'd by giblit
Last edited on
thank you mr. giblit...this is not math 101..this is programming...i dont think is that obvious for a beginner...then why dont we just write...for(int r = 0; r!=5; r++) i understand and accept what you say...but i dont think is that obvious..it could as well be a special syntax for something special...this is not math but a programming language..could have meant anything
then why dont we just write...for(int r = 0; r!=5; r++)


You could. The only difference is that the loop will still run if r>5, whereas in the above form it wouldn't.

but i dont think is that obvious..it could as well be a special syntax for something special...this is not math but a programming language..could have meant anything


I don't know what you're complaining about. The language is the language. <= is pretty standard fare in all programming languages to mean "less than or equal to", so it is fairly obvious to anyone familiar with programming.
naa am just a lil bit pissed of someone is not understanding that am a beginner in programming and insulting my maths abilities as an engineering student lol :P ...anyway thank you guys..thank you
Topic archived. No new replies allowed.