15
COMP 111 – PROGRAMMING I REPETITION STATEMENTS Instructor: Dr Dionysiou ADMINISTRATIVE 2 ! This week’s lecture ! [BRON06] Chapter 5 (5.1-5.7) ! Basic loop structures, while loop, for loop, do-while loop, nested loop Figures on slides 6, 7, 11, 46, 54 taken from [BRON06] Copyright © Dionysiou 2010 LECTURE OUTLINE 3 ! Basic Loop Structures ! while statement ! for statement ! Nested statement ! do-while statement Copyright © Dionysiou 2010 BASIC LOOP STRUCTURES 4 ! Many problems require a repetition capability ! get student’s grades for various courses ! find the square root of all integer numbers in [0,100] ! find the factorial of all integer numbers in [0,12] ! Construct repeating sections of code ! That’s a loop ! Each repetition through the code is called ! Iteration or pass through the loop Copyright © Dionysiou 2010

COMP 111 – PROGRAMMING I REPETITION STATEMENTS fileCOMP 111 – PROGRAMMING I REPETITION STATEMENTS Instructor: Dr Dionysiou ADMINISTRATIVE 2 ! This week’s lecture ! [BRON06] Chapter

Embed Size (px)

Citation preview

COMP 111 – PROGRAMMING I

REPETITION STATEMENTS

Instructor: Dr Dionysiou

ADMINISTRATIVE

2

! This week’s lecture !  [BRON06] Chapter 5 (5.1-5.7)

!  Basic loop structures, while loop, for loop, do-while loop, nested loop

Figures on slides 6, 7, 11, 46, 54 taken from [BRON06]

Copyrigh

t © D

ionysiou

2010

LECTURE OUTLINE

3

! Basic Loop Structures !  while statement !  for statement ! Nested statement !  do-while statement

Copyrigh

t © D

ionysiou

2010

BASIC LOOP STRUCTURES

4

! Many problems require a repetition capability !  get student’s grades for various courses !  find the square root of all integer numbers in [0,100] !  find the factorial of all integer numbers in [0,12]

! Construct repeating sections of code !  That’s a loop !  Each repetition through the code is called

!  Iteration or pass through the loop

Copyrigh

t © D

ionysiou

2010

BASIC LOOP STRUCTURES (CONT.)

5

! Constructing a repetitive section of code requires 4 elements: !  Repetition statement

!  while !  for !  do-while

!  Repetition condition !  If condition is true, the loop is executed !  If condition is false, the loop terminates

!  Statement that initially sets the condition !  Statement within the repeating section of code that

allows the condition to become false !  Ensure that repetition stops

!  If not you end up with an infinite loop

Copyrigh

t © D

ionysiou

2010

PRETEST AND POSTTEST LOOPS

6

!  Pretest loop !  Condition testing occurs at the

beginning of the loop before any statements in the loop are executed !  Condition is true " loop

iteration !  Condition is false " loop

terminates !  If initial value of condition is

false, then loop is not entered

!  Also known as entrance-controlled loop

!  while and for belong to this category

Copyrigh

t © D

ionysiou

2010

PRETEST AND POSTTEST LOOPS (CONT.)

7

! Posttest loop !  Condition testing occurs at

the end of the loop !  Condition is true " loop

iteration !  Condition is false " loop

terminates

!  Loop statements will be executed at least once before condition is tested

! Also known as exit-controlled loop

!  do-while belongs to this category

FIXED COUNT VS. VARIABLE CONDITION LOOPS

8

! Loops can also be categorized in terms of the type of condition being tested !  Fixed count loop

!  A fixed number of iterations are performed !  All C++ repetition statements can be used to produce fixed

count loops

!  Variable condition loop !  Number of iterations not known in advance !  Tested condition does not depend on a count being achieved

!  when a specified value is encountered, repetitions stop !  All C++ repetition statements can be used to produce variable

condition loop

Copyrigh

t © D

ionysiou

2010

LECTURE OUTLINE

9

! Basic Loop Structures !  while statement !  for statement ! Nested statement !  do-while statement

Copyrigh

t © D

ionysiou

