Main Menu


Sponsored Links

  


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

The While Statement

Using a while statement, we can rewrite CountDown :

void CountDown ( int iN )

{

while ( iN > 0 )

{

ShowText ( iN );

iN = iN - 1;

}

ShowText ( "START!!!" );

}

You can almost read a while statement as if it were English. What this means is, “While iN is greater than zero, continue displaying the value of iN and then reducing the value of iN by 1. When you get to zero, output the word " START!!!"”.

More formally, the flow of execution for a while statement is as follows:

  1. Evaluate the condition in parentheses, yielding true or false.

  2. If the condition is false, exit the while statement and continue execution at the next statement.

  3. If the condition is true, execute each of the statements between the squiggly-braces, and then go back to step 1.

This type of flow is called a loop because the third step loops back around to the top. Notice that if the condition is false the first time through the loop, the statements inside the loop are never executed. The statements inside the loop are called the body of the loop.

The body of the loop should change the value of one or more variables so that, eventually, the condition becomes false and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop. An endless source of amusement for computer scientists is the observation that the directions on shampoo, “Lather, rinse, repeat,” are an infinite loop.

In the case of CountDown, we can prove that the loop will terminate because we know that the value of n is finite, and we can see that the value of iN gets smaller each time through the loop (each iteration), so eventually we have to get to zero. In other cases it is not so easy to tell.


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