0% found this document useful (0 votes)
11 views

PreludeProgramming6ed pp06

The document discusses combining loops and decision structures to create more complex programs. It provides examples of nesting loops within selection structures and vice versa. The examples demonstrate tracking user input with counters, validating data, and exiting loops early under certain conditions. Functions like Length_Of() and formatting output are also covered.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

PreludeProgramming6ed pp06

The document discusses combining loops and decision structures to create more complex programs. It provides examples of nesting loops within selection structures and vice versa. The examples demonstrate tracking user input with counters, validating data, and exiting loops early under certain conditions. Functions like Length_Of() and formatting output are also covered.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Chapter 6

More About Loops and


Decisions

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


6.1  Combining  Loops  With  If-Then  
Statements
By  combining  loops  and  decision  structures,  programs  become  much  more  
complex.    
Loops  can  be  nested  inside  selecJon  structures  and  selecJons  can  be  nested  
inside  loops.  
Loops  can  be  nested  inside  other  loops.  
Using  mulJple  combinaJons  of  these  structures  allows  for  limitless  possibiliJes!  

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


Exi8ng  a  Loop  Early

 One  reason  to  nest  a  selecJon  structure  inside  a  loop  is  to  
allow  the  loop  to  end  before  the  test  condiJon  has  been  
met  for  any  reason.  For  example:  
ØIf  the  user  has  entered  an  incorrect  value  that  would  
cause  an  error    
ØIf  the  user  has  entered  a  required  response  and  the  
program  can  conJnue  without  further  iteraJons  

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


Example:  Exi8ng  the  Loop  When  There’s  No  More  Money
1 Declare Cost, Total, Max As Float
2 Declare Count As Integer
3 Set Total = 0
4 Write “Enter the maximum amount you want to spend: $ “
5 Input Max
6 For (Count = 1; Count < 11; Count++)
7 Write “Enter the cost of an item: “
8 Input Cost
9 Set Total = Total + Cost
10 If Total > Max Then
11 Write “You have reached your spending limit.”
12 Write “You cannot buy this item or anything else.”
13 Set Total = Total – Cost
14 Exit For
15 End If
16 Write “You have bought “ + Count + “ items.”
17 End For
18 Write “Your total cost is $ “ + Total

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


Example:  The  Guessing  Game  using  a  Do…While  loop
1 Declare SecretNumber, Count, Guess As Integer
2 Write “Enter a secret number: “
3 Input SecretNumber
4 Clear Screen
5 Set Count = 1
6 Do
7 Write “Guess the secret number: “
8 Input Guess
9 If Guess == SecretNumber Then
10 Write “You guessed it!”
11 Exit Loop
12 Else
13 Write “Try again”
14 End If
15 Set Count = Count + 1
16 While Count <= 5

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


Example:  Combining  Loops,  Decisions,  and  Valida8ng  Data    
                                                       Compu8ng  valid  square  roots
1 Declare Number, Root As Float
2 Declare Response As Character
3 Write “Do you want to find the square root of a number?”
4 Write “Enter ‘y’ for yes, ‘n’ for no: “
5 While Response == “y”
6 Write “Enter a positive number: “
7 Input Number
8 If (Number >= 0) Then
9 Set Root = Sqrt(Number)
10 Write “The square root of “ + Number + “ is: “ + Root
11 Else
12 Write “Your number is invalid.”
13 End If
14 Write “Do you want to do this again?”
15 Write “Enter ‘y’ for yes, ‘n’ for no: “
16 Input Response
17 End While

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


6.2  Combining  Loops  and  Decisions  in  Longer  
Programs

 The  example  in  the  next  slide  shows  how  to  keep  track  of  how  many  
posiJve  numbers  and  how  many  negaJve  numbers  are  input  by  a  
user.    
 Uses  for  this  type  of  program:  
