Understanding Loops in C++: for, while, and do, Exams of Computer Science

The concept of loops in c++ programming language, focusing on the for, while, and do loops. It covers the operation of each loop type, including initialization, test, and increment expressions, and provides examples. The document also discusses the advantages of using each loop type in specific scenarios.

Typology: Exams

2015/2016

Uploaded on 01/30/2016

hamza_malik
hamza_malik 🇬🇧

2 documents

1 / 4

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Loops
Loops cause a section of your program to be repeated a certain number of times. The
repetition
continues while a condition is true. When the condition becomes false, the loop ends and
control
passes to the statements following the loop.
There are three kinds of loops in C++: the for loop, the while loop, and the do loop.
The for Loop
The for loop is (for many people, anyway) the easiest C++ loop to understand. All its
loopcontrol
elements are gathered in one place, while in the other loop constructions they are scattered
about the program, which can make it harder to unravel how these loops work.
The for loop executes a section of code a xed number of times. It’s usually (although not
always) used when you know, before entering the loop, how many times you want to
execute
the code.
The Initialization Expression
The initialization expression is executed only once, when the loop rst starts. It gives the
loop
variable an initial value. In the FORDEMO example it sets j to 0.
The Test Expression
The test expression usually involves a relational operator. It is evaluated each time through
the
loop, just before the body of the loop is executed. It determines whether the loop will be
executed
again. If the test expression is true, the loop is executed one more time. If it’s false, the
loop ends, and control passes to the statements following the loop. In the FORDEMO example
the
statement
cout << endl;
is executed following the completion of the loop.
The Increment Expression
The increment expression changes the value of the loop variable, often by incrementing it. It
is
always executed at the end of the loop, after the loop body has been executed. Here the
increment
operator ++ adds 1 to j each time through the loop. Figure 3.2 shows a owchart of a for
loop’s operation.
How Many Times?
The loop in the FORDEMO example executes exactly 15 times. The rst time, j is 0. This is
ensured in the initialization expression. The last time through the loop, j is 14. This is
determined
by the test expression j<15. When j becomes 15, the loop terminates; the loop body is
not executed when j has this value. The arrangement shown is commonly used to do
something
a xed number of times: start at 0, use a test expression with the less-than operator and a
value equal to the desired number of iterations, and increment the loop variable after each
iteration.
Chapter 3
80
for Loop Variations
pf3
pf4

Partial preview of the text

Download Understanding Loops in C++: for, while, and do and more Exams Computer Science in PDF only on Docsity!

Loops

Loops cause a section of your program to be repeated a certain number of times. The repetition continues while a condition is true. When the condition becomes false, the loop ends and control passes to the statements following the loop. There are three kinds of loops in C++: the for loop, the while loop, and the do loop.

The for Loop

The for loop is (for many people, anyway) the easiest C++ loop to understand. All its loopcontrol elements are gathered in one place, while in the other loop constructions they are scattered about the program, which can make it harder to unravel how these loops work. The for loop executes a section of code a fixed number of times. It’s usually (although not always) used when you know, before entering the loop, how many times you want to execute the code.

The Initialization Expression

The initialization expression is executed only once, when the loop first starts. It gives the loop variable an initial value. In the FORDEMO example it sets j to 0.

The Test Expression

The test expression usually involves a relational operator. It is evaluated each time through the loop, just before the body of the loop is executed. It determines whether the loop will be executed again. If the test expression is true, the loop is executed one more time. If it’s false, the loop ends, and control passes to the statements following the loop. In the FORDEMO example the statement cout << endl; is executed following the completion of the loop.

The Increment Expression

The increment expression changes the value of the loop variable, often by incrementing it. It is always executed at the end of the loop, after the loop body has been executed. Here the increment operator ++ adds 1 to j each time through the loop. Figure 3.2 shows a flowchart of a for loop’s operation.

How Many Times?

The loop in the FORDEMO example executes exactly 15 times. The first time, j is 0. This is ensured in the initialization expression. The last time through the loop, j is 14. This is determined by the test expression j<15. When j becomes 15, the loop terminates; the loop body is not executed when j has this value. The arrangement shown is commonly used to do something a fixed number of times: start at 0, use a test expression with the less-than operator and a value equal to the desired number of iterations, and increment the loop variable after each iteration. Chapter 3 80

