0% found this document useful (0 votes)
3 views

CHAPTER-4

Chapter 4 discusses looping in C++, covering three types of loops: while, do-while, and for loops, each with distinct control mechanisms for repetition. It explains the structure, usage, and examples of each loop type, including how to terminate loops, use counters, and implement nested loops. Additionally, it introduces control statements like break and continue, and emphasizes the importance of loops in data validation.

Uploaded by

atakilti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

CHAPTER-4

Chapter 4 discusses looping in C++, covering three types of loops: while, do-while, and for loops, each with distinct control mechanisms for repetition. It explains the structure, usage, and examples of each loop type, including how to terminate loops, use counters, and implement nested loops. Additionally, it introduces control statements like break and continue, and emphasizes the importance of loops in data validation.

Uploaded by

atakilti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 34

CHAPTER 4

LOOPING
Introduction to Loops
A loop is a control structure that causes a
statement or group of statements to
repeat.
 C++ has three looping control structures:
 the while loop,
 the do-while loop, and
 the for loop.
 Thedifference between each of these is
how they control the repetition.
The while Loop
 The while loop has two important parts:
 (1) an expression that is tested for a true or false value, and
 (2) a statement or block that is repeated as long as the
expression is true.
 The general format of the while loop:
Example-1(… the while Loop)
// custom countdown using while
#include <iostream.h>
int main ()
{
int n;
cout << "Enter the starting number > ";
cin >> n;
while (n>0)
{
cout << n << ", ";
--n;
}
cout << "FIRE!"; Output:
return 0; Enter the starting number > 8
} 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
Example-2(… the while Loop)
// This program demonstrates a simple while loop.
#include <iostream.h>
int main()
{
int number = 0;
cout << “Enter number after a number. Enter 99 to quit.\n";
while (number != 99)
cin >> number;
cout << "Done\n";
return 0;
}
… the while Loop
 This program repeatedly reads values from the keyboard
until the user enters 99.
 The loop controls this action by testing the variable
number.
 As long as number does not equal 99, the loop repeats.
 Each repetition is known as an iteration.
while Is a Pretest Loop
 The while loop is known as a pretest loop,
 which means it tests its expression before each iteration.
 Notice the variable definition of number in Example-2:
int number = 0;
number is initialized to 0.
 If number had been initialized to 99, as shown in the
following program segment, the loop would never
execute the cin statement:
int number = 99;
while (number != 99)
cin >> number;
 An important characteristic of the while loop is that the
loop will never iterate if the test expression is false to
start with.
Terminating a Loop
 Loops must contain a way to terminate.
 This means that something inside the loop must eventually make the
test expression false..
 If a loop does not have a way of stopping, it is called an infinite
loop. Here is an example:
int test = 0;
while (test < 10)
cout << "Hello\n";
 The following loop will stop after it has executed 10 times:
int test = 0;
while (test < 10)
{
cout << "Hello\n";
test++;
}
Counters
 A counter is a variable that is regularly incremented or
decremented each time a loop iterates.
 For example, the following code displays numbers 1
through 10 and their squares, so its loop must iterate 10
times. Output
int num = 1; // Initialize counter Number Number Squared
---------- ---------------
while (num <= 10) 1 1
{ 2 4
3 9
cout << num << "\t\t" << (num * num) << endl; 4 16
num++; // Increment counter 5 25
6 36
} 7 49
8 64
9 81
10 100
…counters
 num is used as a counter variable,
 num counts the number of iterations the loop has
performed.
 Since num is controlling when to stay in the loop and
when to exit from the loop, it is called the loop control
variable.
 Anotherapproach is to combine the increment
operation with the relational test, as shown in the
code below.
int num = 0;
while (num++ < 10)
cout << num << "\t\t" << (num * num) << endl;
The do-while Loop
 The do-while loop looks similar to a while
loop turned upside down.
 The following figure shows its format:
… the do-while Loop
 The do-while loop must be terminated with
a semicolon after the closing parenthesis
of the test expression.
 do-while is a posttest loop.
 It tests its expression after each iteration is
complete.
 do-while always performs at least one
iteration, even if the test expression is false
from the start.
… the do-while Loop
 For example, in the following while loop the cout
statement will not execute at all:
int x = 1;
while (x < 0)
cout << x << endl;
 But the cout statement in the following do-while loop will
execute once.
int x = 1;
do
cout << x << endl;
while (x < 0);
 You should use do-while when you want to make sure
the loop executes at least once.
Example -1(… the do-while Loop)
// the following program echoes any number you enter until you enter 0.
#include <iostream.h>
int main () Output:
{ Enter number (0 to end):
unsigned long n; 12345
do You entered: 12345
{ Enter number (0 to end):
cout << "Enter number (0 to end): "; 160277
cin >> n; You entered: 160277
Enter number (0 to end): 0
cout << "You entered: " << n << "\n";
You entered: 0
} while (n != 0);
return 0;
}
The for Loop
 Itis ideal for situations that require a
counter.
 Here is the format of the for loop.

for (initialization; test; update)


{
statement;
statement;
// Place as many statements here as necessary.
}
… the for Loop
 The for loop has three expressions inside the
parentheses, separated by semicolons.
 The first expression is the initialization
expression.
 It
is used to initialize a counter or other variable that
must have a starting value.
 The second expression is the test expression.
 it controls the execution of the loop.
 The third expression is the update expression.
 It executes at the end of each iteration.
 It increments a counter or other variable that must be
modified in each iteration.
… the for Loop
 Example: The mechanics of the for loop
Example -1(… the for Loop)
// countdown using a for loop
#include <iostream.h>
int main ()
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
}
cout << "FIRE!";
return 0;
}
Output:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
… the for Loop
 The initialization expression may be omitted from the for
