GreenSalamanderCS's post

Creating a Loop

With most programming languages, there are two general types of loops:

 

> For Loop

> While Loop

 

The for loop has a starting point, a finish condition & a step, like the following generic syntax:

> for (int i = 0; i < 10; i++) 

In the above for loop, using the C programming language, "int i = 0" is the starting point. The loop begins with "i" being set to 0. "i < 10" tells the loop to terminate when the value of "i" = 10. "i++" is shorthand form for telling the loop to increment by 1 each time. 

So inside the for loop, if we were to print "Hello" inside that for loop, it would print 10 times, like this:

Hello

Hello

Hello

Hello

Hello

Hello

Hello

Hello

Hello

Hello

 

Conversely, the while loop can have any condition inside of it & any code running inside the while loop will run until the condition for that while loop is no longer met. 

Say we have a while loop which had the following condition: while (i < 10) & we had a printf("Hello") & "i++" inside the while loop. The code will continue to run repeatedly until "i" is 10, then the loop will stop. The while loop is preferred if you are unsure of how many times the code will run.

More from GreenSalamanderCS