1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Tutorial - Lesson Five - About Control Statements

By , About.com Guide

2 of 5

The For Loop

The For Loop

There are several ways of doing loops in C and c++. Most are found in C# as well.

This is the syntax of a for statement.

for ( initial statement; conditional expression; loop statement ) main statement;
Note This is the one place where there is no need to put brackets around a conditional expression.

This executes the initial statement once, then while the conditional expression is true, the loop statement and the main statement are executed.

All three sections are optional so the following is allowed. It is an infinite loop as the conditional expression is always true if absent.

for ( ;; ) mainstatement;
This will keep executing main statement for ever.

The conditional expression is the most important of the three sections. As long as it is true the main statement is always run. Once the expression is false, the loop exits.

for (index=1 ;index <= 10;index++ )
printf("The value of i is %i\n\r",i) ;
This outputs ten lines
The value of i is 1
The value of i is 2
..
The value of i is 10

index++ is shorthand for adding 1 to index. You could write index = index + 1 or index +=1 but index++ is more concise.

Beware

When processing a list or array you'll often write code where the first element is index 0. This code sums the array and prints the total of an array with 10 values in it.
int value =0;
for (index=0 ;index < 10;index++ )
value += numbers[ index ];
printf("Value = %i",value) ;
On the next page : Learn a quick way to exit a loop.
Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. The For Loop

©2009 About.com, a part of The New York Times Company.

All rights reserved.