Chapter 5. Looping - PowerPoint PPT Presentation

1 / 67
About This Presentation
Title:

Chapter 5. Looping

Description:

Title: Chapter 1. Introduction to Computers and Programming Author: Catherine Wyman Last modified by: Tony Gaddis Created Date: 8/31/1999 9:01:44 PM – PowerPoint PPT presentation

Number of Views:51
Avg rating:3.0/5.0
Slides: 68
Provided by: Catherin253
Category:

less

Transcript and Presenter's Notes

Title: Chapter 5. Looping


1
Chapter 5. Looping
2
5.1 The Increment and Decrement Operators
  • and -- are operators that add and subtract one
    from their operands.
  • num num 1
  • num 1
  • num

3
Program 5-1
  • // This program demonstrates the increment and
    decrement
  • // operators.
  •  
  • include ltiostream.hgt
  • void main(void)
  • int bigVal 10, smallVal 1
  •  
  • cout ltlt "bigVal is " ltlt bigVal
  • ltlt " and smallVal is " ltlt smallVal ltlt endl
  • smallVal
  • bigVal--

Program continues
4
Program continued from previous slide.
  • cout ltlt "bigVal is " ltlt bigVal
  • ltlt " and smallVal is " ltlt smallVal ltlt endl
  • smallVal
  • --bigVal
  • cout ltlt "bigVal is " ltlt bigVal
  • ltlt " and smallVal is " ltlt smallVal ltlt endl

5
Program Output
  • bigVal is 10 and smallVal is 1
  • bigVal is 9 and smallVal is 2
  • bigVal is 8 and smallVal is 3

6
Program 5-2
  • //This program demonstrates the prefix and
    postfix modes of the
  • // increment and decrement operators.
  • include ltiostream.hgt
  • void main(void)
  • int bigVal 10, smallVal 1
  •   cout ltlt "bigVal starts as " ltlt bigVal
  • cout ltlt " and smallVal starts as " ltlt smallVal
    ltlt endl
  • cout ltlt "bigVal-- " ltlt bigVal-- ltlt endl
  • cout ltlt "smallVal " ltlt smallVal ltlt endl
  • cout ltlt "Now bigVal is " ltlt bigVal ltlt endl
  • cout ltlt "Now smallVal is " ltlt smallVal ltlt endl
  • cout ltlt "--bigVal " ltlt --bigVal ltlt endl
  • cout ltlt "smallVal " ltlt smallVal ltlt endl

7
Program Output
  • bigVal starts as 10 and smallVal starts as 1
  • bigVal-- 10
  • smallVal 1
  • Now bigVal is 9
  • Now smallVal is 2
  • --bigVal 8
  • smallVal 3

8
Using and -- in Mathematical Expressions
  • a 2
  • b 5
  • c a b
  • cout ltlt a ltlt ltlt b ltlt ltlt c
  • Results 2 6 10

9
Using and -- in Relational Expressions
  • x 10
  • if ( x gt 10)
  • cout ltlt x is greater than 10.\n
  • Two operations are happening
  • the value in x is tested to determine if it is
    greater than 10
  • then x is incremented

10
5.2 Introduction to Loops - The while Loop
  • A loop is part of a program that repeats.
  • A while loop is a pre test loop - the
    expression is tested before the loop is executed
  • while (expression)
  • statement

11
Program 5-3
  • // This program demonstrates a simple while loop.
  • include ltiostream.hgt
  • void main(void)
  • int number 0
  •   cout ltlt "This program will let you enter number
    after\n"
  • cout ltlt "number. Enter 99 when you want to quit
    the "
  • cout ltlt "program.\n"
  • while (number ! 99)
  • cin gtgt number

12
Program Output with Example Input
  • This program will let you enter number after
    number. Enter 99 when you want to quit the
    program.
  • 1 Enter
  • 2 Enter
  • 30 Enter
  • 75 Enter
  • 99 Enter

13
Terminating a Loop
  • A loop that does not have a way of stopping is
    called an infinite loop
  • int test 0
  • while (test lt 10)
  • cout ltlt Hello\n
  • A null statement is also an infinite loop, but it
    does nothing forever
  • while (test lt 10)

14
Programming Style and the while Loop
  • If there is only one statement repeated by the
    loop, it should appear on the line after the
    while statement and be indented one additional
    level
  • If the loop repeats a block, the block should
    begin on the line after the while statement and
    each line inside the braces should be indented

15
5.3 Counters
  • A counter is a variable that is incremented or
    decremented each time a loop iterates.