2010

while LOOP

10

Copyrigh

t © D

ionysiou

2010

1.  Test the expression (condition) 2.  If the expression has a nonzero value (true condition)

a.  Execute the statement following the parenthesis b.  Go back to step 1

else a.  exit the loop

while LOOP (CONT.)

11

Copyrigh

t © D

ionysiou

2010

while LOOP (CONT.)

12

Copyrigh

t © D

ionysiou

2010

#include <iostream> using namespace std;

int main() { int count;

count = 1;

while (count <= 5) { cout << count << “ “; count++; }

return 0; }

Initialize count

condition

Increment count

while LOOP (CONT.) – ITERATION 1

13

Copyrigh

t © D

ionysiou

2010

#include <iostream> using namespace std;

int main() { int count;

count = 1;

while (count <= 5) { cout << count << “ “; count++; }

return 0; }

count is 1

1 <= 5

count is 2

1

while LOOP (CONT.) – ITERATION 2

14

Copyrigh

t © D

ionysiou

2010 #include <iostream> using namespace std;

int main() { int count;

count = 1;

while (count <= 5) { cout << count << “ “; count++; }

return 0; }

2 <= 5

count is 3

1 2

while LOOP (CONT.) – ITERATION 3

15

Copyrigh

t © D

ionysiou

2010

#include <iostream> using namespace std;

int main() { int count;

count = 1;

while (count <= 5) { cout << count << “ “; count++; }

return 0; }

3 <= 5

count is 4

1 2 3

while LOOP (CONT.) – ITERATION 4

16

Copyrigh

t © D

ionysiou

2010

#include <iostream> using namespace std;

int main() { int count;

count = 1;

while (count <= 5) { cout << count << “ “; count++; }

return 0; }

4 <= 5

count is 5

1 2 3 4

while LOOP (CONT.) – ITERATION 5

17

Copyrigh

t © D

ionysiou

2010

#include <iostream> using namespace std;

int main() { int count;

count = 1;

while (count <= 5) { cout << count << “ “; count++; }

return 0; }

5 <= 5

count is 6

1 2 3 4 5

while LOOP (CONT.) – ITERATION 6?

18

Copyrigh

t © D

ionysiou

2010 #include <iostream> using namespace std;

int main() { int count;

count = 1;

while (count <= 5) { cout << count << “ “; count++; }

return 0; }

6 <= 5

1 2 3 4 5

while LOOP (CONT.) – WHAT IS THE OUTPUT?

19

Copyrigh

t © D

ionysiou

2010

#include <iostream> using namespace std;

int main() { int i;

i = 10;

while (i >= 5) { cout << i << “ “; i--; }

return 0; }

while LOOP (CONT.) – WHAT IS THE OUTPUT?

20

Copyrigh

t © D

ionysiou

2010

#include <iostream> using namespace std;

int main() { int i;

i = 1;

while (i <= 10) { cout << i << “ “; i += 2; }

return 0; }

while LOOP (CONT.) – WHAT IS THE OUTPUT?

21

Copyrigh

t © D

ionysiou

2010

#include <iostream> using namespace std;

int main() { int i;

i = 11;

while (i <= 10) { cout << i << “ “; i += 2; }

return 0; }

while LOOP (CONT.) – WHAT IS THE OUTPUT?

22

Copyrigh

t © D

ionysiou

2010 #include <iostream> using namespace std;

int main() { int i;

i = 0;

while (i <= 10) { cout << i << “ “; i += 2; }

cout << i << endl;

return 0; }

while LOOP (CONT.) – WHAT IS THE OUTPUT?

23

Copyrigh

t © D

ionysiou

2010

while LOOP (CONT.) – WHAT IS THE OUTPUT?

24

Copyrigh

t © D

ionysiou

2010

IN-CLASS EXERCISE

25

! Write a program that prints a table of numbers from 1 to 5 with their squares and cubes. You must use a while statement in this program.

Copyrigh

t © D

ionysiou

2010

IN-CLASS EXERCISE SOLUTIONS

26

Copyrigh

t © D

ionysiou

2010

IN-CLASS EXERCISE

