Programming in C: For Loops

In the last tutorial we looked at if statements, today we will be looking at for loops. Loops are used to repeat a block of code.Being able to repeat a block of code multiple times is a very simple but very useful task in programming.

There are other kinds of loops in C, but for this tutorial we will be focusing only on using FOR loops. A for loop is the most useful type of loop, here is the general syntax:

for (variable_name = variable_value; condition; update variable)
{
 /* block of code to execute */
}

The first condition in the for loop statement allows you to initialize a variable, typically an integer which is used as a counter. The second statement is a condition that tells the loop if it should continue repeating or not, based on if the condition still evaluates to true. If the condition evaluates to false, the program will stop executing what is in the loop and move on to the next set of code. The third and final statement in the for loop usually updates the variable, in the case of a counter it may increment or decrement the value.

Here is an example of a for loop in a program, this program counts from 0 to 10 and prints out each value.

#include <stdio.h>

int main()
{
int x;

for (x = 0; x <= 10; x++) 
{
 printf( "%d\n", x );
}

 return 0;
}

More tutorials coming soon! Let me know how you like the tutorials by commenting below and if there is any specific topics or languages you would like covered. Follow me on Twitter to keep up-to-date on all the latest news and tutorials.

Apple's iBooks Textbooks and iTunes U Course Manager Now Available in Over 50 Countries

Programming in C: If Statements