Main Menu


Sponsored Links

  


  
  
Web Cartoon Maker: a Fun Way to Learn C++ Contents Previous Next

For Loops

The while loop we were using above have three elements common for most of the loops.

  1. Most of them start by initializing a variable. We used a parameter variable called iN in CountDown , which is obviously initialized during the function call.

  2. Most of them have a test, or condition, that depends on that variable

  3. Inside the loop most of them do something to that variable, like increment or decrement it.

This type of loop is so common that there is an alternate loop statement, called for , that expresses it more concisely. The general syntax looks like this:

for ( INITIALIZER; CONDITION; INCREMENTOR )

{

BODY

}

This statement is exactly equivalent to

INITIALIZER;

while ( CONDITION )

{

BODY

INCREMENTOR

}

except that it is more concise and, since it puts all the loop-related statements in one place, it is easier to read. For example:

for ( int i = 0; i < 4 ; i++ )

{

ShowText ( i );

}

is equivalent to

int i = 0;

while ( i < 4 )

{

ShowText ( i );

i++;

}

You may notice that I used an integer variable called i in the example above. It is common to use simple variable names like i , j , k and so on in for loops. It is also possible to have embedded loops like this:

for ( int i = 0; i < 4 ; i++ )

{

for ( int j = 0; j < 3 ; j++ )

{

ShowText ( i * j );

}

}

Historical Note: The i, j, k convention actually came from the first commercial high level scientific language, Fortran 2. (Fortran 1 was what we would now call “beta” software.) In Fortran 2 all integer variables, and only integer s had to begin with i, j, or k.


Contents Previous Next
  
News

New Tales Animator Video by Alan Sturgess

Alan Sturgess shared an excellent video he made using Tales Animator! You can still download Tales Animator here. Unfortunately it is only available for Wi

...

Simple Online Character Designer

There is a prototype of simple online character designer available HERE. It is only a prototype, it does not contain many pieces yet but it can already generat

...

Book is updated

Now our book "Web Cartoon Maker: A Fun Way to Learn C++" is fully in synch with WCM 1.5! It is available for download and online reading HERE.

...

Web Cartoon Maker 1.5 is here!

Web Cartoon Maker 1.5 is finally here! You can download it HERE! Here is what was updated in version 1.5: Web Cartoon Maker Desktop Edition is now fully standal

...

read more news...


Poll