0% found this document useful (0 votes)
30 views20 pages

Chapter 05

Uploaded by

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

Chapter 05

Uploaded by

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

Looping Flow of Control

(Iterations)
IT1134
Chapter 05
LOOPS (Iterations)

• A loop can be used to tell a program to execute statements repeatedly.


• Loops are constructs that control repeated executions of a block of statements. The
concept of looping is fundamental to programming. C++ provides three types of
loop statements:
while loops, do-while loops, and for loops.
• The purpose of loops is to repeat the same, or similar, code a number of times.
This number of times could be specified to a certain number, or the number of
times could be dictated by a certain condition being met.
• It provides code reusability. (Many Data, redundant tasks) (Eg. compute the salaries
of all the employees, computing Grades of all the students)
• Using loops, we do not need to write the same code again and again.
• Using loops, we can traverse over the elements of data structures (array).
The while Loop
• A while loop executes statements repeatedly while the condition is true.
• The syntax for the while loop is

• The part of the loop that contains the statements int index=1;
to be repeated is called the loop body.
while (index<=10)
• A one-time execution of a loop body is
referred to as an iteration (or repetition) {
of the loop. cout<< index << " ";
• The condition may be any Boolean expression. index=index+1;
The loop iterates while the condition is true.
When the condition becomes false, program }
control passes to the line immediately following return 0;
the loop. }
Examples
• Display the even numbers from 1 to 100.
• Display the odd number from 1 to N
• Find the sum of integer from 1 to N.
• Find the average of given N students’ Marks
• Write a program to calculate N!. N! is defined to be 1 for N = 1 and N(N-1)! for N > 1. The value of N is input
from the keyboard. 5! = 5*4*3*2*1 = 120.
• Write programs to display the following outputs
Properties of while Loop
• Caution: Make sure that the loop-continuation-condition eventually
becomes false so that the program will terminate.
• A common programming error involves infinite loops. If your
program takes an unusually long time to run and does not stop, it may
have an infinite loop. If you are running the program from the
command window, press CTRL+C to stop it.
• Key point of the while loop is that the loop might not ever run. When
the condition is tested and the result is false, the loop body will be
skipped and the first statement after the while loop will be executed.
• The error may lies in the condition, which should be count < 100 rather
than count <= 100
Controlling a Loop with User Confirmation

Don’t use floating-point values for equality checking in a loop control


expression.
The do-while Loop

• A do-while loop is the same as a while loop except that it


executes the loop body first and then checks the loop
continuation condition.

• The loop body is executed first. Then the loop-


continuation-condition is evaluated.
• If the evaluation is true, the loop body is executed again;
otherwise the do-while loop terminates.
While VS Do-while Loop
• The major difference between a while and a do-while loop is the order in which the loop-
continuation-condition is evaluated and the loop body executed. The while and do-while loops
have equal expressive power. Sometimes one is more convenient than the other. A do...while loop is
guaranteed to execute at least one time.
The for Loop

• A for loop has a concise syntax for writing loops.


• A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to execute a specific number
of times.
• The syntax of a for loop in C++ is:
The for Loop
The initial action step is executed first, and only once. This step allows you to declare and initialize any loop
control variables.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the
loop does not execute and flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment statement.

A for loop generally uses a variable to control how


many times the loop body is executed and when the
loop terminates. This is called a control variable.
Which Loop to Use?

• You can use a for loop, a while loop, or a do-while loop, whichever is convenient.
• The while loop and for loop are called pretest loops because the continuation
condition is checked before the loop body is executed. The do-while loop is called a
posttest loop because the condition is checked after the loop body is executed.
• Use the loop statement that is most intuitive and comfortable for you. In general, a
for loop may be used if the number of repetitions is known in advance, as, for
example, when you need to display a message 100 times.
• A while loop may be used if the number of repetitions is not fixed, as in the case of
reading the numbers until the input is 0.
• A do-while loop can be used to replace a while loop if the loop body has to be
executed before the continuation condition is tested.
Nested Loops

• A loop can be nested inside another loop.


• Nested loops consist of an outer loop and one or more inner loops. Each time the
outer loop is repeated, the inner loops are reentered, and started a new.
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic
objects that were created in that scope are destroyed. C++ supports the following control statements:
The break statement
break leaves 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.
float number, sum = 0.0;
while (true)
{ cout<< "Enter a number: ";
cin>> number;
if (number != 0.0)
{ sum += number;
}
else
{ break;
}
}
cout<< "Sum = " << sum;
Loop Control Statements
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.
C++ program to display integer from 1 to 10 except 6 and 9.

int main()
{
for (int i = 1; i <= 10; i++)
{
if ( i == 6 || i == 9)
{
continue;
}
cout<<i<< "\t";
}
return 0;
}
Homework
1. Write a program to calculate N!. N! is defined to be 1 for N = 1 and N(N-1)! for N > 1. The value of N is input from
the keyboard. 5! = 5*4*3*2*1 = 120.
2. A prime number is a number defined to be a number that is evenly divisible only by 1 and itself. We can check to
see if an integer is prime in the following way.
Let's look at 9. 9 divided by 2 = 4.5 (still a candidate), 9 divided by 3 = 3 (cannot be prime)
What about 17?
17 divided by 2 = 8.5 (keep checking), 17 divided by 3 = 5.66 (keep checking)
17 divided by 4 = 4.25 (keep checking), 17 divided by 5 = 3.4 (looks prime)
It is only necessary to divide by numbers that are less than or equal to the square root of the number being checked.
Design a program that reads in a number from the keyboard and checks to see whether it is prime or not.
Homework
3. Write and run a program to tabulate sin(x), cos(x) and tan(x) for x = 5, 10, 15,: : :,85 degrees. Notice that you
have to convert x from degrees to radians before using standard functions.
4. The Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, 13,: : :, where the first two terms are 0 and 1, and each term
thereafter is the sum of the two preceding terms, that is, Fib(n) = Fib(n-1) + Fib(n-2). Using this information,
write a program that calculates the nth number in a Fibonacci sequence, where n is entered into the program by
the user.
Algorithms for Loops WHILE condition
statements
ENDWHILE

int index=1;
while (index<=10)
{
cout<< index << " ";
index=index+1;
}
return 0;
}
STEP1 START
STEP2 index<-1;
STEP3 WHILE (index<=10)
STEP 3.1 PRINT index
STEP 3.2 index<-index+1;
ENDWHILE
STEP4 END
Algorithms for Loops

FOR range of iteration


statements
ENDFOR

STEP1 START
STEP2 For index=1 to 20
PRINT index
ENDFOR
STEP3 END
FOR each element in Array A
FOR each month of the year
FOR i = 1 to 10 INCREMNET
2
Maximum value of an Array

STEP1 START
STEP2 CREATE A [10]
STEP3 PRINT “Enter 10 Numbers:”
STEP4 For i=1 to 10
READ A[i]
ENDFOR
STEP5 Max<- A[1]
STEP6 FOR i=2 to 10
IF Max<A[i] THEN
Max<- A[i]
ENDIF
STEP7 PRINT Max
STEP8 END

You might also like