Sei sulla pagina 1di 18

Back to Bluesfear Digital Art

C++ - For Loops


Written by Gary Texmo Looping is probably one of the most important programming concepts in existence. There are so many applications of loops it would be impossible to list them all. To name a few though, things like parsing a string, trapping for errors, and animation. Also, since it will allow you to execute a block of code over and over, it saves time and typing. Now, depending on what kind of programming language you came from, loops might already be familiar to you, but if you've come from a low level programming language such as assembly or (god forbit) GWBasic, you are probably more familiar with jump or goto statements. Well, loops take into account all that lovely comparison crap you used to have to do before and puts it into one nice package. The easiest and most used of these loops is the for loop. The syntax of the for loop is as follows... for (var; condition; increment) for (var; condition; increment) { ... } Note the semi-colons between the different parts of the loop. If you are familiar with loops then you know that a counter variable is needed (obviously) to control your loop. Something to tell your loop how the hell to get out. There are ways to get out of a loop with no condition, but why make things more complicated than we really need to right? So, var is the name of our counter variable. Usually we would use an integer here, or perhaps a double type variable. You could probably get away with a char type, but I can't see much application in a string as a counter... not in a for loop anyways. Condition is the test to see if the loop should continue. If condition evaluates to true, the loop will execute once, then the increment (how much we modify the variable by) is incremented, and the condition tested once more. The condition is any boolean logic test as described in chapter I. Just so you can see a loop in action, here is a quick code excerpt to demonstrate. int i = 0; for (i; i < 10; i++) cout << i << endl;

Notice a few things. We start the loop by using i as our counter variable. Then we place a condition on loop execution. The loop will execute so long as the value of i remains less than 10. Lastly, our increment is i++ which means we want to add one to i each cycle through the loop. Now, a couple time savers in this process is that we can initialize our variable when we tell the loop which variable we are using as our counter variable. Also, a new addition for C++ over C is that we can define a variable on the fly to use as a counter. Something to be aware of though is that the scope of this variable is the loop itself. Although it appears that in some compilers the variable continues to exist after the loop even though has finished. Confusing yes? I thought so. Just assume that your variable goes out of scope and dies when your loop finishes if you've declared your counter within the loop. Another thing to note is that loops can be nested (one loop inside the other) just like if statements. Here are some more examples of loops. #include <iostream.h> int main(void) { cout << "First Loop" << endl << "----------" << endl; int x = 3; cout << "Initial value of x (before loop): " << x << endl << endl; for (x = 1; x < 42; x = x * 2) cout << "Inside loop, value of x: " << x << endl; cout << endl << "Final value of x (after loop): " << x << endl << endl; cout << "Second Loop" << endl << "-----------" << endl; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j += 1) for (int k = 0; k < 3; k = k + 1) cout << "[ " << i << " " << j << " " << k << " ]" << endl; } return 0;

output -----First Loop ---------Initial value of x (before loop): 3 Inside Inside Inside Inside Inside Inside loop, loop, loop, loop, loop, loop, value value value value value value of of of of of of x: x: x: x: x: x: 1 2 4 8 16 32

Final value of x (after loop): 64 Second Loop ----------[ 0 0 0 ] [ 0 0 1 ] [ 0 0 2 ]

[ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [

0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2

1 1 1 2 2 2 0 0 0 1 1 1 2 2 2 0 0 0 1 1 1 2 2 2

0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2

] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ]

Analyse this code and the output it generates and try to understand what happens. One thing to note is that the condition test of the for loop is always exeucted after the increment has been evaluated. This is why x takes the value of 64 at the end of the loop instead of keeping the last value it had inside the loop. Also, take note of the increment statement in the nested for loops. Each of these does exactly the same thing, increment the counter by one. It demonstrates the different arithmetic methods that can be used here. Lastly, I just want to bring to your attention that it is possible that a for loop will not execute even once. The condition is tested before the loop progresses so if your condition evaluates as false the first time through the loop, the block of code for the loop will not execute. Tutorial Info Written By: Gary Texmo a.k.a. Trinith Written For: Omicron of http://www.bluesfear.com

Back to Bluesfear Digital Art 2000, 2004 BlueSfear

the for statement