16
Program 5-4
  • // This program displays the numbers 1 through 10
    and
  • // their squares.
  • include ltiostream.hgt
  • void main(void)
  • int num 1 // Initialize counter
  • cout ltlt "number number Squared\n"
  • cout ltlt "-------------------------\n"
  • while (num lt 10)
  • cout ltlt num ltlt "\t\t" ltlt (num num) ltlt endl
  • num // Increment counter

17
Program Output
  • number number Squared
  • -------------------------1 12
    43 94
    165 256 367
    498 649
    8110 100

18
Program 5-5
  • // This program displays the numbers 1 through 10
    and
  • // their squares.
  •  include ltiostream.hgt
  •  void main(void)
  • int num 0
  •   cout ltlt "number number Squared\n"
  • cout ltlt "-------------------------\n"
  • while (num lt 10)
  • cout ltlt num ltlt "\t\t" ltlt (num num) ltlt endl

19
Program Output
  • number number Squared
  • -------------------------1 12
    43 94
    165 256 367
    498 649
    8110 100

20
5.4 Letting the User Control the Loop
  • We can let the user indicate the number of times
    a loop should repeat.

21
Program 5-6
  • // This program averages a set of test scores for
    multiple
  • // students. It lets the user decide how many.
  • include ltiostream.hgt
  • void main(void)
  • int numStudents, count 0
  •  
  • cout ltlt "This program will give you the average
    of three\n"
  • cout ltlt "test scores per student.\n"
  • cout ltlt "How many students do you have test
    scores for? "
  • cin gtgt numStudents
  • cout ltlt "Enter the scores for each of the
    students.\n"
  • cout.precision(2)

Program continues
22
Program continued from previous slide.
  • while (count lt numStudents)
  • int score1, score2, score3
  • float average
  • cout ltlt "\nStudent " ltlt count ltlt " "
  • cin gtgt score1 gtgt score2 gtgt score3
  • average (score1 score2 score3) / 3.0
  • cout ltlt "The average is " ltlt average ltlt ".\n"

23
Program Output with Example Input
  • This program will give you the average of three
    test scores per student.
  • How many students do you have test scores for? 3
    Enter
  • Enter the scores for each of the students.
  • Student 1 75 80 82 Enter
  • The average is 79.
  • Student 2 85 85 90 Enter
  • The average is 86.67. 
  • Student 3 60 75 88 Enter
  • The average is 74.33.

24
5.5 Keeping a Running Total
  • A running total is a sum of numbers that
    accumulates with each iteration of a loop. The
    variable used to keep the running total is called
    an accumulator.

25
Program 5-7
  • // This program takes daily sales figures over a
    period of
  • // time and calculates their total.
  • include ltiostream.hgt
  • void main(void)
  • int days, count 0
  • float total 0.0
  •  
  • cout ltlt "For how many days do you have sales
    figures? "
  • cin gtgt days

Program continues
26
Program continues
  • while (count lt days)
  • float sales
  • cout ltlt "Enter the sales for day " ltlt count ltlt
    " "
  • cin gtgt sales
  • total sales
  • cout.precision(2)
  • cout.setf(iosfixed iosshowpoint)
  • cout ltlt "The total sales are " ltlt total ltlt
    endl

27
Program Output with Example Input
  • For how many days do you have sales figures? 5
    Enter
  • Enter the sales for day 1 489.32 Enter
  • Enter the sales for day 2 421.65 Enter
  • Enter the sales for day 3 497.89 Enter
  • Enter the sales for day 4 532.37 Enter
  • Enter the sales for day 5 506.92 Enter
  • The total sales are 2448.15

28
5.6 Sentinels
  • A sentinel is a special value that marks the end
    of a list of values.

29
Program 5-8
  • // This program calculates the total number of
    points a
  • // soccer team has earned over a series of games.
    The user
  • // enters a series of point values, then -1 when
    finished.
  •  
  • include ltiostream.hgt
  • void main(void)
  • int count 0, points 0, total 0
  • cout ltlt "Enter the number of points your team
    has earned\n"
  • cout ltlt "so far in the season, then enter -1
    when\n"
  • cout ltlt "finished.\n"

Program continues
30
Program continued from previous slide.
  • while (points ! -1)
  • count
  • cout ltlt "Enter the points for game " ltlt count
    ltlt " "
  • cin gtgt points
  • if (points ! -1)
  • total points
  • cout ltlt "The total points are " ltlt total ltlt
    endl

