©1994-2003 Kevin Boone
Home     Section index     K-Zone home C++ tutorial (under construction)

Site search

Glossary
Confused by computer jargon? Look it up!

Shameless plug


Now available!

Articles
- Ten-minute guide to setting up a WAP site

- Talk like your boss: new developments in managerese

More...

Development
File handling in the Linux kernel

Java development for the Sony-Ericsson P800

SunONE Application Server 7 FAQ

More...

Linux
Using Linux with the Treo 600

- Linux on the Tecra M1

- Some notes on openzaurus

More...

Download
Java stuff

Linux stuff

More...

(Please read the download policy)

Home automation
The X10 system

Linux TW723 driver

More...

The K-Zone
K-Zone computing

K-Zone law

K-Zone education and science

K-Zone motorcycles

K-Zone DIY

K-Zone railways

K-Zone martial arts

About the author

K-Zone home page

 
do
contents
if-then
C++ tutorial: for


A 'for' loop typically repeats a fixed number of times
The 'for' loop is similar to the while loop, but formalizes the sorts of operations that normally control a loop. The general structure of a 'for' loop is shown below:

for (start_statements; condition; loop_statements)
     {
     statment1;
     statment2;
	// more statements...
     }

'start_statements' is the set of statements that are executed before the loop begins. These typically define the variables used in the loop and their unitial values.
'condition' is the condition under which the loop will continue to run; this is exactly the same as the condition in 'while' loop.
'loop_statements' is the set of statements that is executed at the end of each turn of the loop.

This may sound complicated, but almost all practical uses of 'for' are for implementing a simple loop that executes a fixed number of times. The usual format of such a loop is:

for (int i = 1; i <= N; i++)
     {
     statment1;
     statment2;
	// more statements...
     }

This loop will repeat 'N' times, because it starts by setting 'i' to 1, and continues while 'i' is less than or equal to 'N'.

Exercise: re-write 'box1.cpp' so that it achieves the same result using a 'for' loop