27

! Write a program that prints a Celsius-to-Fahrenheit temperature conversion table. We only want to print Celsius temperatures in the range [5,50] but in increments of 5 degrees.

! Formula to use

Copyrigh

t © D

ionysiou

2010

!

F =95C +32

IN-CLASS EXERCISE SOLUTION

28

Copyrigh

t © D

ionysiou

2010

INTERACTIVE while LOOPS

29

! Modify the previous program so that the user will be prompted to enter the range of valid Celsius temperatures [MINCELSIUS,MAXCELSIUS]

Copyrigh

t © D

ionysiou

2010

SOLUTION

30

Copyrigh

t © D

ionysiou

2010

INTERACTIVE while LOOPS

31

! Modify the previous program so that the user will be prompted to enter the range of valid Celsius temperatures [MINCELSIUS,MAXCELSIUS]. In addition, your program will perform data validation on the user values so that the max temperature is always greater than the min temperature. !  Keep asking for valid temperatures

Copyrigh

t © D

ionysiou

2010

SOLUTION

32

Copyrigh

t © D

ionysiou

2010

ACCUMULATING VALUES

33

Copyrigh

t © D

ionysiou

2010

1.  What happens to num every time the loop in entered? 2.  What happens if count is initialized to 1? 3.  What happens if count++ is replaced by ++count?

ACCUMULATING VALUES

34

Copyrigh

t © D

ionysiou

2010

1.  Modify the program so that every number is added to a total, and the total is printed when the loop terminates.

2.  Then, modify the program to perform data validation on the value of maxNums

ACCUMULATING VALUES

35

Copyrigh

t © D

ionysiou

2010

1.  How can we print the average of the numbers entered?

IN-CLASS EXERCISE

36

! Write a program that reads ten numbers and prints the largest and smallest numbers entered.

Copyrigh

t © D

ionysiou

2010

SOLUTION

37

Copyrigh

t © D

ionysiou

2010

SENTINEL-CONTROLLED LOOP

38

! There are occasions that we don’t know ahead of time how many loop iterations we are going to have! !  Loop terminates when a specific value is encountered

!  Sentinel value !  It must not be in conflict with legitimate values that the

program can accept

!  Examples !  Accept numbers until the user enters -1 !  Repeat the process if the user enters ‘y’ or ‘Y’ !  Keep withdrawing money from your bank account as long as

the balance is positive !  Data validation

Copyrigh

t © D

ionysiou

2010

SENTINEL-CONTROLLED LOOP

39

Copyrigh

t © D

ionysiou

2010

1.  What happens if the user enters negative value for the amount? 2.  Modify the program so that the loop terminates when the

balance is zero or when the user enters -1. In this case, amount must only take positive values.

SENTINEL-CONTROLLED LOOP - SOLUTION

40

Copyrigh

t © D

ionysiou

2010

LECTURE OUTLINE

41

! Basic Loop Structures !  while statement !  for statement ! Nested statement !  do-while statement

Copyrigh

t © D

ionysiou

2010

for STATEMENT

42

!  for loop: Constructed using for statement !  Performs same functionality as while statement

!  In its most common form: •  initializing list sets starting value of one or more counters

•  expression contains max or min value of counter

–  Determines when loop finished

•  altering list provides increment value added to or subtracted from counter each time through loop

Copyrigh

t © D

ionysiou

2010

for STATEMENT

43

!  for statement does not require any items in parentheses be present !  Or that they be used for initializing or altering values in

expression statements !  Two semicolons must be present !  Keeping loop control structure “clean” is an important

programming practice

! Omitting expression results in infinite loop C

opyright ©

Dion

ysiou 2010

for LOOP

44

Copyrigh

t © D

ionysiou

2010

#include <iostream> using namespace std;

int main() {

int counter;

for (counter = 1; counter <= 10; counter++) cout << counter << endl;

cout << “Final value of counter is “ << counter; return 0; }

Initialize counter

Loop continuation condition

Increment counter

for LOOP

45

Copyrigh

t © D

ionysiou

2010

#include <iostream> using namespace std;