the for statement has the form:
for(initial_value,test_condition,step){ // code to execute inside loop };

initial_value sets up the initial value of the loop counter. test_condition this is the condition that is tested to see if the loop is executed again. step this describes how the counter is changed on each execution of the loop.

Here is an example:
// The following code adds together the numbers 1 through 10 // this variable keeps the running total int total=0; // this loop adds the numbers 1 through 10 to the variable total for (int i=1; i < 11; i++){ total = total + i; }

So in the preceding chunk of code we have:


initial_condition is int i=0; test_condition is i < 11; step is i++;

So, upon initial execution of the loop, the integer variable i is set to 1. The statement total = total + i; is executed and the value of the variable total becomes 1. The step code is now executed and i is incremented by 1, so its new value is 2. The test_condition is then checked, and since i is less than 11, the loop code is executed and the variable total gets the value 3 (since total was 1, and i was 2. i is then incremented by 1 again. The loop continues to execute until the condition i<11 fails. At that point total will have the value 1+2+3+4+5+6+7+8+9+10 = 55.

the while statement


The while statement has the form:
while(condition) { // code to execute };

condition is a boolean statement that is checked each time after the final "}" of the while statement executes. If the condition is true then the while statement executes again. If the condition is false, the while statement does not execute again.

As an example, let's say that we wanted to write all the even numbers between 11 and 23 to the screen. The following is a full C++ program that does that.
// include this file for cout #include <iostream.h> int main(){ // this variable holds the present number int current_number = 12; // while loop that prints all even numbers between // 11 and 23 to the screen while (current_number < 23){ cerr << current_number << endl; current_number += 2; } cerr << "all done" << endl; }

The preceding example prints the value of current_number to the screen and then adds 2 to its value. As soon as the value of the variable current_number goes above 23, the while loop exits and the next line is executed. The output of the preceding program would be:
12 14 16 18 20 22 all done

Control Structures
A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done by our program, when and under which circumstances. With the introduction of control structures we are going to have to introduce a new concept: the compound-statement or block. A block is a group of statements which are separated by semicolons (;) like all C++ statements, but grouped together in a block enclosed in braces: { }:

{ statement1; statement2; statement3; }


Most of the control structures that we will see in this section require a generic statement as part of its syntax. A statement can be either a simple statement (a simple instruction ending with a semicolon) or a compound statement (several instructions grouped in a block), like the one just described. In the case that we want the statement to be a simple statement, we do not need to enclose it in braces ({}). But in the case that we want the statement to be a compound statement it must be enclosed between braces ({}), forming a block.

Conditional structure: if and else


The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is:

if (condition) statement
Where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues right after this conditional structure. For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100:

1 if (x == 100) 2 cout << "x is 100";

If we want more than a single statement to be executed in case that the condition is true we can specify a block using braces { }:

1 if (x == 100) 2{ cout << "x is "; 3 cout << x; 4 } 5

We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword else. Its form used in conjunction with if is:

if (condition) statement1 else statement2


For example:

1 if (x == 100) 2 cout << "x is 100"; 3 else cout << "x is not 100"; 4

prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it prints out x is not 100. The if + else structures can be concatenated with the intention of verifying a range of values. The following example shows its use telling if the value currently stored in x is positive, negative or none of them (i.e. zero):

1 if (x > 0)

2 cout << "x 3 else if (x < 4 cout << "x else 5 cout << "x 6

is positive"; 0) is negative"; is 0";

Remember that in case that we want more than a single statement to be executed, we must group them in a block by enclosing them in braces { }.

Iteration structures (loops)


Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled.

The while loop


Its format is:

while (expression) statement


and its functionality is simply to repeat statement while the condition set in expression is true. For example, we are going to make a program to countdown using a while-loop:

1 // custom countdown using while Enter the starting number > 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE! 2 #include <iostream> 3 using namespace std; 4 5 int main () 6{ 7 int n; 8 cout << "Enter the starting number 9 > "; 10 cin >> n; 11 while (n>0) { 12 cout << n << ", "; 13 --n; 14 } 15 16 cout << "FIRE!\n"; 17 return 0; } 18 19

When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0)

remains being true. The whole process of the previous program can be interpreted according to the following script (beginning in main):

1. User assigns a value to n 2. The while condition is checked (n>0). At this point there are two possibilities:
* condition is true: statement is executed (to step 3) * condition is false: ignore statement and continue after it (to step 5)

3. Execute statement:
cout << n << ", "; --n; (prints the value of n on the screen and decreases n by 1)
4. 5. End of block. Return automatically to step 2 Continue the program right after the block: print FIRE! and end program.

When creating a while-loop, we must always consider that it has to end at some point, therefore we must provide within the block some method to force the condition to become false at some point, otherwise the loop will continue looping forever. In this case we have included --n; that decreases the value of the variable that is being evaluated in the condition (n) by one - this will eventually make the condition (n>0) to become false after a certain number of loop iterations: to be more specific, when n becomes 0, that is where our while-loop and our countdown end. Of course this is such a simple action for our computer that the whole countdown is performed instantly without any practical delay between numbers.

The do-while loop


Its format is:

do statement while (condition);


Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, the following example program echoes any number you enter until you enter 0.

1 // number echoer 2 3 #include <iostream> using namespace std; 4 5 int main () 6{ 7 unsigned long n; 8 do { cout << "Enter number (0 to end): 9 10 "; cin >> n; 11 cout << "You entered: " << n <<

Enter number You entered: Enter number You entered: Enter number You entered:

(0 to end): 12345 12345 (0 to end): 160277 160277 (0 to end): 0 0

12 "\n"; 13 } while (n != 0); 14 return 0; } 15