Ø  Embed  in  a  larger  program  to  track    various  types  of  entries  
Ø  Use  by  a  college  to  enter  demographic  informaJon  on  students  
Ø  Use  by  a  business  to  track  number  of  items  purchased  that  were  above  or  
below  a  certain  cost  

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


Example:  Keeping  Track  of  User  Input  
1 Declare PositiveCount, NegativeCount, Number As Integer
2 Set PositiveCount = 0
3 Set NegativeCount = 0
4    
Write “Enter a number. Enter 0 when done: “
5 Input Number
6 While Number != 0
7 If Number > 0 Then
8 Set PositiveCount = PositiveCount + 1
9 Else
10 Set NegativeCount = NegativeCount + 1
11 End If
12 Write “Enter a number. Enter 0 when done: “
13 Input Number
14 End While
15 Write “Positive numbers entered: “ + PositiveCount
16 Write “Negative numbers entered: “ + NegativeCount

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


Flowchart  using  a  
selec8on  structure  with  
a  loop  to  keep  track  of  
the  number  of  posi8ve  
and  nega8ve  numbers  
entered

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


The  Length_Of()  Func8on
The  Length_Of()  funcJon  takes  a  string  or  a  string  variable  inside  the  parentheses  and  
returns  the  number  of  characters  in  that  string.  

Ø MyLength = Length_Of(“Hello”)  assigns  the  value  of  5  to  MyLength because  


”Hello”  has  five  characters.  
Ø MyLength = Length_Of(“Good-bye!”)  assigns  the  value  of  9  to  MyLength because  
the  string  has  nine  characters,  including  the  hyphen  and  exclamaJon  point.  

If  Name = “Hermione Hatfield”  then:  


Ø MyLength = Length_Of(Name)  assigns  the  value  of  17  to  MyLength.

If  TheSpace = “ “  then:  
Ø MyLength = Length_Of(TheSpace)  assigns  the  value  of  1  to  MyLength because  a  
space  counts  as  one  character.  
 

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


The  Print  Statement  and  the  newline  Indicator  <NL>
Ø  The  Write statement  indicates  output  to  the  
Code Code
screen  with  the  assumpJon  that  each  new  Write  
Write “Hi” Print “Hi”
statement  would  begin  on  a  new  line.   Write “Ho” Print “Ho” <NL>
Write “Done” Print “Done”
Ø  The  Print  statement  indicates  output  to  the  
screen,  including  the  ability  to  concatenate  variables   Display Display
and  text.  However,  unJl  the  newline  indicator   Hi HiHo
Ho Done
is  used,  it  is    assumed  that  output  from  any   Done
subsequent  Print statements  will  be  on  the  same  
line.  The  newline  indicator  is  <NL>.

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


Using  the  Length_Of()  Func8on  for  FormaRng
1 Declare Name As String
2 Declare Symbol, Choice As Character
  3
4
Declare Number, Count As Integer
Set Count = 0
5 Write “Enter your name: “
6 Input Name
7 Write “Choose one of the following symbols: * or # “
8 Input Symbol
9 Write “Do you want a space between each symbol? Enter ‘Y’ for yes, ‘N’ for no”
10 Input Choice
11 Set Number = Length_Of(Name)
12 Print Name <NL>
13 While Count <= Number
14 If Choice == “y” OR Choice == “Y” Then
15 Print Symbol + “ “
16 Set Count = Count + 2
17 Else
18 Print Symbol
19 Set Count = Count + 1
20 End If
21 End While

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


6.3  Random  Numbers
Random  numbers  are  numbers  whose  values  form  an  
Ø  
unpredictable  sequence.  
Ø  They  have  many  interesJng  applicaJons  in  programming.    
Ø  One  major  use  is  to  provide  an  element  of  chance  in  
computer  games.  
Ø  They  are  also  used  to  simulate  situa7ons  or  processes  in  
business,  mathemaJcs,  engineering,  and  other  disciplines.  

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


