Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Loops:

The Increment and Decrement Operators


++ is the increment operator.

It adds one to a variable.


val++; is the same as val = val + 1;
++ can be used before (prefix) or after (postfix) a variable:
++val; val++;

-- is the decrement operator.

It subtracts one from a variable.


val--; is the same as val = val - 1;
-- can be also used before (prefix) or after (postfix) a variable:
--val; val--;

Can be used in expressions:


result = num1++ + --num2;
Must be applied to something that has a location in memory. Cannot have:
result = (num1 + num2)++;
Can be used in relational expressions:
if (++num > limit)
pre- and post-operations will cause different comparisons

Prefix vs. Postfix


++ and -- operators can be used in complex statements and expressions
In prefix mode (++val, --val) the operator increments or
decrements, then returns the value of the variable
In postfix mode (val++, val--) the operator returns the value of
the variable, then increments or decrements

1
int num, val = 12;
cout << val++; // displays 12,
// val is now 13;
cout << ++val; // sets val to 14,
// then displays it
num = --val; // sets val to 13,
// stores 13 in num
num = val--; // stores 13 in num,
// sets val to 12

Note: if val = 12

then val = ++val + 10 yields a final value of val = 23 //prefix mode

but val = val++ + 10 yields a final value of val = 22 //postfix mode

Introduction to Loops:
Loop: a control structure that causes a statement or statements to repeat
Types:
 while
 do-while
 for

The while Loop


General format of the while loop:
while (expression)
statement;
statement; can also be a block of statements enclosed in { }
Pretest Loop - expression is evaluated BEFORE the loop executes

expression is evaluated
 if TRUE then statement is executed, and expression is
evaluated AGAIN

2
 if FALSE then the loop is finished and program statements following
statement execute

The Logic of a while Loop

Prog 1:

3
Flowchart of the while Loop

//Following loop body NEVER executes

int number = 6; expression is FALSE, since number is already greater


while (number <= 5) than 5, loop body DOES NOT execute
{ while loop body
cout << "Hello\n";
number++;

4
Watch Out for Infinite Loops
The loop must contain code to make expression become false

Otherwise, the loop will have no way of stopping

Such a loop is called an infinite loop, because it will repeat an


infinite number of times

//Example of Infinite loop

int number = 1;
expression is forever TRUE, since
number is always to 1
while (number <= 5)
{ Loop body keeps displaying “Hello “
cout << "Hello\n"; infinite number of times.
}

Using the while Loop for Input Validation


Input validation is the process of inspecting data that is given to the
program as input and determining whether it is valid.

The while loop can be used to create input routines that reject invalid
data, and repeat until valid data is entered.

pseudocode for checking invalid data

Read an item of input


While ( the input is invalid )

{
Display an error message.
Read the input again.
}// end while

5
//Example of Input validation

cout << "Enter a number less than 10:";


cin >> number; Check if input is invalid.
If number is NOT less than 10 then
while (number >= 10)
{ the loop displays error message
cout << "Invalid Entry!" “Invalid Entry “ and prompts user
<< "Enter a number less than 10:"; to enter another number

cin >> number;//prompts user to input again


} //end while

Flowchart for user Input Validation

6
Prog 2

7
Counters (check Prog1 above)
Counter: a variable that is incremented or decremented each time a
loop repeats

Can be used to control execution of the loop (also known as the loop
control variable)

Must be initialized BEFORE entering loop

counter = 1; //initialization
while(counter <=10) //test
{ .
. //repeated actions
.
counter++; //update variable

The do-while Loop


Posttest loop – execute the loop, then test the expression
Loop always executes at least ONCE

Execution continues as long as expression is true, stops repetition


when expression becomes false

Useful in menu-driven programs to bring user back to menu to make


another choice

General Format:
do
statement; // or block in { }
while (expression);

Note that a semicolon is required after (expression)

8
The Logic of a do-while Loop

Example do-while Loop


int x = 1;
do
{
cout << x << endl; Checks if variable x is negative. Although the test
} while(x < 0); expression is false, this loop will still execute ONE time
because do-while is posttest loop.

9
Prog 3

10
The for Loop
Counter-controlled loop
Pretest loop -tests its expression BEFORE each iteration

General Format:
for(initialization; test condition; update)
statement; // or block in { }

1) Perform initialization
2) Evaluate test expression
If true, execute statement
If false, terminate loop execution
3) Execute update, then re-evaluate test expression

