Loops continued - PowerPoint PPT Presentation

About This Presentation
Title:

Loops continued

Description:

cout 'Two raised to the ' number ' power is ' result ... Implication. Generate the solutions systematically. We will make sure that a = b = c = d ... – PowerPoint PPT presentation

Number of Views:31
Avg rating:3.0/5.0
Slides: 30
Provided by: andrew184
Category:

less

Transcript and Presenter's Notes

Title: Loops continued


1
Programming
  • Loops (continued)

2
The for Statement
  • Syntax
  • for (ForInit ForExpression PostExpression)
  • Action
  • How it works
  • Execute ForInit statement
  • While ForExpression is true
  • Execute Action
  • Execute PostExpression
  • Example
  • int i
  • for(i1 ilt20 i)
  • cout ltlt "i is " ltlt i ltlt endl

3
Iteration Using the for Statement
ForInit
ForExpression
true
false
Action
PostExpression
4
N! (for)
  • int number, factorial, n
  • cout ltlt "Enter number "
  • cin gtgt number
  • factorial 1
  • for(n1 nltnumber n)
  • factorial n
  • cout ltlt "The factorial of " ltlt number
  • ltlt " is " ltlt factorial ltlt endl

5
2N (for)
  • int number, result, n
  • cout ltlt "Enter number "
  • cin gtgt number
  • result 1
  • for(n1 nltnumber n)
  • result 2
  • cout ltlt "Two raised to the " ltlt number
  • ltlt " power is " ltlt result ltlt endl

6
Iteration
  • Key Points
  • stopping criterion Make sure there is a
    statement that will eventually stop the loop
  • initializationMake sure to initialize loop
    counters correctly
  • side effect Loop counters should not be
    modified in the loop

7
The Lazy Student Problem
  • Four students working together on HW1
  • Problem will take 200 hours of work that can be
    done over the next few weeks
  • The laziest student convinces the other three
    students to draw straws
  • Each straw is marked with an amount
  • The amount represents both the number of days and
    the numbers of hours per day that the student
    would work
  • Example
  • If the straw was marked three then the student
    who drew it would work for three hours per day
    for three days
  • What are the best markings of the straws for a
    clever, lazy student?

8
Observations
  • Need to find sets of numbers a, b, c, and d such
    that
  • a2 b2 c2 d2 200
  • Maximal legal number is 14 as 152 equals 225
  • which is greater than 200
  • Minimal legal number is 1
  • No advantage to listing the combinations more
    than once
  • Implication
  • Generate the solutions systematically
  • We will make sure that a lt b lt c lt d

9
Method
  • Generate all possibilities for a where for each a
    possibility
  • Generate all possibilities of b where for each b
    possibility
  • Generate all possibilities for c where for each c
    possibility
  • Generate all possibilities for d where for each d
    possibility
  • Determine whether the current combination is a
    solution

10
Nested For Loop Solution
  • int a, b, c, d
  • for(a1 alt14 a)
  • for(ba blt14 b)
  • for(cb clt14 c)
  • for(dc dlt14 d)
  • if(aa bb cc dd 200)
  • cout ltlt a ltlt " " ltlt b ltlt " " ltlt c
  • ltlt " " ltlt d ltlt endl

11
The Do-While Statement
  • Syntax
  • do Action
  • while (Expression)
  • How it works
  • Execute Action
  • if Expression is true then execute Action again
  • Repeat this process until Expression evaluates to
    false
  • Action is either a single statement or a group of
    statements within braces

Action
true
Expression
false
12
N! (do-while)
  • int number, factorial, n
  • cout ltlt "Enter number "
  • cin gtgt number
  • factorial 1
  • n 1
  • do
  • factorial n
  • n
  • while(n lt number)
  • cout ltlt "The factorial of " ltlt number
  • ltlt " is " ltlt factorial ltlt endl

13
2N (do-while)
  • int number, result, n
  • cout ltlt "Enter number "
  • cin gtgt number
  • result 1
  • n 1
  • do
  • result 2
  • n
  • while (n lt number)
  • cout ltlt "Two raised to the " ltlt number
  • ltlt " power is " ltlt result ltlt endl

14
Maximum (do-while)
  • int value //input value
  • int max0 //maximum value
  • do
  • cout ltlt "Enter a value (-1 to stop) "
  • cin gtgt value
  • if(value gt max)
  • max value
  • while(value!-1)
  • cout ltlt "The maximum value found is "
  • ltlt " is " ltlt max ltlt endl

15
Waiting for a Reply
  • char reply
  • do
  • cout ltlt "Continue(y/n) "
  • cin gtgt reply
  • //do something
  • while(reply!'n')

