71
Programming Fundamentals 1 Control Structures (Repetition) Topics to cover here: Introduction to Repetition FOR .. DO Statement WHILE .. DO Statement DO .. WHILE Statement Nested Loops BREAK and CONTINUE Statements

Control Structures ( Repetition)

  • Upload
    thom

  • View
    76

  • Download
    1

Embed Size (px)

DESCRIPTION

Control Structures ( Repetition). Topics to cover here: Introduction to Repetition FOR .. DO Statement WHILE .. DO Statement DO .. WHILE Statement Nested Loops BREAK and CONTINUE Statements. Repetition: An Introduction. You can repeat many steps in an algorithm. - PowerPoint PPT Presentation

Citation preview

Page 1: Control Structures ( Repetition)

Programming Fundamentals 1

Control Structures(Repetition)

Topics to cover here:

• Introduction to Repetition• FOR .. DO Statement• WHILE .. DO Statement• DO .. WHILE Statement• Nested Loops• BREAK and CONTINUE Statements

Page 2: Control Structures ( Repetition)

Programming Fundamentals 2

Repetition: An Introduction

• You can repeat many steps in an algorithm.• Repetition of a sequence of steps in an algorithm is

called a loop.

• Types of loops:

- Counter-controlled loops

(e.g. WHILE..DO, FOR..DO, DO..WHILE)

- Conditional loops (e.g. WHILE..DO, DO..WHILE)- Sentinel-controlled loops (e.g. WHILE..DO, DO..WHILE)

- Flag-controlled loops (e.g. WHILE..DO, DO..WHILE)

Page 3: Control Structures ( Repetition)

Programming Fundamentals 3

Counter-Controlled Loop• The repetition of this loop is controlled by a loop control

variable (lcv) whose value represents a count. • This type of loops is used when you can determine prior

to loop execution exactly how many loop repetitions will be needed to solve a problem.

• The lcv should be incremented as the final statement of the loop.

• NOTE:All types of repetition statements could be used as counter-controlled loops. The FOR statement is based suited for this type of looping.

Page 4: Control Structures ( Repetition)

Programming Fundamentals 4

FOR .. DO Statement• The FOR statement enables us to place all loop control

operations in one place – the statement header.• It could be an increasing loop or decreasing loop.

• Syntax for the increasing loop:FOR (lcv initial_value TO final_value

[ BY increment_value ] ) DOStatements

END FORwhere, lcv is the loop control variable, and the part

[BY increment ] is optional (it is omitted if it is 1).

Page 5: Control Structures ( Repetition)

Programming Fundamentals 5

FOR .. DO Statement .. Cont.

• Semantics:The execution of this statement is as follows1- The lcv is set to initial_value2- lcv is checked with final_value

- if it is less than or equal, then * statements are executed

* the lcv is incremented by increment_value * repeat the process from step (2)

- else, goto the rest of the algorithm

These steps are shown in the following flowchart:

Page 6: Control Structures ( Repetition)

Programming Fundamentals 6

FOR .. DO Statement .. Cont.

lcv final_value

Statements

lcv initial_value

continue

False

True

lcv lcv + increment_value

Page 7: Control Structures ( Repetition)

Programming Fundamentals 7

FOR .. DO Statement .. Cont.

• Syntax for the decreasing loop:FOR (lcv final_value DOWNTO initial_value [ BY decrement_value ] ) DO

Statements END FOR

• The lcv is initialized to the final_value and consequentially will take values up to the initial_value. The lcv is decremented in each step by the decrement_value.

Page 8: Control Structures ( Repetition)

Programming Fundamentals 8

Examples

• Example 1

Write an algorithm that print the first 10 positive integer numbers

•Analysis Stage:

- Problem Input:

The 10 integers are generated by the algorithm

- Problem Output:

The first 10 positive integers

Page 9: Control Structures ( Repetition)

Programming Fundamentals 9

Example 1 .. Cont.

• Algorithm Design:ALGORITHM PrintBegin FOR ( I 1 TO 10 ) DO // here, increment by

1 OUTPUT I, “ “ END FOREND print-------------------------------------------------------------------------• Exercise

Modify the above algorithm so that it prints the numbers from 1 to n.

• Modify the above algorithm so that it prints the numbers from m to n.