loop’s parentheses if it has already been performed.
int num = 1;
for ( ; num <= 10; num++)
cout << num << "\t\t" << (num * num) << endl;
 You may also omit the update expression if it is being
performed elsewhere in the loop.
 The following for loop works just like a while loop:
int num = 1;
for ( ; num <= 10; )
{
cout << num << "\t\t" << (num * num) << endl;
num++;
}
… the for Loop
 You can even go so far as to omit all three
expressions from the for loop’s parentheses.
 Be warned, that if you leave out the test
expression, the loop has no built-in way of
terminating.
 Here is an example:
for ( ; ; )
cout << "Hello World\n";
 Because this loop has no way of stopping, it will
display "Hello World\n" forever (or until
something interrupts the program).
Other Forms of the Update
Expression
 Hereis a loop that displays all the even numbers
from 2 through 100 by adding 2 to its counter:
for (number = 2; number <= 100; number += 2)
cout << number << endl;
 And
here is a loop that counts backward from 10
down to 0:
for (number = 10; number >= 0; number--)
cout << number << endl;
 The following loop has no formal body. The
combined increment operation and cout
statement in the update expression perform all
the work of each iteration:
for (number = 1; number <= 10; cout << number++);
… the for Loop
 Connecting multiple statements with commas works well in
the initialization and update expressions.
 If you wish to perform more than one conditional test, build
an expression with the && or || operators, like this:

for (count = 1, total = 0; count <= 10 && total < 500; count++)
{
double amount;
cout << "Enter the amount of purchase #" << count << ": ";
cin >> amount;
total += amount;
}
Nested Loops
 A loop that is inside another loop is called a nested loop.
 The first loop is called the outer loop.
 The one nested inside it is called the inner loop.
 Here is the format:
while (some condition) // Beginning of the outer loop
{
// ---
while (some condition) // Beginning of the inner loop
{
//------
} // End of the inner loop
} // End of the outer loop
 Nested loops are used when, for each iteration of the outer loop,
something must be repeated a number of times.
 Whatever the task, the inner loop will go through all its iterations
each time the outer loop is done.
 Any kind of loop can be nested within any other kind of loop.
… Nested Loops
 An inner loop goes through all of its iterations for
each iteration of an outer loop.
 Inner loops complete their iterations faster than
outer loops.
 To get the total number of iterations of an inner
loop, multiply the number of iterations of the
outer loop by the number of iterations done by
the inner loop each time the outer loop is done.
 For example, if the outer loop is done twice, and the
inner loop is done three times for each iteration of the
outer loop, the inner loop would be done a total of six
times in all.
Breaking Out of a Loop
 The break statement causes a loop to terminate early.
 When it is encountered, the loop stops and the program jumps to
the statement immediately following the loop.
 It can be used to end an infinite loop, or to force it to end before its
natural end.
 The following program segment appears to execute 10 times, but
the break statement causes it to stop after the fifth iteration.
int count = 0;
while (count++ < 10)
{
cout << count << endl;
if (count == 5)
break;
}
Example -1
//Stop the count down before it naturally finishes using break statement:
#include <iostream.h>
int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}
Output:
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
Using break in a Nested Loop
 In a nested loop, the break statement only interrupts the loop it is
placed in.
 For example:
for (int row = 0; row < 2; row++)
{
for (int star = 0; star < 6; star++)
{ The output of this program segment is
cout << '*';
if (int star == 3)
break;
****
****
}
cout << endl;
}
The continue Statement
 The continue statement causes a loop to stop its
current iteration and begin the next one.
 The continue statement causes the current
iteration of a loop to end immediately.
 When continue is encountered, all the
statements in the body of the loop that appear
after it are ignored, and the loop prepares for the
next iteration.
 In a while loop, this means the program jumps to the
test expression at the top of the loop.
 In a do-while loop, the program jumps to the test
expression at the bottom of the loop
 In a for loop, continue causes the update expression
to be executed.
Example(…the continue statement)
 The following program segment demonstrates the use of continue in
a while loop:
int testVal = 0;
while (testVal++ < 10)
{
if (testVal == 4)
continue;
cout << testVal << " ";
}
 This loop looks like it displays the integers 1 through 10. When
testVal is equal to 4, however, the continue statement causes the
loop to skip the cout statement and begin the next iteration.
The output of the loop is
1 2 3 5 6 7 8 9 10
… the continue Statement
 The continue instruction causes the program to skip the rest of the
loop in the present iteration, causing it to jump to the following
iteration.
 For example, we are going to skip the number 5 in our countdown:
#include <iostream.h>
int main ()
{
for (int n=10; n>0; n--)
{
if (n==5) Output:
continue; 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
cout << n << ", ";
}
cout << "FIRE!";
return 0;
}
The goto statement
 Itallows making an absolute jump to
another point in the program.
 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 (:).
… the goto statement
// goto loop example
#include <iostream.h>
int main ()
{
int n=10;
loop: Output:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
cout << n << ", ";
n--;
if (n>0)
goto loop;
cout << "FIRE!";
return 0;
}
Using Loops for Data Validation
 Loops can be used to create input routines that repeat until
acceptable data is entered.
 Loops are especially useful for validating input.
 They can test whether an invalid value has been entered and, if so,
require the user to continue entering inputs until a valid one is received.
 Using if statements to validate user inputs cannot provide an ideal
solution.
 Using while loop to validate input data, Every input will be checked.
cout << "Enter a number in the range 1 - 100: ";
cin >> number;
while (number < 1 || number > 100)
{
cout << "ERROR: The value must be in the range 1 - 100: ";
cin >> number;
}
………………………………………
………………………………………
………………………………..END
………………………………….OF
………………………...CHPTER 4
-*-*-*-*-*-*-*-*-*-*-*-*-*-*- THANK U!

You might also like