For Loops

For loops are really great for running a loop multiple times but ending after a certain amount of runs. You add a counter variable which you increase every time you run through the loop and you set a condition which stops the loop from running more than you want it too. Let’s see an example code!

 

#include <stdio.h>
#include <stdlib.h>

int main(){
int i = 0;
for (i=0; i<=10, i; i++){ /* i can also be initialized in the for loop
 int i = 0 as the first condition. i++ indicates that i increases by a
 value of 1 when it reaches the loop repeats. Remember the middle condition
 is the one that stops i from counting. You can change this condition or 
 use any of the conditions from the if else loops*/
printf(“%i”, i);}
return 0;}
/*In your condition (in this case i<=10) you can change your parameters based
 on the starting position of i. For example try changing the initial value of
 i to another integer value and watch how the compiler handles that change. 
 Try something greater than 10 and something less than 10*/

Conclusion

Ugh finally nothing that you haven’t seen before… well almost. You will see that the console prints all values from 0-10 thus proving that the for loop cycles through for all times that i is less than or equal to 10 and equal to or greater than 0. This can also be good for running through multiple cases or repeating a process a certain number of times. To do that just make the statement inside the loop dependent upon the variable i.

 

Leave a comment