31
Program Output with Example Input
  • Enter the number of points your team has earned
    so far in the season, then enter -1 when you are
    finished.
  • Enter the points for game 1 7 Enter
  • Enter the points for game 2 9 Enter
  • Enter the points for game 3 4 Enter
  • Enter the points for game 4 6 Enter
  • Enter the points for game 5 8 Enter
  • Enter the points for game 6 -1 Enter
  • The total points are 34

32
5.7 The do-while Loop and for Loops
  • In addition to the while loop, C also offers
    the do-while and for loops.
  • A do-while loop is similar to a while loop, but
    in post-test format
  • do
  • statement
  • while (expression)

33
Program 5-9
  • //This program averages 3 test scores. It repeats
    as many times as
  • // the user wishes
  • include ltiostream.hgt
  • void main(void)
  • int score1, score2, score3
  • float average
  • char again
  • do
  • cout ltlt "Enter 3 scores and I will average
    them "
  • cin gtgt score1 gtgt score2 gtgt score3
  • average (score1 score2 score3) / 3.0
  • cout ltlt "The average is " ltlt average ltlt ".\n"
  • cout ltlt "Do you want to average another set?
    (Y/N) "
  • cin gtgt again
  • while (again 'Y' again 'y')

34
 Program Output with Example Input
  • Enter 3 scores and I will average them 80 90 70
    Enter
  • The average is 80.
  • Do you want to average another set? (Y/N) y
    Enter
  • Enter 3 scores and I will average them 60 75 88
    Enter
  • The average is 74.333336.
  • Do you want to average another set? (Y/N) n
    Enter

35
Program 5-10
  • // This program displays a menu and asks the user
    to make a
  • // selection. A switch statement determines which
    item the
  • // user has chosen. A do-while loop repeats the
    program until
  • // the user selects item 4 from the menu.
  •  
  • include ltiostream.hgt
  •  
  • void main(void)
  • int choice, months
  • float charges
  •  
  • cout.setf(iosfixed iosshowpoint)
  • cout.precision(2)

Program continues
36
Program continued from previous slide.
  • do
  • cout ltlt "\n\t\tHealth Club Membership
    Menu\n\n"
  • cout ltlt "1. Standard Adult Membership\n"
  • cout ltlt "2. Child Membership\n"
  • cout ltlt "3. Senior Citizen Membership\n"
  • cout ltlt "4. Quit the Program\n\n"
  • cout ltlt "Enter your choice "
  • cin gtgt choice
  • if (choice ! 4)
  • cout ltlt "For how many months? "
  • cin gtgt months

Program continues
37
Program continued from previous slide.
  • switch (choice)
  • case 1 charges months 40.00
  • cout ltlt "The total charges are "
  • cout ltlt charges ltlt endl
  • break
  • case 2 charges months 20.00
  • cout ltlt "The total charges are "
  • cout ltlt charges ltlt endl
  • break
  • case 3 charges months 30.00
  • cout ltlt "The total charges are "
  • cout ltlt charges ltlt endl
  • break

Program continues
38
 Program continued from previous slide.
  • case 4 cout ltlt "Thanks for using this
    " cout ltlt "program.\n" break
  • default cout ltlt "The valid choices are 1-4.
    " cout ltlt "Try again.\n" while
    (choice ! 4)

Program continues
39
Program Output with Example Input
  • Health Club Membership Menu 1. Standard
    Adult Membership2. Child Membership3. Senior
    Citizen Membership4. Quit the ProgramEnter
    your choice 1 EnterFor how many months 12
    EnterThe total charges are 480.00 
    Health Club Membership Menu 1. Standard
    Adult Membership2. Child Membership3. Senior
    Citizen Membership4. Quit the ProgramEnter
    your choice 4 EnterThanks for using this
    program.

40
The for Loop
  • Ideal for situations that require a counter
    because it has built-in expressions that
    initialize and update variables.
  • for (initialization test update)
  • statement

41
Program 5-11
  • // This program displays the numbers 1 through 10
    and
  • // their squares.
  • include ltiostream.hgt
  • void main(void)
  • int num
  •  
  • cout ltlt Number Number Squared\n"
  • cout ltlt "-------------------------\n"
  •  
  • for (num 1 num lt 10 num)
  • cout ltlt num ltlt "\t\t" ltlt (num num) ltlt endl

42
Program Output
  • Number Number Squared
  • -------------------------1 12
    43 94
    165 256 367
    498 649
    8110 100