Page 10: Control Structures ( Repetition)

Programming Fundamentals 10

Example 1.. Cont.

• Testing the Algorithm

I (I ≤ 5 ) The output:

1 True 12345678910 2 True

3 True

4 True

5 True

6 True

7 True

8 True 9 True 10 True

11 False (Stop)

Page 11: Control Structures ( Repetition)

Programming Fundamentals 11

Examples

• Example 1

Write an algorithm that finds the sum of the first 5 positive integer numbers

•Analysis Stage:

- Problem Input:

The 5 integers are generated by the algorithm

- Problem Output:

The sum of the first 5 positive integers

Page 12: Control Structures ( Repetition)

Programming Fundamentals 12

Example 1 .. Cont.

• Algorithm Design:ALGORITHM SumOfIntegersBegin sum 0 FOR ( I 1 TO 5 ) DO // here, increment by

1 sum sum + I END FOR OUTPUT “ Sum = “, sumEND SumOfIntegers-------------------------------------------------------------------------• Exercise

Modify the above algorithm so that it finds the sum of any 10 integers.

Page 13: Control Structures ( Repetition)

Programming Fundamentals 13

Example 1.. Cont.

• Testing the Algorithm

sum I (I ≤ 5 ) The output: 0

1 True

12

True 3

3True

64

True 10

5True

156

False (Stop) sum = 15

Page 14: Control Structures ( Repetition)

Programming Fundamentals 14

For Statement in C++

• Syntax for (initialization; test expression; update) Statements where, - initialization is to initialize the loop control variable (lcv) - test expression is the condition that will stop the loop - update is the increment to the lcv (in case of increasing loop) or decrement to the lcv (in case of decreasing loop)

Page 15: Control Structures ( Repetition)

Programming Fundamentals 15

Increment and Decrement Operators in C++

• For postfix operators, the increment (or decrement) occurs after the current value of the variable has been used.

• For prefix operators, the increment (or decrement) occurs first and the new value of the variable is then used.

• ExampleThe following C++ statements has the effects as shown in the comment:

i = 3; // initial value of ik = i++; // assigns 3 to k and 4 to ik = ++i; // assigns 5 to k and 5 to i

k = i-- ; // assigns 5 to k and 4 to ik = --i ; // assigns 3 to k and 3 to i

Increment Operators Decrement Operators

1- Postfix operator: e.g. i++

2- Prefix operator: e.g. ++i

1- Postfix operator: e.g. i-- 2- Prefix operator: e.g. --i

Page 16: Control Structures ( Repetition)

Programming Fundamentals 16

Compound Assignment Operators in C++

Simple assignment operator Compound assignment operator

X = X + 1; X += 1;

Y = Y – 1 ; Y -= 1 ;

Z = Z + X ; Z += X ;

P = P * item ; P *= item ;

N = N * (x + 1) ; N *= (x + 1) ;

Total = Total / (X+Y); Total /= (X+Y);

Hours = Hours % 13; Hours %= 13;

Page 17: Control Structures ( Repetition)

Programming Fundamentals 17

Example 1: C++ Program

// File: SumOfIntegers.cpp/* The program finds the sum of the first 5 positive

integer numbers. */

#include <iostream.h>void main ( ){ int I, sum = 0; for ( I = 1; I < =5; I++ ) // here, increment by 1 sum = sum + I; cout << “ Sum = “ << sum << endl;}

Page 18: Control Structures ( Repetition)

Programming Fundamentals 18

Example 2

Write an algorithm that finds the sum of the odd numbers among the first 6 positive integers.

• Analysis Stage: - Problem Input: The first 6 integers are generated by the algorithm - Problem Output: The sum of the odd integers

Page 19: Control Structures ( Repetition)

Programming Fundamentals 19

Example 2 .. Cont.• Algorithm Design:ALGORITHM SumOddBegin sum 0 FOR ( I 1 TO 6 BY 2 ) DO sum sum + I END FOR OUTPUT “ Sum = “, sumEND SumOdd-------------------------------------------------------------------------• Exercise

Modify the above algorithm so that it finds the sum of the odd integers and the sum of the even integers among the first 6 positive integers.

Page 20: Control Structures ( Repetition)

Programming Fundamentals 20

Example 2 .. Cont.• Testing the Algorithm