The do-while loop is usually used when the condition that has to determine the end of the loop is determined within the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end. In fact if you never enter the value 0 in the previous example you can be prompted for more numbers forever.

The for loop


Its format is:

for (initialization; condition; increase) statement;


and its main function is to repeat statement while condition remains true, like the while loop. But in addition, the for loop provides specific locations to contain an initialization statement and an

increase statement. So this loop is specially designed to perform a repetitive action with a counter
which is initialized and increased on each iteration. It works in the following way:

1. initialization is executed. Generally it is an initial value setting for a counter variable.


This is executed only once.

2. condition is checked. If it is true the loop continues, otherwise the loop ends and
statement is skipped (not executed).
braces { }.

3. statement is executed. As usual, it can be either a single statement or a block enclosed in 4. finally, whatever is specified in the increase field is executed and the loop gets back to step
2.

Here is an example of countdown using a for loop:

1 // countdown using a for loop 2 #include <iostream> 3 using namespace std; int main () 4 { 5 for (int n=10; n>0; n--) { 6 cout << n << ", "; 7 } 8 cout << "FIRE!\n"; 9 return 0; 10 } 11

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

The initialization and increase fields are optional. They can remain empty, but in all cases the semicolon signs between them must be written. For example we could write: for (;n<10;) if we wanted to specify no initialization and no increase; or for (;n<10;n++) if we wanted to include an increase field but no initialization (maybe because the variable was already initialized before). Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in a for loop, like in initialization, for example. The comma operator (,) is an expression separator, it serves to separate more than one expression where only one is generally expected. For example, suppose that we wanted to initialize more than one variable in our loop:

1 for ( n=0, i=100 ; n!=i ; n++, i-- ) 2{ // whatever here... 3 } 4

This loop will execute for 50 times if neither n or i are modified within the loop:

n starts with a value of 0, and i with 100, the condition is n!=i (that n is not equal to i). Because n is increased by one and i decreased by one, the loop's condition will become false after the 50th loop, when both n and i will be equal to 50.

Jump statements.
The break statement
Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end. For example, we are going to stop the count down before its natural end (maybe because of an engine check failure?):

1 // break loop example 2 3 #include <iostream> using namespace std; 4 5 int main () 6{ 7 int n; 8 for (n=10; n>0; n--) 9 { cout << n << ", "; 10

10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!

11 if (n==3) { 12 cout << "countdown aborted!"; 13 break; 14 } 15 } 16 return 0; 17 } 18 19

The continue statement


The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. For example, we are going to skip the number 5 in our countdown:

1 // continue loop example 2 #include <iostream> 3 using namespace std; 4 int main () 5{ 6 for (int n=10; n>0; n--) { 7 if (n==5) continue; cout << n << ", "; 8 9 } 10 cout << "FIRE!\n"; return 0; 11 } 12 13

10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!

The goto statement


goto allows to make an absolute jump to another point in the program. You should use this feature
with caution since its execution causes an unconditional jump ignoring any type of nesting limitations. The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:). Generally speaking, this instruction has no concrete use in structured or object oriented programming aside from those that low-level programming fans may find for it. For example, here is our countdown loop using goto:

1 // goto loop example 2 3 #include <iostream> using namespace std; 4 5 int main ()

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

6{ 7 8 9 10 11 12 13 } 14 15