The  Random()  Func8on
Ø  Most  programming  languages  contain  a  funcJon  that  is  used  to  generate  a  
sequence  of  random  numbers.  
Ø  The  name  of  this  funcJon  and  the  way  it  works  varies  from  language  to  
language.  
Ø  We  define  a  funcJon  of  the  following  form:  Random()  which  generates  a  
random  number  from  0.0  to  1.0  (including  0.0  but  not  1.0).  
Ø  To  increase  the  range  of  random  numbers  generated,  mulJply  Random()  by  
any  value.  
Ø  To  change  the  spread  of  the  range,  add  an  integer  to  the  values  generated.  
Ø  Use  the  Int()  or  Floor()  funcJon  to  generate  random  integers.  

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


Examples  of  Random  Numbers  Using  the  
Random()Func8on
Ø  If  Random() = 0.3792,  then  Random() * 10 = 3.7920
Ø  If  Random() = 0.0578,  then  Random() * 10 = 0.5780
MulJplying  Random()  by  10  generates  random  numbers  between  0.0 and  
10.0,  not  including  10.0.    
To  generate  only  integer  values,  use  the  Floor()  or  Int()  funcJon:  
Ø  If  Random() = 0.3792,  then  Floor(Random() * 10) = 3
Ø  If  Random()  = 0.0578,  then  Floor(Random()  * 10) = 0
To  change  the  range  of  integers,  add  a  number  to  the  result.  For  example,  adding  
1  to  the  previous  result  will  generate  random  numbers  between  1 and  10.  
Ø  If  Random()  = 0.3792,  then  (Floor(Random()  * 10) + 1) = 4
Ø  If  Random()  = 0.0578,  then  (Floor(Random() * 10) + 1) = 1

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