sum I (I ≤ 6 ) The output: 0

1 True

13

True 4

5True

97

False (Stop) sum = 9

Page 21: Control Structures ( Repetition)

Programming Fundamentals 21

Example 2: C++ Program

/* The program finds the sum of the odd numbers among the first 6 positive integers. */

#include <iostream.h>

void main ( ){ int i, sum = 0 ; for ( i =1 ; i <=6 ; i += 2 ) sum += i ; cout << “ Sum = “ << sum << endl;}

Page 22: Control Structures ( Repetition)

Programming Fundamentals 22

WHILE Statement• Syntax:

WHILE (logical expression) DO

Statements

END WHILE

• Semantics:

The execution of this statement is shown as in the following flowchart:

Page 23: Control Structures ( Repetition)

Programming Fundamentals 23

WHILE Statement Execution

Logical Expression

Statements

True

False

continue

Page 24: Control Structures ( Repetition)

Programming Fundamentals 24

An Example on Count-Controlled Loop• Example 1:

Write an algorithm that prints the squares of the first 4 positive integers.

• Analysis Stage:

- Problem Input:

The 4 integers are generated by the algorithm

- Problem Output:

The square value of each integer

Page 25: Control Structures ( Repetition)

Programming Fundamentals 25

Example1 .. Cont.• Algorithm Design:ALGORITHM SquaresBegin I 1 WHILE ( I ≤ 4 ) DO OUTPUT “ square of “, I , “ is “ , I * I I I + 1

END WHILE END Squares----------------------------------------------------------------------------• Exercise

Try to modify the above algorithm so that it squares any 10 integers.

Page 26: Control Structures ( Repetition)

Programming Fundamentals 26

Example1 .. Cont.• Testing the Algorithm

I (I ≤ 4 ) The output: 1

True square of 1 is 1

2True

square of 2 is 4 3

Truesquare of 3 is 9

4 True

square of 4 is 16 5

False (Stop)

Page 27: Control Structures ( Repetition)

Programming Fundamentals 27

While Statement in C++Syntax: while (logical expression) statements;

where statements could be one or more statements enclosed by braces { and }

Semantics:This statement has the same meaning as in the

algorithmic language.

Page 28: Control Structures ( Repetition)

Programming Fundamentals 28

Example 1: C++ Program

/* The program prints the squares of the first 4 positive integers. It uses a counter-based loop. */

#include <iostream.h>void main ( ){ int I = 1; while ( I <= 4 ) {cout <<“Square of “ << I << “ is “ << I * I << endl ; I = I + 1; }}

Page 29: Control Structures ( Repetition)

Programming Fundamentals 29

Conditional Loops• Such loops are used when you cannot determine the exact

number of loop repetitions before loop execution begins.

• The number of repetitions may depend on some aspects of the data that is not known before the loop is entered but that usually can be stated by a condition.

• The condition value should be modified inside the loop to ensure loop termination.

• NOTE:

The WHILE .. DO statement and DO .. WHILE statement are best suited for this type of looping.

Page 30: Control Structures ( Repetition)

Programming Fundamentals 30

An Example on Conditional Loops• Example 2:

Write an algorithm that reads a sequence of integer numbers and finds the product of the numbers as long they are positive.

• Analysis Stage:- Problem Input:

a sequence of integers - Problem Output: The product of the positive integers- Criteria: Any negative number will stop looping

Page 31: Control Structures ( Repetition)

Programming Fundamentals 31

Example 2 .. Cont.• Algorithm Design:ALGORITHM MultiplyingBegin

product 1OUTPUT “ Enter first number: “INPUT numberWHILE ( number > 0 ) DO

product product * numberOUTPUT “ Enter next number: “INPUT number

END WHILEOUTPUT “ The product is “ , product

END Multiplying

Page 32: Control Structures ( Repetition)

Programming Fundamentals 32

Example 2 .. Cont.• Testing the Algorithm

product number (number > 0 ) The output:1 Enter first number:

2 True

2 Enter next number:

5True

10 Enter next number:

7True

70 Enter next number:

-3 False (stop) The product is 70

Page 33: Control Structures ( Repetition)

Programming Fundamentals 33