int main() {

for (int counter = 1; counter <= 10; counter++) {

cout << counter << endl; cout << “===\n“ } return 0;

}

Initialize counter

Loop continuation condition

Increment counter

for LOOP

46

Copyrigh

t © D

ionysiou

2010

for LOOP

47

Copyrigh

t © D

ionysiou

2010

#include <iostream> using namespace std;

int main() {

for (int counter = 1; counter <= 10; counter++) {

cout << counter << endl; cout << “===\n“ } cout << “The final value of counter is “ << counter; return 0;

}

Initialize counter

Loop continuation condition

Increment counter

COMPILE ERROR!! Variable counter’s scope restricted inside the for loop! counter is undeclared outside the loop!! How can we fix it?

for LOOP

48

Copyrigh

t © D

ionysiou

2010

#include <iostream> using namespace std;

int main() { int a,b;

for (a = 0; a <= 10; a = a + 2) cout << a << endl;

for (a = 3 ; a <= 15 ; a++) cout << a << endl;

for ( ; a <=20 ; a++) cout << a << endl;

for ( ; a <=30 ;) { cout << a << endl;

a = a + 1; } for (int b=2 ; b < 5 ; b++) cout << b+a << endl;

return 0; }

for LOOP

49

Copyrigh

t © D

ionysiou

2010

#include <iostream> using namespace std;

int main() { int a,b; bool notDone;

for (a = 0 , b = 0; a <= 5; a++, b++) cout << a+b << endl;

for (a = 1 , notDone = 1; notDone; a++) if ((a % 5 ) == 0) notDone = 0;

for ( int c =1; ; c++) cout << c << endl;

for (b=2 ; b < 5 ;) cout << b << endl;

for (a = 1; a <=10 ; a++) ;

return 0; }

IN-CLASS EXERCISES

50

! Write programs that use for loops to do the following: !  Create the following output:

!  2 4 6 8 10 12 14

!  Compute the factorial of 5 !  5! = 1x2x3x4x5

!  Compute the sum of the numbers in the range [-5,5] !  Compute the sum of all even numbers in the range [-5,5] !  Compute the product of 1x3x5x7x9

Copyrigh

t © D

ionysiou

2010

WHEN TO USE for? WHEN TO USE while?

51

! Both loops are pretest loops

! Both loops can be used to construct !  Fixed count loop !  Variable condition loop

!  In most languages !  for is used for fixed count !  while is used for variable condition count

Copyrigh

t © D

ionysiou

2010

LECTURE OUTLINE

52

! Basic Loop Structures !  while statement !  for statement !  do-while statement ! Nested statement

Copyrigh

t © D

ionysiou

2010

do-while LOOP

53

!  It is a posttest loop !  Allows at least one loop iteration before the condition is

evaluated at the end of the loop

!  do-while statement can always replace or be replaced by equivalent while or for statement !  If you need something to execute at-least-once it is

clearer to use a do-while loop !  Remember to end the expression with a ;

Copyrigh

t © D

ionysiou

2010

do-while LOOP

54

Copyrigh

t © D

ionysiou

2010

do-while LOOP

55

Copyrigh

t © D

ionysiou

2010

#include <iostream> using namespace std;

int main() {

int counter=1;

do { cout << counter << endl; counter++; } while (counter <= 10);

return 0; }

do-while LOOP – VALIDITY CHECKS

56

!  do-while statement useful in filtering user-entered input and providing data validation checks

Copyrigh

t © D

ionysiou

2010

do-while LOOP – MENU-DRIVEN APPLICATION

57

Copyrigh

t © D

ionysiou

2010

LECTURE OUTLINE

58

! Basic Loop Structures !  while statement !  for statement !  do-while statement ! Nested statement

Copyrigh

t © D

ionysiou

2010

NESTED STATEMENTS

59

! Nested loops: Loop contained within another loop !  Inner and outer loops

!  All statements in inner loop contained within boundaries of outer loop

!  Use different variables to control each loop

! Very helpful when working with matrices

Copyrigh

t © D

ionysiou

2010

NESTED STATEMENTS

60

Copyrigh

t © D

ionysiou

2010