43
Omitting the for Loops Expressions
  • int num 1
  • for ( num lt 10 num)
  • cout ltlt num ltlt \t\t ltlt (num num) ltlt endl

44
Using initialization and update lists
  • You may need to perform more than one statement
    in the initialization part of a for loop. In that
    case, just separate the statements with commas.

45
Program 5-12
  • // This program takes daily sales figures for one
    week
  • // and calculates their total.
  •  
  • include ltiostream.hgt
  • void main(void)
  • const int days 7
  • int count
  • float total
  • for (count 1, total 0.0 count lt days
    count)
  • float sales
  • cout ltlt "Enter the sales for day " ltlt count ltlt
    " "

Program continues
46
Program continued from previous slide.
  • cin gtgt sales
  • total sales
  • cout.precision(2)
  • cout.setf(iosfixed iosshowpoint)
  • cout ltlt "The total sales are " ltlt total ltlt
    endl

47
Program Output with Example Input
  • Enter the sales for day 1 489.32 Enter
  • Enter the sales for day 2 421.65 Enter
  • Enter the sales for day 3 497.89 Enter
  • Enter the sales for day 4 532.37 Enter
  • Enter the sales for day 5 506.92 Enter
  • Enter the sales for day 6 489.01 Enter
  • Enter the sales for day 7 476.55 Enter
  • The total sales are 3413.71

48
5.8 Other forms of the update expression
  • Incrementing the counter by something besides 1
  • for(number 2 number lt 100 number 2)
  • cout ltlt number ltlt endl // print the even numbers
    2 100
  • Going backwards
  • for(number 10 number gt 0 number--)
  • cout ltlt number ltlt endl //count from 10 to 0
  • A stand-alone for loop
  • //This one prints the integers from 1 to 10
  • for(number 1 number lt 10 cout ltlt number)
  • There are quite a few variations, try some of
    your own!

49
5.8 Focus on Software Engineering Deciding Which
Loop to Use
  • The while Loop
  • A pre-test loop.
  • Use when you do not want the loop to iterate if
    the condition is false from the beginning.
  • Ideal if you want to use a sentinel.
  • The do-while Loop
  • A post-test loop.
  • Use if you always want the loop to iterate at
    least once.
  • The for Loop
  • A pre-test loop.
  • Automatically executes an update expression at
    the end of each iteration.
  • Ideal for situations where a counter variable is
    needed.
  • Used when the exact number of required iterations
    is known.

50
5.9 Focus on Software Engineering Nested Loops
  • A loop that is inside another loop is called a
    nested loop.

51
Program 5-13
  • // This program averages test scores. It asks the
    user for the
  • // number of students and the number of test
    scores per student.
  • include ltiostream.hgt
  • void main(void)
  • int numStudents, numTests, total
  • float average
  •  
  • cout ltlt "This program averages test scores.\n"
  • cout ltlt "For how many students do you have
    scores? "
  • cin gtgt numStudents
  • cout ltlt "How many test scores does each student
    have? "
  • cin gtgt numTests

Program continues
52
Program continued from previous slide.
  • for (int count1 1 count1 lt numStudents
    count1)
  • total 0 // Initialize accumulator
  • for (int count2 1 count2 lt numTests
    count2)
  • int score
  • cout ltlt "Enter score " ltlt count2 ltlt " for "
  • cout ltlt "student " ltlt count1 ltlt " "
  • cin gtgt score
  • total score // accumulate running total
  • average total / numTests
  • cout ltlt "The average score for student " ltlt
    count1
  • cout ltlt " is " ltlt average ltlt ".\n\n"

53
Program Output with Example Input
  • This program averages test scores.
  • For how many students do you have scores? 2
    Enter
  • How many test scores does each student have? 3
    Enter
  • Enter score 1 for student 1 84 Enter
  • Enter score 2 for student 1 79 Enter
  • Enter score 3 for student 1 97 Enter
  • The average for student 1 is 86. 
  • Enter score 1 for student 2 92 Enter
  • Enter score 2 for student 2 88 Enter
  • Enter score 3 for student 2 94 Enter
  • The average for student 2 is 91.

54
5.10 Breaking Out of a Loop
  • The break statement causes a loop to terminate
    early.

55
Program 5-14
  • // This program raises the user's number to the
    powers
  • // of 0 through 10.
  • include ltiostream.hgt
  • include ltmath.hgt
  • void main(void)
  • int value
  • char choice
  •  
  • cout ltlt "Enter a number "
  • cin gtgt value
  • cout ltlt "This program will raise " ltlt value
  • cout ltlt " to the powers of 0 through 10.\n"