Example 2: C++ Program/* The program reads a sequence of integer numbers and finds the product of

the numbers as long they are positive. It uses a conditional loop */#include <iostream.h>void main ( ){ int number, product; product = 1 ; cout << “ Enter first number: “ ;

cin >> numberwhile ( number > 0 )

{ product = product * number ; cout << “ Enter next number; to end enter any negative number “ ; cin >> number ; }

cout << “ The product is “ << product << endl;}

Page 34: Control Structures ( Repetition)

Programming Fundamentals 34

Sentinel-Controlled Loops• This type of loops is used when you don’t know exactly how

many data items a loop will process before it begins execution.

• One way to handle this situation is to instruct the user to enter a unique data value, called a sentinel value, as the last data item.

• The sentinel value should be carefully chosen and must be a value that cannot possibly occur data.

• NOTE:

The WHILE .. DO statement and DO .. WHILE statement are can be used for this type of looping.

Page 35: Control Structures ( Repetition)

Programming Fundamentals 35

An Example on Sentinel-Controlled Loops• Example 3:

Write an algorithm that sums up the student’s exam scores by using sentinel-controlled loop.

• Analysis Stage:You must choose a sentinel value that could not be a student’s score (say, -1)- Problem Input:

a sequence of student’s exam scores that ends with -1- Problem Output: The sum of the scores- Criteria: the input -1 will stop looping

Page 36: Control Structures ( Repetition)

Programming Fundamentals 36

Example 3 .. Cont.• Algorithm Design:ALGORITHM ScoresBegin

sum 0OUTPUT “Enter a score: “INPUT scoreWHILE ( score ≠ -1 ) DO

sum sum + scoreOUTPUT “Enter the next score, to end enter -1: “INPUT score

END WHILEOUTPUT “ The sum is “ , sum

END Score----------------------------------------------------------------------------• Exercise

Modify the algorithm so that it calculates the average of the exam scores.

Page 37: Control Structures ( Repetition)

Programming Fundamentals 37

Example 3 .. Cont.• Testing the Algorithm

sum score (score ≠ -1 ) The output:0

Enter a score: 60

True60

Enter the next score, to end enter -1: 75

True135

Enter the next score, to end enter -1:80

True215

Enter the next score, to end enter -1: -1

False (stop) The sum is 215

Page 38: Control Structures ( Repetition)

Programming Fundamentals 38

Example 3: C++ Program/* The program sums up the student’s exam scores by using sentinel-

controlled loop. */

#include <iostream.h>void main ( ){ int sum = 0 , score ; cout << “Enter a score: “ ; cin >> score ; while ( score != -1 )

{ sum =- sum + score ; cout << “Enter the next score, to end enter -1: “ ;

cin >> score ; } cout << “ The sum is “ << sum << endl ;}

Page 39: Control Structures ( Repetition)

Programming Fundamentals 39

Flag-Controlled Loops

A variable of type Boolean is used as status flag to control the execution of such loops.

• The value of the flag is initialized prior to loop entry and is redefined when a particular event occurs inside the loop.

• A flag-controlled loop executes until the anticipated event occurs and the flag value is changed.

• NOTE:The WHILE .. DO statement and DO .. WHILE statement are best suited for this type of looping.

Page 40: Control Structures ( Repetition)

Programming Fundamentals 40

An Example on Flag-Controlled LoopsExample 4:

Write an algorithm that reads a character and prints it as long as it is not a digit, using a flag-controlled loop.

• Analysis Stage:This example continues to read a character until it reads a digit. You must initialize a flag to a Boolean value to control the loop.

- Problem Input: a character, (say next)_char)

- Problem Output: The characters that are not digit- Criteria: flag = true to stop the loop

Page 41: Control Structures ( Repetition)

Programming Fundamentals 41

Example 4 .. Cont.• Algorithm Design:

ALGORITHM CharactersBegin

flag true // assume no digit character has been readWHILE ( flag ) DO

OUTPUT “Enter the next character: “INPUT next_charIF (next_char <‘0’ OR next_char > ‘9’ ) THEN OUTPUT “ Character is “ , next_charELSE flag false

END WHILEOUTPUT “ *** Finished ***“

END Characters

Page 42: Control Structures ( Repetition)

Programming Fundamentals 42

Example 4: C++ Program/* The program reads a character and prints it as long as it is not a digit, using a

flag-controlled loop. */

