C Loops


C++ Loops

The following table lists C++ loops and shows how they relate to Delphi loops. Notice the C++ for loop.

Table 4-1: C++ and Delphi loops

C++ Loop

Works Like Delphi Loop

while

while

do-while

repeat-until

for

for, while

The while Loop

The while loop in C++ works exactly as it does in Delphi: It executes a statement or a block of statements as long as the condition is True. The while loop tests the condition before executing its statements, and if the condition evaluates to False at the beginning, the statements never get executed.

The only notable difference between the two languages lies in syntax. Here's the syntax of the C++ while loop:

while (condition) statement; while (condition) {    statements; }

The following example shows how to display the first 20 numbers with the while loop.

Listing 4-14: The while loop

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int x=0;    while(++x <= 20)       cout << x << endl;    getch();    return 0; }
image from book

The do-while Loop

The do-while loop in C++ is the equivalent of the repeat-until loop in Delphi, which means that it executes its statements at least once and continues to do so until the condition is met. The syntax of the do-while loop is:

do    statement while (condition); do {    statements; } while (condition); 

The following example uses the do-while loop to display the first 20 numbers.

Listing 4-15: The do-while loop

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int x = 0;    do       cout << ++x << endl;    while (x < 20);    getch();    return 0; }
image from book

The for Loop

Depending on how it is written, the for loop in C++ can work like a for or a while loop in Delphi. The syntax of the for loop is:

for (initialization; condition; condition_update)    statement;

The initialization part is used to initialize the loop's counter. The condition is an expression that gets evaluated before the statements are executed, which means that the statements of the for loop are not executed if the condition evaluates to False at the beginning. The condition_update part is an expression called after each iteration to update the loop's counter.

For instance, the for loop in Listing 4-16 displays all lowercase letters of the alphabet. The loop works by setting the letter 'a' (characters in C++ are written inside single quote marks, as they are in Delphi) as the beginning letter in the initialization section and by setting the char <= 'z' condition in the condition part to make the for loop iterate as long as the Char variable contains any of the lowercase letters of the alphabet. The condition_update part updates the condition by incrementing the Char variable by one at each iteration.

Listing 4-16: A simple for loop

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    char ch;    for(ch = 'a'; ch <= 'z'; ch++)       cout << ch;    getch();    return 0; }
image from book

Unlike the Delphi for loop, which allows you to increase or decrease the value of the counter variable by 1, the for loop in C++ allows you to increase or decrease the counter variable by whatever you like. For instance, the for loop in Listing 4-17 outputs only odd numbers to the console by setting the counter to 1 in the initialization part and then incrementing the counter variable by
2.

Listing 4-17: Using compound operators in the for loop

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int i;    for(i=1; i<20; i+=2)       cout << i << endl;    getch();    return 0; }
image from book

The for-downto Loop

To create a for-downto loop in C++, you only have to rewrite the condition_update part of the loop to decrement the counter variable. Listing 4-18 shows how to write a for-downto loop in C++.

Listing 4-18: A C++ for-downto loop

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int i;    for(i=20; i>0; i--)       cout << i << endl;    getch();    return 0; }
image from book

The while-like for Loop

The for loop in C++ can very easily be written to act just like the while loop — to repeat statements as long as a condition is True. For instance, the following for loop enables the user to enter an integer value and calculates the square of the entered number. The loop repeats this action until the user enters 0.

This for loop has only the condition part. Both the intialization and condition_update parts are empty. The initialization part is empty because the counter variable is initialized in the declaration, and the condition_update part is empty because the counter variable (the condition) is updated in the loop's block.

Listing 4-19: A weird-looking for loop

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int i=1;    for(; i!=0; )    {       cout << "Enter a number (or 0 to exit): ";       cin >> i; // this reads the user input and updates the condition       if(i != 0)         cout << "The square of your number is " << i*i << endl << endl;    }    cout << "Thank you. Press any key to continue..." << endl;    getch();    return 0; }
image from book

The Infinite for Loop

To write an infinite for loop in C++, simply omit all three parts of the for statement. To terminate the loop, use the reserved word break. The following example shows how to display numbers from 1 to 10 with an infinite loop.

Listing 4-20: An infinite for loop

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int i = 1;    for( ; ; ) {       cout << i << endl;       if (i++ == 10) break;    }    getch();    return 0; }
image from book

The Strange for Loop

The for loop in the C++ language has two more characteristics:

  • It supports multiple expressions in the initialization, condition, and condition_update parts (the expressions must be comma delimited).

  • Because of the aforementioned characteristic, it can perform useful tasks without having to execute additional statements in its block.

The example that follows is an updated version of the example in Listing 4-19, which allows the user to enter integer values and displays these values squared until the user enters 0. The initialization part of the for loop is empty, the condition part keeps the loop working as long as i != 0, and everything else (input and output of values) is done in the final section of the loop.

Note the semicolon with which the for loop is ended. When a semicolon is placed immediately after the loop, without additional statements, it means that the loop should do nothing.

Listing 4-21: A pretty unusual for loop

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int i=1;    cout << "Enter 0 to exit..." << endl << endl;    for( ; i != 0;  cout << "Number: ",     cin >> i, cout << "Squared = " << i*i <<  endl) ;    cout << "Finished. Press any key to continue...";    getch();    return 0; }
image from book

image from book
Figure 4-6: The result of the strange loop from Listing 4-21

Declaring a Dedicated Counter Variable

In Delphi you can only use a simple local variable as the counter variable in a for loop. In C++, you can use a local variable for the counter, as we've done, or you can declare the counter variable inside the for loop. Such a variable only exists as long as the for loop is executing and can only be used by the for loop and the statements in the for loop's block. The counter variable is declared in the initialization part of the for loop:

for(data_type var_name = init_value; condition; condition_update)

Listing 4-22 shows how to declare a counter variable in the for loop and shows where this variable can and cannot be used.

Listing 4-22: Declaring a counter variable in the for loop

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    /* i cannot be used before the loop */    for(int i=0; i<20; i++)    {       cout << i+1 << endl;    } // i is destroyed here    /* i cannot be used after the loop */    getch();    return 0; }
image from book



Inside Delphi 2006
Inside Delphi 2006 (Wordware Delphi Developers Library)
ISBN: 1598220039
EAN: 2147483647
Year: 2004
Pages: 212
Authors: Ivan Hladni

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net