Program continues
56
Program continued from previous slide.
  • for (int count 0 count lt 10 count)
  • cout ltlt value ltlt " raised to the power of "
  • cout ltlt count ltlt " is " ltlt pow(value, count)
  • cout ltlt "\nEnter Q to quit or any other key "
  • cout ltlt "to continue. "
  • cin gtgt choice
  • if (choice 'Q' choice 'q')
  • break

57
Program Output
  • Enter a number 2 Enter
  • This program will raise 2 to the powers of 0
    through 10.
  • 2 raised to the power of 0 is 1
  • Enter Q to quit or any other key to
  • continue. C Enter
  • 2 raised to the power of 1 is 2
  • Enter Q to quit or any other key to continue. C
    Enter
  • 2 raised to the power of 2 is 4
  • Enter Q to quit or any other key to continue. Q
    Enter

58
5.11 Using break in a nested loop
  • The break statement below breaks out of the inner
    loop but NOT the outer loop
  • for(int row 0 row lt 5 row)
  • //begin outer loop
  • for(star 0 star lt 20 star)
  • //begin inner loop
  • // some statements
  • break
  • // some more statements
  • //end inner loop
  • //end outer loop

59
5.11 The continue Statement
  • The continue statement causes a loop to stop its
    current iteration and begin the next one.

60
Program 5-15
  • // This program calculates the charges for video
    rentals.
  • // Every third video is free.
  •  
  • include ltiostream.hgt
  • include ltiomanip.hgt
  • void main(void)
  • int videoCount 1, numVideos
  • float total 0.0
  • char current
  • cout ltlt "How many videos are being rented? "
  • cin gtgt numVideos

Program continues
61
Program continued from previous slide.
  • do
  • if ((videoCount 3) 0)
  • cout ltlt "Video " ltlt videoCount ltlt " is
    free!\n"
  • continue
  • cout ltlt "Is video " ltlt videoCount
  • cout ltlt " a current release? (Y/N)"
  • cin gtgt current
  • if (current 'Y' current 'y')
  • total 3.50
  • else
  • total 2.50
  • while (videoCount lt numVideos)

Program continues
62
Program continued from previous slide.
  • cout.precision(2)
  • cout.setf(iosfixed iosshowpoint)
  • cout ltlt "The total is " ltlt total

63
Program Output with Example Input
  • How many Videos are being rented? 6 Enter
  • Is video 1 a current release? y Enter
  • Is video 2 a current release? n Enter
  • Video 3 is free!
  • Is video 4 a current release? n Enter
  • Is video 5 a current release? y Enter
  • Video 6 is free!
  • The total is 12.00

64
5.12 Using Loops for Input Validation
  • Loops can be used to create input routines that
    repeat until acceptable data is entered.

65
Program 5-16
  • // This program calculates the number of soccer
    teams
  • // that a youth league may create from the number
    of
  • // available players. Input validation is
    demonstrated
  • // with do-while loops.
  •  
  • include ltiostream.hgt
  •  
  • void main(void)
  • int players, teamPlayers, numTeams, leftOver
  •  
  • // Get the number of players per team.
  • cout ltlt How many players you wish per team?\n
  • cout ltlt (Enter a value in the range 9 - 15) "
  • cin gtgt teamPlayers

Program continues
66
Program continued from previous slide.
  • while (teamPlayers lt 9 teamPlayers gt 15) //
    Validate input
  • cout ltlt "You should have at least 9 but no\n"
  • cout ltlt "more than 15 per team.\n"
  • cout ltlt How many players do you wish per
    team?
  • cin gtgt teamPlayers
  • // Get the number of players available
  •   cout ltlt How many players are available?
  • cin gtgt players
  • while (players lt 0) // Validate input
  • cout ltlt "Please enter a positive number.\n"
  • cin gtgt players
  • // Perform calculations
  • numTeams players / teamPlayers
  • leftOver players teamPlayers
  • cout ltlt "There will be " ltlt numTeams ltlt " teams
    with\n"

67
Program Output with Example Input
  • How many players you wish per team?
  • (Enter a value in the range 9 15) 4Enter
  • You should have at least 9 but no
  • more than 15 per team.
  • How many players you wish per team? 12Enter
  • How many players are available? -142 Enter
  • Please enter a positive number 142Enter
  • There will be 11 teams with 10 players left over.
Write a Comment
User Comments (0)
About PowerShow.com