NO semicolon after the update expression or after the )

An Example: for Loop

Step 1: Perform initialization


int count;
Step 2: Evaluate test expression , if TRUE go to step 3.Otherwise terminate the loop

Step 4: Perform update expression , then go back to Step 2

for (count = 1; count <= 5; count++)


{
cout << "Hello" << endl;
}
Step 3: Execute the body of the loop

11
Flowchart demonstrating for loop

//Following for loop will NEVER iterate as test


//condition fails

for (count = 11; count <= 10; count++)


cout << "Hello" << endl;
Prog 4

12
When to Use the for Loop
In any situation that clearly requires
an initialization
a false condition to stop the loop
an update to occur at the end of each iteration

for Loop – Variations

You can have multiple statements in the initialization expression. Separate


the statements with a comma: initialization expressions
int x, y;
for( x = 1, y = 1 ; x <= 5; x++)
{
cout << x <<" + "<< y << "= " <<(x + y)<< endl;
}

You can also have multiple statements in the update expression. Separate
the statements with a comma:
update expressions

int x, y;
for (x = 1, y = 1; x <= 5; x++, y++ )
{
cout << x <<" +" << y<< "= " <<(x + y)<< endl;

13
You can omit the initialization expression if it has already been
done:
int sum = 0, num = 1;
for (; num <= 10; num++)
sum += num;

You can declare variables in the initialization expression:


int sum = 0;
for (int num = 0; num <= 10; num++)
sum += num;
The scope of the variable num is the for loop.

If the loop-condition in a for loop is omitted, it is implicitly true.


Infinite loop - for (; ;){ while(true){
Do something Do something
} }

Keeping a Running Total


Running total: accumulated sum of numbers from each repetition of
loop
Accumulator: variable that holds running total, needs to be initialized
before used

int sum = 0, num = 1; // sum is the accumulator


while (num <= 10)
{ sum += num;
num++;
}
cout <<" Sum of numbers 1-10 is” << sum << endl;

14
Logic for Keeping a Running Total

Sentinels
sentinel: value in a list of values that indicates end of data
Special value that cannot be confused with a valid value, e.g., -999
for a test score
Used to terminate input when user may not know how many values
will be entered
Prog 5

15
Deciding Which Loop to Use
The while loop is a conditional pretest loop
Iterates as long as a certain condition exists
Validating input
Reading lists of data terminated by a sentinel

The do-while loop is a conditional posttest loop


Always iterates at least once
Repeating a menu

The for loop is a pretest loop


Built-in expressions for initializing, testing, and updating
Situations where the exact number of iterations is known

Nested Loops
A nested loop is a loop inside the body of another loop

Inner loop goes through all repetitions for each repetition of outer loop

Inner loop repetitions complete sooner than outer loop

16
Total number of repetitions for inner loop is product of number of
repetitions of the two loops.

Prog 6

17
Breaking Out of a Loop

Can use break to terminate execution of a loop


When used in an inner loop, terminates that loop only and goes back
to outer loop
Use sparingly if at all – makes code harder to understand and debug

int sum = 0, num = 0;


while (num < 15){
num++;
sum += num;
if (sum >= 80 )
break;// exits the while block
}//end while

cout << “ The sum is: “ << sum;

The continue Statement

Can use continue to go to end of loop and prepare for next


repetition
while, do-while loops: go to test, repeat loop if test
passes
for loop: perform update step, then test, then repeat
loop if test passes
Use sparingly, can make program logic hard to follow:
int sum = 0, num = 0;

while (num < 15){


num++;

if (num == 5 || num == 6 )
continue;//skips to the end of loop, starts new iteration
sum += num;

}//end while

cout << “ The sum is: “ << sum;

18
Prog 7

19

You might also like