#include <iostream.h>void main ( )

{ bool flag; char next_char;

flag = true // assume no digit character has been readwhile ( flag ) { cout << “Enter the next character: “ ;

cin >> next_char ; if (next_char < ‘0’ || next_char > ‘9’ ) cout << “ Character is “ << next_char << endl;

else flag = false ;

}cout << “ *** Finished ***“ << endl ;

}

Page 43: Control Structures ( Repetition)

Programming Fundamentals 43

The DO .. WHILE Statements• Syntax

DO Statements WHILE ( condition)• Semantics The statements are evaluated first, then the condition is

tested. If the condition is true, the process is repeated until the condition become false.

• This statement is executed at least once.• The following figure shows the execution of this

statement.

Page 44: Control Structures ( Repetition)

Programming Fundamentals 44

The DO .. WHILE Statements .. Cont.

Condition

Statements

True

False

Continue

Page 45: Control Structures ( Repetition)

Programming Fundamentals 45

Examples of the DO .. WHILE Statements

•Example 8Write an algorithm that continues reading a number and finds its square as long as the user enters Y or y.•Analysis Stage:Use the DO..WHILE loop to read the numbers one by one and square each one as long as the user enters Y or y. - Problem Input: the numbers be read repeatedly. - Problem Output: the square of each number - Criteria To end the loop, enter N or n

Page 46: Control Structures ( Repetition)

Programming Fundamentals 46

Example 8 .. Cont.

•Algorithm Design:ALGORITHM squaringBegin DO OUTPUT “ Enter a number: ” INPUT num OUTPUT num , “ “ , num * num OUTPUT “Continue execution?-Y (Yes)/ N (No):“ INPUT ch WHILE ( ch = ‘Y’ OR ch = ‘y’) OUTPUT “ Finished “END squaring………………………………………………….H.W: Rewrite the above algorithm by using the WHILE statement.

Page 47: Control Structures ( Repetition)

Programming Fundamentals 47

Example 8 .. Cont.•Testing the Algorithm

num choice (ch=‘Y’ OR ch=‘y’) The output Enter a number: 4 4 16 Continue execution? Y(Yes)/N(no) Y True

Enter a number: 7 7 49

Continue execution? Y(Yes)/N(no) Y True Enter a number:3 3 9 Continue execution? Y(Yes)/N(no) N False (stop) Finished

Page 48: Control Structures ( Repetition)

Programming Fundamentals 48

Do .. While Loop in C++

• Syntax

do

{

Statements

} while (condition);

• Semantics

It has the same meaning s in the algorithmic language.

Page 49: Control Structures ( Repetition)

Programming Fundamentals 49

Example 8: C++ Program/* The program continues reading a number and finds its square as long as the user enters Y or y. */#include <iostream.h>void main ( ){ int num; char ch ;

do { cout << “ Enter a number: ” ; cin >> num ; cout << num << “ “ << num * num << endl ; cout << “Continue execution?-Y (Yes)/ N (No):“ ; cin >> ch ; } while ( ch == ‘Y’ || ch == ‘y’) ; cout << “ Finished “ << endl ;}

Page 50: Control Structures ( Repetition)

Programming Fundamentals 50

An Example of Converting between Loops

• Initialize the lcv to the same initial_value of the FOR loop

• Make a condition that tests the lcv with the final_value of the FOR loop.

• Write a counter-controlled WHILE statement with the above condition to execute the same body of FOR loop.

• Increment the lcv by the increment_value of the FOR loop

Page 51: Control Structures ( Repetition)

Programming Fundamentals 51

Example

Write an algorithm that reads payroll data (number of worked hours and the rate per hour) for 7 employees and computes and displays each employee’s weekly pay.

•Analysis Stage: - Problem Input: hours, rate for each employee - Problem Output: The weekly pay for each employee

Page 52: Control Structures ( Repetition)

Programming Fundamentals 52

Example : C++ Program

/* The program reads payroll data (number of worked hours and the rate per hour) for 7 employees and computes and displays each employee’s weekly pay.. */

ALGORITHM Pay1Begin

I 1for ( i 1 to 7 ) do output “ Enter hours and rate for employee “ , i , “ : “ input hours , rate weekly_pay = hours * rate output “Weekly pay for employee “, i ,“ = “,weekly_pay End for output “ All employees are processed “End Pay1