int n=10; loop: cout << n << ", "; n--; if (n>0) goto loop; cout << "FIRE!\n"; return 0;

The exit function


exit is a function defined in the cstdlib library.
The purpose of exit is to terminate the current program with a specific exit code. Its prototype is:

void exit (int exitcode);

The exitcode is used by some operating systems and may be used by calling programs. By convention, an exit code of 0 means that the program finished normally and any other value means that some error or unexpected results happened.

The selective structure: switch.


The syntax of the switch statement is a bit peculiar. Its objective is to check several possible constant values for an expression. Something similar to what we did at the beginning of this section with the concatenation of several if and else if instructions. Its form is the following:

switch (expression) { case constant1: group of statements 1; break; case constant2: group of statements 2; break; . . . default: default group of statements }
It works in the following way: switch evaluates expression and checks if it is equivalent to

constant1, if it is, it executes group of statements 1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure.

If expression was not equal to constant1 it will be checked against constant2. If it is equal to this, it will execute group of statements 2 until a break keyword is found, and then will jump to the end of the switch selective structure. Finally, if the value of expression did not match any of the previously specified constants (you can include as many case labels as values you want to check), the program will execute the statements included after the default: label, if it exists (since it is optional). Both of the following code fragments have the same behavior: switch example if-else equivalent

switch (x) { if (x == 1) { case 1: cout << "x is 1"; cout << "x is 1"; } break; else if (x == 2) { case 2: cout << "x is 2"; cout << "x is 2"; } break; else { default: cout << "value of x unknown"; cout << "value of x unknown"; } }
The switch statement is a bit peculiar within the C++ language because it uses labels instead of blocks. This forces us to put break statements after the group of statements that we want to be executed for a specific condition. Otherwise the remainder statements -including those corresponding to other labels- will also be executed until the end of the switch selective block or a break statement is reached. For example, if we did not include a break statement after the first group for case one, the program will not automatically jump to the end of the switch selective block and it would continue executing the rest of statements until it reaches either a break instruction or the end of the switch selective block. This makes it unnecessary to include braces { } surrounding the statements for each of the cases, and it can also be useful to execute the same block of instructions for different possible values for the expression being evaluated. For example:

1 switch (x) { 2 case 1: 3 case 2: case 3: 4 cout << "x is 1, 2 or 3"; 5 break; 6 default: 7 cout << "x is not 1, 2 nor 3"; 8 } 9

Notice that switch can only be used to compare an expression against constants. Therefore we cannot put variables as labels (for example case n: where n is a variable) or ranges (case (1..3):) because they are not valid C++ constants.

If you need to check ranges or values that are not constants, use a concatenation of if and else if statements

Loops are used to repeat a block of code. Being able to have your program repeatedly execute a block of code is one of the most basic but useful tasks in programming -- many programs or websites that produce extremely complex output (such as a message board) are really only executing a single task many times. (They may be executing a small number of tasks, but in principle, to produce a list of messages only requires repeating the operation of reading in some data and displaying it.) Now, think about what this means: a loop lets you write a very simple statement to produce a significantly greater result simply by repetition.

One Caveat: before going further, you should understand the concept of C++'s true and false, because it will be necessary when working with loops (the conditions are the same as with if statements). There are three types of loops: for, while, and do..while. Each of them has their specific uses. They are all outlined below. FOR - for loops are the most useful type. The syntax for a for loop is

for ( variable initialization; condition; variable update ) { Code to execute while the condition is true } The variable initialization allows you to either declare a variable and give it a value or give a value to an already existing variable. Second, the condition tells the program that while the conditional expression is true the loop should continue to repeat itself. The variable update section is the easiest way for a for loop to handle changing of the variable. It is possible to do things like x++, x = x + 10, or even x = random ( 5 ), and if you really wanted to, you could call other functions that do nothing to the variable but still have a useful effect on the code. Notice that a semicolon separates each of these sections, that is important. Also note that every single one of the sections may be empty, though the semicolons still have to be there. If the condition is empty, it is evaluated as true and the loop will repeat until something else stops it. Example:

#include <iostream> using namespace std; // So the program can see cout and endl int main() { // The loop goes while x < 10, and x increases by one every loop for ( int x = 0; x < 10; x++ ) { // Keep in mind that the loop condition checks // the conditional statement before it loops again. // consequently, when x equals 10 the loop breaks. // x is updated before the condition is checked. cout<< x <<endl; } cin.get(); } This program is a very simple example of a for loop. x is set to zero, while x is less than 10 it calls cout<< x <<endl; and it adds 1 to x until the condition is met. Keep in mind also that the variable is incremented after the code in the loop is run for the first time. WHILE - WHILE loops are very simple. The basic structure is while ( condition ) { Code to execute while the condition is true } The true represents a boolean expression which could be x == 1 or while ( x != 7 ) (x does not equal 7). It can be any combination of boolean statements that are legal. Even, (while x ==5 || v == 7) which says execute the code while x equals five or while v equals 7. Notice that a while loop is the same as a for loop without the initialization and update sections. However, an empty condition is not legal for a while loop as it is with a for loop. Example: #include <iostream> using namespace std; // So we can see cout and endl int main() { int x = 0;

// Don't forget to declare variables

while ( x < 10 ) { // While x is less than 10 cout<< x <<endl; x++; // Update x so the condition can be met eventually } cin.get(); } This was another simple example, but it is longer than the above FOR loop. The easiest way to think of the loop is that when it reaches the brace at the end it jumps back up to the beginning of the loop, which checks the condition again and decides whether to repeat the block another time, or stop and move to the next statement after the block. DO..WHILE - DO..WHILE loops are useful for things that want to loop at least once. The structure is do { } while ( condition ); Notice that the condition is tested at the end of the block instead of the beginning, so the block will be executed at least once. If the condition is true, we jump back to the beginning of the block and

execute it again. A do..while loop is basically a reversed while loop. A while loop says "Loop while the condition is true, and execute this block of code", a do..while loop says "Execute this block of code, and loop while the condition is true". Example: #include <iostream> using namespace std; int main() { int x; x = 0; do { // "Hello, world!" is printed at least one time // even though the condition is false cout<<"Hello, world!\n"; } while ( x != 0 ); cin.get(); } Keep in mind that you must include a trailing semi-colon after the while in the above example. A common error is to forget that a do..while loop must be terminated with a semicolon (the other loops should not be terminated with a semicolon, adding to the confusion). Notice that this loop will execute once, because it automatically executes before checking the condition.

Loops are basically means to do a task multiple times, without actually coding all statements over and over again. For example, loops can be used for displaying a string many times, for counting numbers and of course for displaying menus. Loops in C++ are mainly of three types :1. 'while' loop 2. 'do while' loop 3. 'for' loop For those who have studied C or JAVA, this isn't very new, as the syntax for the loops are exactly same. So if you know the above languages, don't waste your time understanding loop syntax in C++. The 'while' loop :Let me show you a small example of a program which writes ABC three(3) times.

#include<iostream> int main() { int i=0; while(i<3) { i++; cout<<"ABC"<<endl;

The output of the above code will be :ABC ABC ABC A point to notice here is that, for making it more easy to understand, we could also write,

int i=1; while(i<=3)

This would make our code more easy for a newbie, but in actuality it doesn't make a difference either way. The 'do while' loop :It is very similar to the 'while' loop shown above. The only difference being, in a 'while' loop, the condition is checked beforehand, but in a 'do while' loop, the condition is checked after one execution of the loop. Example code for the same problem using a 'do while' loop would be :-

#include <iostream> int main() { int i=0; do { i++; cout<<"ABC"<<endl; }while(i<3); }

The output would once again be same as in the above example. The 'for' loop :This is probably the most useful and the most used loop in C/C++. The syntax is slightly more complicated than that of 'while' or the 'do while' loop. The general syntax can be defined as :for(<initial value>;<condition>;<increment>) To further explain the above code, we will take an example. Suppose we had to print the numbers 1 to 5, using a 'for' loop. The code for this would be :-

#include<iostream> int main() { for(inti=1;i<=5;i++) cout<<i<<endl;

The output for this code would be :1 2 3 4 5 Here variable 'i' is given an initial value of 1. The condition applied is till 'i' is less than or equal to 5. And for each iteration, the value of 'i' is also incremented by 1. Notice here that if we wanted to print, 5 4 3 2 1 we would change our 'for' loop to :-

for(int i=5;i>=1;i--)

This is a very brief introduction to loops in C++. Hope it helped. A few reference books that I would suggest are :1. Object Oriented Programming using C++ By E Balagurusamy Tata McGraw Hill

Potrebbero piacerti anche