Genera8ng  Random  Numbers  in  Various  Ranges
If  NewNumber  is  an  integer  variable,  then:  
Ø NewNumber = Floor(Random() * 10) + 1  will  result  in  a  random  
number  between  1  and  10  (inclusive)  
Ø NewNumber = Floor(Random() * 100) + 1  will  result  in  a  random  
number  between  1  and  100  (inclusive)  
Ø NewNumber = Floor(Random() * 10) + 4  will  result  in  a  random  
number  between  4  and  13  (inclusive)  
Ø NewNumber = Floor(Random() * 2)  will  result  in  either  0  or  1
Ø NewNumber = Floor(Random() * 2) + 1  will  result  in  either  1 or  2
 A[er  examining  these  examples,  we  can  conclude  that,  to  generate  a  sequence  of  N  random  integers  
beginning  with  the  integer  M,  use:  
Floor(Random() * N) + M

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


Example:  Flipping  a  Coin
1 Declare Number As Integer
2 Declare Response As Character
3 Write “Do you want to flip a coin? Enter ‘y’ for yes, ‘n’ for no:“
4 Input Response
5 While Response == “y”
6 Set Number = Floor(Random() * 2)
7 If Number == 1 Then
8 Write “Heads”
9 Else
10 Write “Tails”
11 End If
12 Write “Flip again? Enter ‘y’ for yes, ‘n’ for no: “
13 Input Response
14 End While

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


Example:  Winning  at  Dice:  What  number  should  I  bet  on?

Possible  ways  to  roll  the  11  possible  sums


1 + 1 = 2 2 + 1 = 3 3 + 1 = 4 4 + 1 = 5 5 + 1 = 6 6 + 1 = 7

1 + 2 = 3 2 + 2 = 4 3 + 2 = 5 4 + 2 = 6 5 + 2 = 7 6 + 2 = 8

1 + 3 = 4 2 + 3 = 5 3 + 3 = 6 4 + 3 = 7 5 + 3 = 8 6 + 3 = 9

1 + 4 = 5 2 + 4 = 6 3 + 4 = 7 4 + 4 = 8 5 + 4 = 9 6 + 4 = 10

1 + 5 = 6 2 + 5 = 7 3 + 5 = 8 4 + 5 = 9 5 + 5 = 10 6 + 5 = 11

1 + 6 = 7 2 + 6 = 8 3 + 6 = 9 4 + 6 = 10 5 + 6 = 11 6 + 6 = 12

           
Possible  ways  to  roll  a  5:  (1,4), (4,1), (2,3), (3,2)

Possible  ways  to  roll  an  8:  (2,6), (6,2), (3,5), (5,3), (4,4)

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


Example:  Winning  at  Dice:  What  number  should  I  bet  on?
 1 Declare FiveCount, EightCount, K, Die1, Die2, Sum As Integer
 2 Set FiveCount = 0
 3 Set EightCount = 0
 4 For (K = 1; K <= 1000; K++)
 5 Set Die1 = Floor(Random() * 6) + 1
 6 Set Die2 = Floor(Random() * 6) + 1
 7 Set Sum = Die1 + Die2
 8 If Sum == 5 Then
 9 Set FiveCount = FiveCount + 1
 10 End If
 11 If Sum == 8 Then
 12 Set EightCount = EightCount + 1
 13 End If
 14 End For
 15 Write “Number of times sum was 5: ” + FiveCount
 16 Write “Number of times sum was 8: ” + EightCount

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


The  Algorithm  for  a  Pseudorandom  Number
Ø  A  computer  doesn’t  understand,  “Pick  any  number  between  1  and  20.”    
Ø  A  computer  must  receive  instrucJons  from  a  program.  
Ø  Random  numbers  are  o[en  produced  by  means  of  a  mathema7cal  
algorithm.  
Ø A  mathemaJcal  algorithm  is  a  formula  that  instructs  the  computer  how  
to  pick  some  number  in  a  specified  range.  
Ø  An  algorithm  requires  some  beginning  value  to  manipulate.  
Ø  This  starJng  number  is  the  seed  value.  

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


The  Seed  for  a  Pseudorandom  Number
Ø  If  the  same  seed  is  used  each  Jme,  the  numbers  generated  are  not  really  random.  Such  
numbers  are  called  pseudorandom.  
Ø If  the  starJng  value  of  the  algorithm  never  changes,  the  same  sequence  of  numbers  will  be  
produced  each  Jme  the  program  is  executed.  This  may  be  useful  for  debugging  purposes.  
Ø  The  programmer  must  force  the  computer  to  use  a  different  seed  on  each  run  so  that  the  
random  numbers  produced  will  be  unpredictable.  
Ø use  a  seed  that  is  not  predetermined,  like  the  number  of  milliseconds  since  the  beginning  of  the  
current  year    
Ø it  will  only  occur  once  a  year  
Ø forces  a  random  number  generator  to  start  with  a  different  seed  each  Jme    

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


6.4  Nested  Loops

ØWhen  one  loop  is  contained  enJrely  within  another  we  say  that  
they  are  nested  loops.    
Ø The  larger  loop  is  called  the  outer  loop  
Ø The  one  lying  within  it  is  called  the  inner  loop    
ØIt  is  o[en  difficult  to  follow  the  logical  sequence  of  steps  when  
nested  loops  are  implemented.    
ØIt  is  very  important  to  be  able  to  walk  through  (desk  check)  the  
pseudocode  with  paper  and  pencil,  carefully  wriJng  down  the  values  
of  each  variable  at  each  step.  

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


Example

1 Declare OutCount As Integer


OutCount InCount output  
2 Declare InCount As Integer
1   1  
3 For (OutCount = 1; OutCount <=2; OutCount++)
1   2  
4 For (InCount = 1; InCount <=3; InCount++)
1   3  
5 Write OutCount + “: “ + InCount
1   4  
6 End For(InCount)
2   1  
7 Write “ “
2   2  
8 End For(OutCount)
2   3  
2   4  
3  

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


Flowchart  for  the  
nested  loops  on  the  
previous  slide

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


Nes8ng  Other  Kinds  of  Loops:    
Any  style  of  loop  may  be  nested.    Each  nested  loop  must  be  indented  to  indicate  
which  statements  are  controlled  by  which  looping  construct.
Do
Code Statements
While <condition>
More code may be here
For (initial condition; test; increment)
more code here
End For
More code may be here
End While
More code may be here
While <condition>

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


1 Declare Count1, Count2, Side As Integer
Example:   2 Declare Symbol As Character
Drawing   3
4
Write “Choose a symbol (any character from the keyboard):“
Input Symbol
Squares 5 Write “Enter the length of a side of the square: “
6 Input Side
7 Set Count1 = 1
8 Set Count2 = 1
9 While Count1 <= Side
10 While Count2 <= Side
11 Print Symbol
12 Set Count2 = Count2 + 1
13 End While
14 Print <NL>
15 Set Count2 = 1
16 Set Count1 = Count1 + 1
17 End While

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


X Y Z output  
Mind  Games  Workout  #1 1 ? ? Pass Number 1
1 1 2 1 + 1 = 2
1 4 5 1 + 4 = 5
1 7 8 1 + 7 = 8
1 Declare X, Y, Z As Integer 1 10 8
2 For (X = 1; X < 4; X++) 2 10 8 Pass Number 2
3 Write “Pass Number “ + X 2 1 3 2 + 1 = 3
4 For (Y = 1; Y < 10; Y+3) 2 4 6 2 + 4 = 6
5 Set Z = X + Y 2 7 9 2 + 7 = 9
6 Write X + “ + “ + Y + “ = “+ Z 2 10 9
7 End For(Y) 3 10 9 Pass Number 3
8 End For(X) 3 1 4 3 + 1 = 4
3 4 7 3 + 4 = 7
3 7 10 3 + 7 = 10
3 10 10
4 10 10

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


X Y Z Count1 Count2 output
? 3 ? 1 ?
Mind  Games:  Workout  #  2 2 3 ? 1 1 Pass Number 1
2 3 6 1 1 X = 2, Y = 3, Z = 6
1 Declare X, Y, Z As Integer 3 3 6 1 2
2 Declare Count1 As Integer 3 3 9 1 2 X = 3, Y = 3, Z = 9
3 Declare Count2 As Integer 4 3 9 1 3
2 Set Y = 3
3 Set Count1 = 1 4 3 12 1 3 X = 4, Y = 3, Z = 12
4 Do 5 3 12 1 4
5 Set X = Count1 + 1 And so on...
6 Set Count2 = 1
7 Write “Pass Number “ + Count1
8 While Count2 <= Y
9 Set Z = Y * X
10 Write “X = “ + X + “, Y = “ + Y + “, Z = “ + Z
11 Set X = X + 1
12 Set Count2 = Count2 + 1
13 End While
14 Set Count1 = Count1 + 1
15 While Count1 < Y

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


1 Declare A, B, C As Integer
2 Set A = 1
3 Write “Cheers!”
4 While A < 3
Mind   5 Set C = A
Games:     6
7
Write A
Set B = 1
Workout  #3     8
9
While B < 4
Set C = C + A
10 Write C
11 If (A == 1 AND C >= 4) Then
12 Write “Let’s do this some more!”
13 Else
14 If (A == 2 AND C >= 8) Then
15 Write “Who do we appreciate?”
16 End If
17 End If
18 Set B = B + 1
19 End While
20 Set A = A + 1
21 End While

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  


A B C output
1 ? ? Cheers!
1 ? 1 1
1 1 1
Mind   1 1 2 2

Games:     1
1
2
2
2
3 3
Workout  #3   1 3 3

Follow   1
1
3
3
4
4 Let’s do this some more!
4

Along…     1 4 4
2 1 2 2
2 1 4 4
2 2 4
2 2 6 6
2 3 6
2 3 8 8
2 3 8 Who do we appreciate?
2 4 8
3 4 8

PRELUDE  TO  PROGRAMMING,  6TH  EDITION  BY  ELIZABETH  DRAKE  

You might also like