Page 53: Control Structures ( Repetition)

Programming Fundamentals 53

Example : C++ Program

/* The program reads payroll data (number of worked hours and the rate per hour) for 7 employees and computes and displays each employee’s weekly pay.. */

#include <iostream.h>void main ( ){ int i , hours; float rate, weekly_pay ; for ( i = 1 ; i <= 7 ; i++ ) { cout << “ Enter hours and rate for employee “ << i << “ : “ ; cin >> hours >> rate ; weekly_pay = hours * rate ; cout << “Weekly pay for employee “<< i << “ = “ <<weekly_pay << endl; } cout << “ All employees are processed “ << endl;}

Page 54: Control Structures ( Repetition)

Programming Fundamentals 54

An Example of Converting between Loops

ALGORITHM Pay2Begin

I 1 WHILE ( I 7 ) DO OUTPUT “ Enter hours and rate for employee “ , I, “: “

INPUT hours, rate weekly_pay hours * rate

OUTPUT “ Weekly pay for employee “ , I , “ = ‘ , weekly_pay , ‘\n’

I I + 1 END WHILE OUTPUT “ All employees are processed “END Pay

Page 55: Control Structures ( Repetition)

Programming Fundamentals 55

Example 4

Write an algorithm to print a list of 4 integer values with their squares and their square roots. Suppose that there is a subalgorithm called pow to calculate the power of a base value to any value, and sqrt to calculate the square root of a value.

•Analysis Stage: - Problem Input: any four integers - Problem Output: the number, its square value, its square root

Page 56: Control Structures ( Repetition)

Programming Fundamentals 56

Example 4 .. Cont.• Algorithm Design:ALGORITHM CalculateBegin OUTPUT “ Number Square Square Root “ FOR ( I 1 TO 4 ) DO

INPUT number square pow ( number , 2 )

root sqrt (number) OUTPUT “ “ , number , “ “ , square, “ “ , root

OUTPUT “\n” END FOREND Calculate

Page 57: Control Structures ( Repetition)

Programming Fundamentals 57

Example 4 .. Cont.• Testing the Algorithm

I (I≤4) number square root The output: Number Square Square Root

1 True 5 25 2.23 5 25 2.23 2 True 6 36 2.45 6 36 2.453 True 4 16 2 4 16 24 True 9 81 3 9 81 35 False (stop)

Page 58: Control Structures ( Repetition)

Programming Fundamentals 58

Example 4: C++ Program

/* The program prints a list of 4 integer values with their squares and their square roots. It uses the math library functions pow to calculate the power of a base value to any value, and sqrt to calculate the square root of a value.*/

#include <iostream.h># include <cmath.h>void main ( ){ int I, number ; double root, square; cout<< “ Number Square Square Root “ << endl; for ( I = 1 ; I <= 4; I++ ) { cin >> number ;

square = pow ( number , 2 ) ; root = sqrt (number) ; cout << “ “ << number << “ “ <<square<< “ “ << root << endl; }}

Page 59: Control Structures ( Repetition)

Programming Fundamentals 59

Example 5

Write an algorithm to calculate the following:

• Analysis Stage:This equation similar to

- Problem Input: x and n - Problem Output: the sum of the series, say sum

nxgivenanyforx

Yn

ii

,1

11

nxxxx

1...

1111

32

Page 60: Control Structures ( Repetition)

Programming Fundamentals 60

Example 5 .. Cont.

• Algorithm Design:ALGORITHM SeriesBegin sum 0 OUTPUT “ Enter value of x and the number n :” INPUT x, n FOR ( I 1 TO n) DO

sum sum + 1 / pow ( x , I ) END FOR OUTPUT “ Sum = “ , sumEND Series

• HW: Trace and test this algorithm.

Page 61: Control Structures ( Repetition)

Programming Fundamentals 61

Example 5: C++ Program

/* The program calculates a series.*/#include <iostream.h>#include <cmath.h>void main ( )

{ int i, n, x, sum = 0 ;

cout << “ Enter value of x and the number n :” ;

cin >> x >> n ;

for ( i = 1; i <= n ; i++ )

sum = sum + 1 / pow ( x , i ) ;

cout << “ Sum = “ << sum << endl ;

}