16
Which Loop to Use?
  • For loop
  • Best for calculations that are repeated a fixed
    number of times using a value that is changed by
    an equal amount (usually 1) each time through the
    loop.
  • While loop
  • You want to repeat a segment of code without
    knowing exactly how many times it will be
    repeated.
  • You are working with user input
  • There are situations when the code segment should
    not be executed at all.
  • Do-while loop
  • The code segment should always be executed at
    least once.
  • Otherwise, the situations when do-while loops are
    used are very similar to those when while loops
    are used.

17
A simpler lazy student problem
  • three straws a, b, c
  • minimum value 1
  • maximum value 3
  • a lt b lt c
  • 1 1 1
  • 1 1 2
  • 1 1 3
  • 1 2 2
  • 1 2 3
  • 1 3 3
  • 2 2 2
  • 2 2 3
  • 2 3 3
  • 3 3 3
  • for (a1 alt3 a)
  • for (ba blt3 b)
  • for (cb blt3 c)
  • cout ltlt a ltlt b ltlt c ltlt endl

18
How to Stop a Loop
  • Known number of iterations before the loop stops
    (for)
  • Test for a user-controlled condition before or
    after each iteration (while, do-while)
  • Use the break command.

19
break
  • The break command is the same as the one used
    previously in switch.
  • break leaves the current loop immediately. It is
    recommended that break be used for situations
    where the loop needs to be terminated immediately
    (e.g., due to user intervention or if a fatal
    error occurs).

20
Maximum (while with break)
  • int value0 //input value
  • int max0 //maximum value
  • while(true)
  • cout ltlt "Enter a value (-1 to stop) "
  • cin gtgt value
  • if(value gt max)
  • max value
  • if(value-1)
  • break
  • cout ltlt "The maximum value found is "
  • ltlt " is " ltlt max ltlt endl
  • MAX

21
Common Loop Errors
  • while(balance ! 0.0)
  • balance balance - amount
  • This will lead to an infinite loop!
  • for(n1 nltcount n)
  • cout ltlt "hello" ltlt endl
  • "hello" only printed once!

22
Common Loop Errors (with correct indentation and
curly braces)
  • while(balance ! 0.0)
  • // do nothing infinitely !!
  • balance balance - amount
  • This will lead to an infinite loop!
  • for(n1 nltcount n)
  • // do nothing n times!!
  • cout ltlt "hello" ltlt endl
  • "hello" only printed once!

23
Common Loop Errors
  • while(balance ! 0.0)
  • balance balance - amount
  • balance may not become equal zero due to
    numerical inaccuracies
  • int power
  • while(power lt 1000)
  • cout ltlt "Next power of N is " ltlt power ltlt endl
  • power n
  • Be sure to initialize to 0 a variable used for
    sums
  • Be sure to initialize to 1 a variable used for
    products

24
Nested Loops
  • Nested loops are loops within loops. They are
    similar in principle to nested if and if-else
    statements.
  • Many applications require nested loops.

25
Nested Loops
  • // Find the average score on 8 lab assignments
  • int n, lastlab8
  • double avg, score, tscore
  • char resp
  • do
  • tscore 0
  • for(n1 nltlastlab n)
  • cout ltlt "Enter students score for lab " ltlt n
    ltlt " "
  • cin gtgt score
  • tscore score
  • avg tscore/double(lastlab)
  • cout ltlt "The average score is " ltlt avg ltlt endl
  • cout ltlt "Enter another student (y/n)? "
  • cin gtgt resp
  • while(resp'y' resp'Y')

26
Diamond Pattern
  • Print out the following diamond pattern

27
Diamond Pattern
  • Subproblem
  • print out the upper half
  • print out the lower half
  • Print out upper half
  • row 1 print 4 spaces, 1 star
  • row 2 print 3 spaces, 3 stars
  • row 3 print 2 spaces, 5 stars
  • row 4 print 1 space, 7 stars
  • row 5 print 0 spaces, 9 stars
  • Algorithm Refinement
  • row 1 print (5-row) spaces, (2row - 1) stars
  • row 2 print (5-row) spaces, (2row - 1) stars
  • row 3 print (5-row) spaces, (2row - 1) stars
  • row 4 print (5-row) spaces, (2row - 1) stars
  • row 5 print (5-row) spaces, (2row - 1) stars

28
Diamond Pattern
  • int row, space, star // loop counters
  • for(row1 rowlt5 row) //top half
  • for(space1 spacelt5-row space)
  • cout ltlt " "
  • for(star1 starlt2row-1 star)
  • cout ltlt ""
  • cout ltlt endl
  • for(row4 rowgt1 row--) //bottom half
  • for(space1 spacelt5-row space)
  • cout ltlt " "
  • for(star1 starlt2row-1 star)
  • cout ltlt ""
  • cout ltlt endl

29
Multiplication Table
  • // Program to output the
  • // multiplication table
  • int i //Outer loop counter
  • int j //Inner loop counter
  • for(i1 ilt10 i)
  • for(j1 jlt10 j)
  • cout ltlt ij ltlt " "
  • cout ltlt endl
Write a Comment
User Comments (0)
About PowerShow.com