for Loop Variations

The increment expression doesn’t need to increment the loop variable; it can perform any operation it likes. In the next example it decrements the loop variable. This program, FACTOR , asks the user to type in a number, and then calculates the factorial of this number. (The factorial is calculated by multiplying the original number by all the positive integers smaller than itself. Thus the factorial of 5 is 54321, or 120.) // factor.cpp // calculates factorials, demonstrates FOR loop #include using namespace std; int main() { unsigned int numb; unsigned long fact=1; //long for larger numbers cout << “Enter a number: “; cin >> numb; //get number

for(int j=numb; j>0; j--) //multiply 1 by fact *= j; //numb, numb-1, ..., 2, 1 cout << “Factorial is “ << fact << endl; return 0; } In this example the initialization expression sets j to the value entered by the user. The test expression causes the loop to execute as long as j is greater than 0. The increment expression decrements j after each iteration. We’ve used type unsigned long for the factorial, since the factorials of even small numbers are very large. On 32-bit systems such as Windows int is the same as long , but long gives added capacity on 16-bit systems. The following output shows how large factorials can be, even for small input numbers: Enter a number: 10 Factorial is 3628800 The largest number you can use for input is 12. You won’t get an error message for larger inputs, but the results will be wrong, as the capacity of type long will be exceeded.

Variables Defined in for Statements

There’s another wrinkle in this program: The loop variable j is defined inside the for statement: for(int j=numb; j>0; j--) This is a common construction in C++, and in most cases it’s the best approach to loop variables. It defines the variable as closely as possible to its point of use in the listing. Variables defined in the loop statement this way are visible in the loop body only. (The Microsoft compiler makes them visible from the point of definition onward to the end of the file, but this is not Standard C++.)

Multiple Initialization and Test Expressions

You can put more than one expression in the initialization part of the for statement, separating the different expressions by commas. You can also have more than one increment expression. You can have only one test expression. Here’s an example: for( j=0, alpha=100; j<50; j++, beta-- ) { // body of loop } This example has a normal loop variable j, but it also initializes another variable, alpha, and decrements a third, beta. The variables alpha and beta don’t need to have anything to do with

cout << “Enter divisor: “; cin >> divisor; cout << “Quotient is “ << dividend / divisor; cout << “, remainder is “ << dividend % divisor; cout << “\nDo another? (y/n): “; //do it again? cin >> ch; } while( ch != ‘n’ ); //loop condition return 0; } Most of this program resides within the do loop. First, the keyword do marks the beginning of the loop. Then, as with the other loops, braces delimit the body of the loop. Finally, a while statement provides the test expression and terminates the loop. This while statement looks much like the one in a while loop, except for its position at the end of the loop and the fact that it ends with a semicolon (which is easy to forget!).

When to Use Which Loop

We’ve made some general statements about how loops are used. The for loop is appropriate when you know in advance how many times the loop will be executed. The while and do loops are used when you don’t know in advance when the loop will terminate (the while loop when you may not want to execute the loop body even once, and the do loop when you’re sure you want to execute the loop body at least once). These criteria are somewhat arbitrary. Which loop type to use is more a matter of style than of hard-and-fast rules. You can actually make any of the loop types work in almost any situation. You should choose the type that makes your program the clearest and easiest to follow.

Decisions

The decisions in a loop always relate to the same question: Should we do this (the loop body) again? As humans we would find it boring to be so limited in our decision-making processes. We need to decide not only whether to go to work again today (continuing the loop), but also whether to buy a red shirt or a green one (or no shirt at all), whether to take a vacation, and if so, in the mountains or by the sea. Programs also need to make these one-time decisions. In a program a decision causes a onetime jump to a different part of the program, depending on the value of an expression.

Decisions can be made in C++ in several ways. The most important is with the if...else statement, which chooses between two alternatives. This statement can be used without the else, as a simple if statement. Another decision statement, switch , creates branches for multiple alternative sections of code, depending on the value of a single variable. Finally, the conditional operator is used in specialized situations. We’ll examine each of these constructions.