Page 62: Control Structures ( Repetition)

Programming Fundamentals 62

Example 6

Write an algorithm that reads 10 numbers and finds the maximum and minimum numbers among them.

• Analysis Stage:

Use a loop to read the 10 numbers one by one and test it for maximum and minimum.

- Problem Input:

Ten numbers to be read repeatedly.

- Problem Output:

maximum, minimum

- Criteria

Let max and min equal the first number in the sequence

Page 63: Control Structures ( Repetition)

Programming Fundamentals 63

Example 6 .. Cont.• Algorithm Design:ALGORITHM MaxMinBegin OUTPUT “ Enter a number: ” INPUT n max n min n FOR ( I 2 TO 10 ) DO

OUTPUT “ Enter a number: ” INPUT n

IF ( n > max ) THEN max n END IF IF ( n < min ) THEN

min n END IF END FOR OUTPUT “ Max = “ , max, “ Min = “ , minEND MaxMin

Page 64: Control Structures ( Repetition)

Programming Fundamentals 64

Example 6 .. Cont.• Testing the Algorithm (for 4 numbers only)

I (I ≤4) n max min (n>max) (n<min) The output: Enter a number: 5 5 52 True Enter a number: 7 True 7 False3 True Enter a number: 2 False True 24 True

Enter a number: 9 True 9 False5 False (stop)

Max = 9 Min = 2

Page 65: Control Structures ( Repetition)

Programming Fundamentals 65

Example 6: C++ Program

/* The program reads 10 numbers and finds the maximum and minimum numbers among them.*/

#include <iostream.h>void main ( ){ int I, n, max, min; cout << “ Enter a number: ” ; cin >> n ; max = n ; min = n ; for ( I = 2 ; I <= 10; I++ ) { cout << “ Enter a number: ” ; cin >> n ; if ( n > max ) max = n ; if ( n < min ) min = n ; } cout << “ Max = “<< max<< “ Min = “<< min<< endl;}

Page 66: Control Structures ( Repetition)

Programming Fundamentals 66

Nested Loops

• When you write a loop inside another loop, then it is called a nested loop.

• You can use FOR loop inside another FOR loop

• You can use WHILE loop inside a FOR loop or vise versa.

Page 67: Control Structures ( Repetition)

Programming Fundamentals 67

Example of Nested Loops

• Example 7

Write an algorithm that prints the following figure by printing one “*” each time. Use nested loops.

*

* *

* * *

* * * *

* * * * *

Page 68: Control Structures ( Repetition)

Programming Fundamentals 68

Example of Nested Loops

• Algorithm Design:

ALGORITHM Stars

Begin

FOR ( I 1 TO 5 ) DO

FOR ( J 1 TO I ) DO

OUTPUT “ * “ , “ “

END FOR

OUTPUT “\n”

END FOR

END Stars

Page 69: Control Structures ( Repetition)

Programming Fundamentals 69

Example 7: C++ Program

/* The program prints a figure of stars by using nested loops to print one “*” at a time. */#include <iostream.h>void main ( ){ int I, J; for ( I = 1; I <= 5 ; I++) for ( J = 1; J <= I ; J++ ) cout << “ * “ << “ “ ; cout << endl ;}

Page 70: Control Structures ( Repetition)

Programming Fundamentals 70

The BREAK and CONTINUE Statements in Loops

• The BREAK Statement• Use BREAK to leave the loop even if the condition for its

end is not achieved.• Example FOR ( n 10 DOWNTO 0 BY -1 ) DO OUTPUT n * 2 , “ , “ IF ( n = 4 ) THEN OUTPUT “ Loop Aborted” BREAK END IF END FORThe output is: 20, 18, 16, 14, 12, 10, 8, Loop Aborted

Page 71: Control Structures ( Repetition)

Programming Fundamentals 71

The BREAK and CONTINUE Statements in Loops

• The CONTINUE Statement• This statement causes the program to skip the rest of the loop in

the present iteration as if the end of the statement block would have been reached, causing it to jump to the following iteration.

• Example FOR ( n 1 TO 10 ) DO IF ( n = 5 ) THEN CONTINUE END IF OUTPUT n , “, ” END FOR OUTPUT “ Finished “

• The output is: 1, 2, 3, 4, 6, 7, 8, 9, 10, Finished