SlideShare a Scribd company logo
1 of 35
Introduction to Computers and
Programming
Lecture 8: More Loops
Professor: Evan Korth
New York University
2
Upcoming schedule
• February 21: lecture 8; hw#2 due
• February 26: lecture 9
• February 28: lecture 10; start review; hw#3 due
• March 5: review
• March 7: midterm
• March 13, 15: Spring break (yay!)
Road Map
• Sentinels
• Sentinel Controlled Loops
• Case Study: Sentinel Controlled Loop
• Case Study: Nested Control Structures
• do/while Loop
• Summary of looping covered so far
• Reading
– Liang 5:chapter 3: 3.3.1, 3.3.2
– Liang 6: chapter 4: 4.2, 4.3
review
• What are three ways to rewrite:
x = x + 1;
• What are the three elements of a while loop?
• What is the difference between pre and post
increment operators?
• Are you guaranteed to execute the body of a while
loop at all?
• What is an infinite loop?
• True or False: You never want to use an infinite
loop?
5
Review
• Given:
char c = 'a';
c++;
What is the value of variable c?
• What method do you use to extract characters
from a String?
– How would you use that method to get the first character
from a String?
• How are characters stored in memory?
• What is the difference between the character '0'
and the integer 0?
Sentinels
Sentinel-controlled repetition
• Counter Controlled Repetition:
– Simply means that we use a counter to tell you when to stop
repeating a statement or group of statements
– The examples from last class were counter-controlled
repetition
• However, what if we want the user or the input to
decide when to end the program?
– Use a sentinel
Understanding Sentinels
• Sentinel: a special value that indicates the “end of
data entry.”
• Also known as signal value, dummy value, or flag
value
• For example:
– -1 means end of data.
– 0 means end of data.
– "END" means ends of data
– Depends on the specific application you are building.
• With a sentinel, we have an indefinite repetition,
because the number of repetitions is unknown at
the time we write the program (or start the loop).
© 2000 Prentice Hall, Inc. All rights reserved. Modified by Evan Korth
Using Sentinels
• How are they used?
– Programmer picks a value that would never be encountered
for normal data
– User enters normal data and then when done, enters the
sentinel value
– The loop will stop when seeing the sentinel value
Using Sentinels cont’d
• For example, if entering age for people, could pick
a sentinel of –1
• No one would expect to be –1 year old.
• Good practice is to remind the user in each
iteration of the loop what the sentinel value is
– For example,
System.out.println
(" Enter age of current resident or –1 to end" );
/* A sentinel controlled loop */
/* A simple census taker */
import javax.swing.JOptionPane;
public class Sentinel
{
public static void main(String [] args)
{
int currentAge = 0 ;
String currentAgeAsString;
/* priming */
currentAgeAsString = JOptionPane.showInputDialog ("Enter age of resident: ") ;
currentAge = Integer.parseInt (currentAgeAsString);
/* testing: keep going until input is sentinel value */
while (currentAge != -1)
{
/* do some calculations with age, e.g. AVERAGE */
/*updating: get the next value from the user */
currentAgeAsString = JOptionPane.showInputDialog ("Enter age of resident: ") ;
currentAge = Integer.parseInt (currentAgeAsString);
}
System.exit (0);
}
}
Good Programming tips
• Pick a sentinel value that you are CERTAIN will
never be confused with normal data
• Style: Remind user each iteration what the sentinel
is
• Y2K-like problem
– Programmers often used 9999 as a sentinel to end a loop
– Worry that on September 9, 1999 (sometimes abbreviated
9999) programs would erroneously stop executing before
they were supposed to.
Case Study: Using Sentinel
Controlled Loops
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Problem becomes:
Develop a class-averaging program that will process an
arbitrary number of grades each time the program is run.
– Unknown number of students
– How will the program know to end?
• Use sentinel value
– Loop ends when user inputs the sentinel value
– Sentinel value chosen so it cannot be confused with a regular
input (such as -1 in this case)
© 2000 Prentice Hall, Inc. All rights reserved.
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Top-down, stepwise refinement
– Begin with a pseudocode representation of the top:
Determine the class average for the quiz
– Divide top into smaller tasks and list them in order:
Initialize variables
Input, sum and count the quiz grades
Calculate and print the class average
• Many programs have three phases:
– Initialization: initializes the program variables
– Processing: inputs data values and adjusts program variables
accordingly
– Termination: calculates and prints the final results
© 2000 Prentice Hall, Inc. All rights reserved.
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Refine the initialization phase from Initialize
variables to:
Initialize total to zero
Initialize counter to zero
• Refine Input, sum and count the quiz grades to
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)
© 2000 Prentice Hall, Inc. All rights reserved.
Formulating Algorithms with Top-Down,
Stepwise Refinement
• Refine Calculate and print the class average to
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
else
Print “No grades were entered”
© 2000 Prentice Hall, Inc. All rights reserved.
18
Initialize total to zero
Initialize counter to zero
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
else
Print “No grades were entered”
Fig. 4.8 Class-average problem pseudocode
algorithm with sentinel-controlled repetition.
© 2003 Prentice Hall, Inc. All rights reserved.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
19
Average2.java
1 // Fig. 4.9: Average2.java
2 // Class-average program with sentinel-controlled repetition.
3 import java.text.DecimalFormat; // class to format numbers
4 import javax.swing.JOptionPane;
5
6 public class Average2 {
7
8 public static void main( String args[] )
9 {
10 int total; // sum of grades
11 int gradeCounter; // number of grades entered
12 int grade; // grade value
13
14 double average; // number with decimal point for average
15
16 String gradeString; // grade typed by user
17
18 // initialization phase
19 total = 0; // initialize total
20 gradeCounter = 0; // initialize loop counter
21
22 // processing phase
23 // get first grade from user
24 gradeString = JOptionPane.showInputDialog(
25 "Enter Integer Grade or -1 to Quit:" );
26
27 // convert gradeString to int
28 grade = Integer.parseInt( gradeString );
29
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
20
Average2.java
Line 31
Line 45
30 // loop until sentinel value read from user
31 while ( grade != -1 ) {
32 total = total + grade; // add grade to total
33 gradeCounter = gradeCounter + 1; // increment counter
34
35 // get next grade from user
36 gradeString = JOptionPane.showInputDialog(
37 "Enter Integer Grade or -1 to Quit:" );
38
39 // convert gradeString to int
40 grade = Integer.parseInt( gradeString );
41
42 } // end while
43
44 // termination phase
45
46
47 // if user entered at least one grade...
48 if ( gradeCounter != 0 ) {
49
50 // calculate average of all grades entered
51 average = (double) total / gradeCounter;
52
53 // display average with two digits of precision
54 JOptionPane.showMessageDialog( null,
55 "Class average is " + average ,
56 "Class Average", JOptionPane.INFORMATION_MESSAGE );
57
58 } // end if part of if...else
59
loop until gradeCounter
equals sentinel value (-1)
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
21
Average2.java
60 else // if no grades entered, output appropriate message
61 JOptionPane.showMessageDialog( null, "No grades were entered",
62 "Class Average", JOptionPane.INFORMATION_MESSAGE );
63
64 System.exit( 0 ); // terminate application
65
66 } // end main
67
68 } // end class Average2
Case Study: Nested Control
Structures
Nested control structures
• Problem
– A college has a list of test results (1 = pass, 2 = fail) for 10
students
– Write a program that analyzes the results
• If more than 8 students pass, print "Raise Tuition"
• Notice that
– The program must process 10 test results
• Counter-controlled loop will be used
– Two counters can be used
• One for number of passes, one for number of fails
– Each test result is a number—either a 1 or a 2
• If the number is not a 1, we assume that it is a 2
© 2003 Prentice Hall, Inc. All rights reserved.
Nested control structures
• Top level outline
Analyze exam results and decide if tuition should be raised
• First Refinement
Initialize variables
Input the ten quiz grades and count passes and failures
Print a summary of the exam results and decide if tuition should
be raised
• Refine Initialize variables to
Initialize passes to zero
Initialize failures to zero
Initialize student counter to one
© 2003 Prentice Hall, Inc. All rights reserved.
Nested control structures
• Refine Input the ten quiz grades and count passes
and failures to
While student counter is less than or equal to ten
Input the next exam result
If the student passed
Add one to passes
else
Add one to failures
Add one to student counter
• Refine Print a summary of the exam results and
decide if tuition should be raised to
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Raise tuition”
© 2003 Prentice Hall, Inc. All rights reserved.
26
Initialize passes to zero
Initialize failures to zero
Initialize student to one
While student counter is less than or equal to ten
Input the next exam result
If the student passed
Add one to passes
else
Add one to failures
Add one to student counter
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Raise tuition”
Fig 4.10 Pseudocode for examination-results problem.
© 2003 Prentice Hall, Inc. All rights reserved.
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
27
Analysis.java
Line 19
Line 29
1 // Fig. 4.11: Analysis.java
2 // Analysis of examination results.
3 import javax.swing.JOptionPane;
4
5 public class Analysis {
6
7 public static void main( String args[] )
8 {
9 // initializing variables in declarations
10 int passes = 0; // number of passes
11 int failures = 0; // number of failures
12 int studentCounter = 1; // student counter
13 int result; // one exam result
14
15 String input; // user-entered value
16 String output; // output string
17
18 // process 10 students using counter-controlled loop
19 while ( studentCounter <= 10 ) {
20
21 // prompt user for input and obtain value from user
22 input = JOptionPane.showInputDialog(
23 "Enter result (1 = pass, 2 = fail)" );
24
25 // convert result to int
26 result = Integer.parseInt( input );
27
28 // if result 1, increment passes; if...else nested in while
29 if ( result == 1 )
30 passes = passes + 1;
Loop until student counter is
greater than 10
Nested control structure
© 2003 Prentice Hall, Inc.
All rights reserved.
Outline
28
Analysis.java
31
32 else // if result not 1, increment failures
33 failures = failures + 1;
34
35 // increment studentCounter so loop eventually terminates
36 studentCounter = studentCounter + 1;
37
38 } // end while
39
40 // termination phase; prepare and display results
41 output = "Passed: " + passes + "nFailed: " + failures;
42
43 // determine whether more than 8 students passed
44 if ( passes > 8 )
45 output = output + "nRaise Tuition";
46
47 JOptionPane.showMessageDialog( null, output,
48 "Analysis of Examination Results",
49 JOptionPane.INFORMATION_MESSAGE );
50
51 System.exit( 0 ); // terminate application
52
53 } // end main
54
55 } // end class Analysis
do/while Loop
The do/while Repetition Structure
• The do/while repetition structure
– Similar to the while structure
– Condition for repetition tested after the body of the loop is
performed
• All actions are performed at least once
– Format:
do {
statement(s);
} while ( condition );
4.8 The do/while Repetition Structure
• Flowchart of the do/while repetition structure
true
false
action(s)
condition
32
public class DoWhileTest
{
public static void main(String args[])
{
int counter;
counter = 1;
do
{
System.out.println ("counter: "+
counter);
counter ++;
} while (counter <= 10);
}
}
Summary of Looping so far
Summary of Looping
• Two broad types of loops:
– Counter-controlled repetition
• A counter controls the number of repetitions.
• Also known as a definite repetition, because we know in
advance how many times the loop will be executed.
– Sentinel-controlled repetition
• A sentinel controls the number of repetitions
• Also known as indefinite repetition, because we do not know
in advance how many times the loop will be executed.
• In either case, watch out for infinite loops!
• If your program requires some kind of loop, first
determine which kind of loop you want.
Summary of Looping
• Once you know which kind of loop you want,
determine which while loop you want:
– While loops
• condition is tested first; then action occurs.
• While loops are much more common than do/while loops.
– Do/while loops
• action is run first; then, condition is tested.
• Use this if you want to make sure that your loop is guaranteed
to be run at least once.

More Related Content

What's hot

Unit 1 python (2021 r)
Unit 1 python (2021 r)Unit 1 python (2021 r)
Unit 1 python (2021 r)praveena p
 
03 algorithm properties
03 algorithm properties03 algorithm properties
03 algorithm propertiesLincoln School
 
Lecture#3 Algorithms and computing
Lecture#3 Algorithms and computingLecture#3 Algorithms and computing
Lecture#3 Algorithms and computingNUST Stuff
 
Flowcharts and pseudocodes
Flowcharts and pseudocodesFlowcharts and pseudocodes
Flowcharts and pseudocodesDr Piyush Charan
 
Algorithm and Flowcharts
Algorithm and FlowchartsAlgorithm and Flowcharts
Algorithm and FlowchartsSURBHI SAROHA
 
Algorithm defination, design & Implementation
Algorithm defination, design & ImplementationAlgorithm defination, design & Implementation
Algorithm defination, design & ImplementationBilal Maqbool ツ
 
Introduction to problem solving in c++
Introduction to problem solving in c++Introduction to problem solving in c++
Introduction to problem solving in c++Online
 
Algorithms and flowcharts
Algorithms and flowchartsAlgorithms and flowcharts
Algorithms and flowchartsSajib
 
Algorithm and flowchart2010
Algorithm and flowchart2010Algorithm and flowchart2010
Algorithm and flowchart2010Jordan Delacruz
 
Cmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowchartsCmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowchartskapil078
 
Algorithm &amp; flowchart
Algorithm &amp; flowchartAlgorithm &amp; flowchart
Algorithm &amp; flowchartsaurabh sen sky
 
Problem Solving Techniques and Introduction to C
Problem Solving Techniques and Introduction to CProblem Solving Techniques and Introduction to C
Problem Solving Techniques and Introduction to CPrabu U
 
Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer   Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer Ashim Lamichhane
 
C LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHES
C LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHESC LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHES
C LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHESHarshJha34
 
COMPUTER PROGRAMMING UNIT 1 Lecture 4
COMPUTER PROGRAMMING UNIT 1 Lecture 4COMPUTER PROGRAMMING UNIT 1 Lecture 4
COMPUTER PROGRAMMING UNIT 1 Lecture 4Vishal Patil
 
Problem solving (C++ Programming)
Problem solving (C++ Programming)Problem solving (C++ Programming)
Problem solving (C++ Programming)Umair Younas
 
Problem solving using Computer
Problem solving using ComputerProblem solving using Computer
Problem solving using ComputerDavid Livingston J
 
Lecture Note-2: Performance analysis of Algorithms
Lecture Note-2: Performance analysis of AlgorithmsLecture Note-2: Performance analysis of Algorithms
Lecture Note-2: Performance analysis of AlgorithmsRajesh K Shukla
 

What's hot (20)

Unit 1 python (2021 r)
Unit 1 python (2021 r)Unit 1 python (2021 r)
Unit 1 python (2021 r)
 
03 algorithm properties
03 algorithm properties03 algorithm properties
03 algorithm properties
 
Lecture#3 Algorithms and computing
Lecture#3 Algorithms and computingLecture#3 Algorithms and computing
Lecture#3 Algorithms and computing
 
Flowcharts and pseudocodes
Flowcharts and pseudocodesFlowcharts and pseudocodes
Flowcharts and pseudocodes
 
Algorithm and Flowcharts
Algorithm and FlowchartsAlgorithm and Flowcharts
Algorithm and Flowcharts
 
Algorithm defination, design & Implementation
Algorithm defination, design & ImplementationAlgorithm defination, design & Implementation
Algorithm defination, design & Implementation
 
Introduction to problem solving in c++
Introduction to problem solving in c++Introduction to problem solving in c++
Introduction to problem solving in c++
 
Algorithms and flowcharts
Algorithms and flowchartsAlgorithms and flowcharts
Algorithms and flowcharts
 
phases of algorithm
phases of algorithmphases of algorithm
phases of algorithm
 
Algorithm and flowchart2010
Algorithm and flowchart2010Algorithm and flowchart2010
Algorithm and flowchart2010
 
Cmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowchartsCmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowcharts
 
Algorithm &amp; flowchart
Algorithm &amp; flowchartAlgorithm &amp; flowchart
Algorithm &amp; flowchart
 
Problem Solving Techniques and Introduction to C
Problem Solving Techniques and Introduction to CProblem Solving Techniques and Introduction to C
Problem Solving Techniques and Introduction to C
 
Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer   Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer
 
C LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHES
C LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHESC LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHES
C LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHES
 
COMPUTER PROGRAMMING UNIT 1 Lecture 4
COMPUTER PROGRAMMING UNIT 1 Lecture 4COMPUTER PROGRAMMING UNIT 1 Lecture 4
COMPUTER PROGRAMMING UNIT 1 Lecture 4
 
Problem solving (C++ Programming)
Problem solving (C++ Programming)Problem solving (C++ Programming)
Problem solving (C++ Programming)
 
Problem solving using Computer
Problem solving using ComputerProblem solving using Computer
Problem solving using Computer
 
Lecture Note-2: Performance analysis of Algorithms
Lecture Note-2: Performance analysis of AlgorithmsLecture Note-2: Performance analysis of Algorithms
Lecture Note-2: Performance analysis of Algorithms
 
Basics of python
Basics of pythonBasics of python
Basics of python
 

Similar to more loops lecture by Professor Evan korth

2. Algorithms Representations (C++).pptx
2. Algorithms Representations (C++).pptx2. Algorithms Representations (C++).pptx
2. Algorithms Representations (C++).pptxssuser4d77b2
 
Online learning with structured streaming, spark summit brussels 2016
Online learning with structured streaming, spark summit brussels 2016Online learning with structured streaming, spark summit brussels 2016
Online learning with structured streaming, spark summit brussels 2016Ram Sriharsha
 
classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxssusere336f4
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsJames Brotsos
 
cpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptcpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptSuleman Khan
 
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docxransayo
 
Cse115 lecture03problemsolving
Cse115 lecture03problemsolvingCse115 lecture03problemsolving
Cse115 lecture03problemsolvingMd. Ashikur Rahman
 
Class 2 variables, classes methods...
Class 2   variables, classes methods...Class 2   variables, classes methods...
Class 2 variables, classes methods...Fernando Loizides
 
Problem-solving and design 1.pptx
Problem-solving and design 1.pptxProblem-solving and design 1.pptx
Problem-solving and design 1.pptxTadiwaMawere
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxAmy Nightingale
 
New software testing-techniques
New software testing-techniquesNew software testing-techniques
New software testing-techniquesFincy V.J
 
Algorithm and C code related to data structure
Algorithm and C code related to data structureAlgorithm and C code related to data structure
Algorithm and C code related to data structureSelf-Employed
 
01 Introduction to analysis of Algorithms.pptx
01 Introduction to analysis of Algorithms.pptx01 Introduction to analysis of Algorithms.pptx
01 Introduction to analysis of Algorithms.pptxssuser586772
 
02 Control Structures - Loops & Conditions
02 Control Structures - Loops & Conditions02 Control Structures - Loops & Conditions
02 Control Structures - Loops & ConditionsEbad ullah Qureshi
 
Lesson 1 of c programming algorithms and flowcharts.pptx
Lesson 1 of c programming algorithms and flowcharts.pptxLesson 1 of c programming algorithms and flowcharts.pptx
Lesson 1 of c programming algorithms and flowcharts.pptxAlinaMishra7
 

Similar to more loops lecture by Professor Evan korth (20)

03b loops
03b   loops03b   loops
03b loops
 
2. Algorithms Representations (C++).pptx
2. Algorithms Representations (C++).pptx2. Algorithms Representations (C++).pptx
2. Algorithms Representations (C++).pptx
 
Control Structures: Part 1
Control Structures: Part 1Control Structures: Part 1
Control Structures: Part 1
 
Online learning with structured streaming, spark summit brussels 2016
Online learning with structured streaming, spark summit brussels 2016Online learning with structured streaming, spark summit brussels 2016
Online learning with structured streaming, spark summit brussels 2016
 
classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptx
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loops
 
cpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptcpphtp4_PPT_02.ppt
cpphtp4_PPT_02.ppt
 
cpphtp4_PPT_02.ppt
cpphtp4_PPT_02.pptcpphtp4_PPT_02.ppt
cpphtp4_PPT_02.ppt
 
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
 
Cse115 lecture03problemsolving
Cse115 lecture03problemsolvingCse115 lecture03problemsolving
Cse115 lecture03problemsolving
 
Class 2 variables, classes methods...
Class 2   variables, classes methods...Class 2   variables, classes methods...
Class 2 variables, classes methods...
 
Problem-solving and design 1.pptx
Problem-solving and design 1.pptxProblem-solving and design 1.pptx
Problem-solving and design 1.pptx
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
 
New software testing-techniques
New software testing-techniquesNew software testing-techniques
New software testing-techniques
 
Algorithm and C code related to data structure
Algorithm and C code related to data structureAlgorithm and C code related to data structure
Algorithm and C code related to data structure
 
DSA 103 Object Oriented Programming :: Week 3
DSA 103 Object Oriented Programming :: Week 3DSA 103 Object Oriented Programming :: Week 3
DSA 103 Object Oriented Programming :: Week 3
 
01 Introduction to analysis of Algorithms.pptx
01 Introduction to analysis of Algorithms.pptx01 Introduction to analysis of Algorithms.pptx
01 Introduction to analysis of Algorithms.pptx
 
02 Control Structures - Loops & Conditions
02 Control Structures - Loops & Conditions02 Control Structures - Loops & Conditions
02 Control Structures - Loops & Conditions
 
Lesson 1 of c programming algorithms and flowcharts.pptx
Lesson 1 of c programming algorithms and flowcharts.pptxLesson 1 of c programming algorithms and flowcharts.pptx
Lesson 1 of c programming algorithms and flowcharts.pptx
 

Recently uploaded

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 

Recently uploaded (20)

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 

more loops lecture by Professor Evan korth

  • 1. Introduction to Computers and Programming Lecture 8: More Loops Professor: Evan Korth New York University
  • 2. 2 Upcoming schedule • February 21: lecture 8; hw#2 due • February 26: lecture 9 • February 28: lecture 10; start review; hw#3 due • March 5: review • March 7: midterm • March 13, 15: Spring break (yay!)
  • 3. Road Map • Sentinels • Sentinel Controlled Loops • Case Study: Sentinel Controlled Loop • Case Study: Nested Control Structures • do/while Loop • Summary of looping covered so far • Reading – Liang 5:chapter 3: 3.3.1, 3.3.2 – Liang 6: chapter 4: 4.2, 4.3
  • 4. review • What are three ways to rewrite: x = x + 1; • What are the three elements of a while loop? • What is the difference between pre and post increment operators? • Are you guaranteed to execute the body of a while loop at all? • What is an infinite loop? • True or False: You never want to use an infinite loop?
  • 5. 5 Review • Given: char c = 'a'; c++; What is the value of variable c? • What method do you use to extract characters from a String? – How would you use that method to get the first character from a String? • How are characters stored in memory? • What is the difference between the character '0' and the integer 0?
  • 7. Sentinel-controlled repetition • Counter Controlled Repetition: – Simply means that we use a counter to tell you when to stop repeating a statement or group of statements – The examples from last class were counter-controlled repetition • However, what if we want the user or the input to decide when to end the program? – Use a sentinel
  • 8. Understanding Sentinels • Sentinel: a special value that indicates the “end of data entry.” • Also known as signal value, dummy value, or flag value • For example: – -1 means end of data. – 0 means end of data. – "END" means ends of data – Depends on the specific application you are building. • With a sentinel, we have an indefinite repetition, because the number of repetitions is unknown at the time we write the program (or start the loop). © 2000 Prentice Hall, Inc. All rights reserved. Modified by Evan Korth
  • 9. Using Sentinels • How are they used? – Programmer picks a value that would never be encountered for normal data – User enters normal data and then when done, enters the sentinel value – The loop will stop when seeing the sentinel value
  • 10. Using Sentinels cont’d • For example, if entering age for people, could pick a sentinel of –1 • No one would expect to be –1 year old. • Good practice is to remind the user in each iteration of the loop what the sentinel value is – For example, System.out.println (" Enter age of current resident or –1 to end" );
  • 11. /* A sentinel controlled loop */ /* A simple census taker */ import javax.swing.JOptionPane; public class Sentinel { public static void main(String [] args) { int currentAge = 0 ; String currentAgeAsString; /* priming */ currentAgeAsString = JOptionPane.showInputDialog ("Enter age of resident: ") ; currentAge = Integer.parseInt (currentAgeAsString); /* testing: keep going until input is sentinel value */ while (currentAge != -1) { /* do some calculations with age, e.g. AVERAGE */ /*updating: get the next value from the user */ currentAgeAsString = JOptionPane.showInputDialog ("Enter age of resident: ") ; currentAge = Integer.parseInt (currentAgeAsString); } System.exit (0); } }
  • 12. Good Programming tips • Pick a sentinel value that you are CERTAIN will never be confused with normal data • Style: Remind user each iteration what the sentinel is • Y2K-like problem – Programmers often used 9999 as a sentinel to end a loop – Worry that on September 9, 1999 (sometimes abbreviated 9999) programs would erroneously stop executing before they were supposed to.
  • 13. Case Study: Using Sentinel Controlled Loops
  • 14. Formulating Algorithms with Top-Down, Stepwise Refinement • Problem becomes: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run. – Unknown number of students – How will the program know to end? • Use sentinel value – Loop ends when user inputs the sentinel value – Sentinel value chosen so it cannot be confused with a regular input (such as -1 in this case) © 2000 Prentice Hall, Inc. All rights reserved.
  • 15. Formulating Algorithms with Top-Down, Stepwise Refinement • Top-down, stepwise refinement – Begin with a pseudocode representation of the top: Determine the class average for the quiz – Divide top into smaller tasks and list them in order: Initialize variables Input, sum and count the quiz grades Calculate and print the class average • Many programs have three phases: – Initialization: initializes the program variables – Processing: inputs data values and adjusts program variables accordingly – Termination: calculates and prints the final results © 2000 Prentice Hall, Inc. All rights reserved.
  • 16. Formulating Algorithms with Top-Down, Stepwise Refinement • Refine the initialization phase from Initialize variables to: Initialize total to zero Initialize counter to zero • Refine Input, sum and count the quiz grades to Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) © 2000 Prentice Hall, Inc. All rights reserved.
  • 17. Formulating Algorithms with Top-Down, Stepwise Refinement • Refine Calculate and print the class average to If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print “No grades were entered” © 2000 Prentice Hall, Inc. All rights reserved.
  • 18. 18 Initialize total to zero Initialize counter to zero Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print “No grades were entered” Fig. 4.8 Class-average problem pseudocode algorithm with sentinel-controlled repetition. © 2003 Prentice Hall, Inc. All rights reserved.
  • 19. © 2003 Prentice Hall, Inc. All rights reserved. Outline 19 Average2.java 1 // Fig. 4.9: Average2.java 2 // Class-average program with sentinel-controlled repetition. 3 import java.text.DecimalFormat; // class to format numbers 4 import javax.swing.JOptionPane; 5 6 public class Average2 { 7 8 public static void main( String args[] ) 9 { 10 int total; // sum of grades 11 int gradeCounter; // number of grades entered 12 int grade; // grade value 13 14 double average; // number with decimal point for average 15 16 String gradeString; // grade typed by user 17 18 // initialization phase 19 total = 0; // initialize total 20 gradeCounter = 0; // initialize loop counter 21 22 // processing phase 23 // get first grade from user 24 gradeString = JOptionPane.showInputDialog( 25 "Enter Integer Grade or -1 to Quit:" ); 26 27 // convert gradeString to int 28 grade = Integer.parseInt( gradeString ); 29
  • 20. © 2003 Prentice Hall, Inc. All rights reserved. Outline 20 Average2.java Line 31 Line 45 30 // loop until sentinel value read from user 31 while ( grade != -1 ) { 32 total = total + grade; // add grade to total 33 gradeCounter = gradeCounter + 1; // increment counter 34 35 // get next grade from user 36 gradeString = JOptionPane.showInputDialog( 37 "Enter Integer Grade or -1 to Quit:" ); 38 39 // convert gradeString to int 40 grade = Integer.parseInt( gradeString ); 41 42 } // end while 43 44 // termination phase 45 46 47 // if user entered at least one grade... 48 if ( gradeCounter != 0 ) { 49 50 // calculate average of all grades entered 51 average = (double) total / gradeCounter; 52 53 // display average with two digits of precision 54 JOptionPane.showMessageDialog( null, 55 "Class average is " + average , 56 "Class Average", JOptionPane.INFORMATION_MESSAGE ); 57 58 } // end if part of if...else 59 loop until gradeCounter equals sentinel value (-1)
  • 21. © 2003 Prentice Hall, Inc. All rights reserved. Outline 21 Average2.java 60 else // if no grades entered, output appropriate message 61 JOptionPane.showMessageDialog( null, "No grades were entered", 62 "Class Average", JOptionPane.INFORMATION_MESSAGE ); 63 64 System.exit( 0 ); // terminate application 65 66 } // end main 67 68 } // end class Average2
  • 22. Case Study: Nested Control Structures
  • 23. Nested control structures • Problem – A college has a list of test results (1 = pass, 2 = fail) for 10 students – Write a program that analyzes the results • If more than 8 students pass, print "Raise Tuition" • Notice that – The program must process 10 test results • Counter-controlled loop will be used – Two counters can be used • One for number of passes, one for number of fails – Each test result is a number—either a 1 or a 2 • If the number is not a 1, we assume that it is a 2 © 2003 Prentice Hall, Inc. All rights reserved.
  • 24. Nested control structures • Top level outline Analyze exam results and decide if tuition should be raised • First Refinement Initialize variables Input the ten quiz grades and count passes and failures Print a summary of the exam results and decide if tuition should be raised • Refine Initialize variables to Initialize passes to zero Initialize failures to zero Initialize student counter to one © 2003 Prentice Hall, Inc. All rights reserved.
  • 25. Nested control structures • Refine Input the ten quiz grades and count passes and failures to While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes else Add one to failures Add one to student counter • Refine Print a summary of the exam results and decide if tuition should be raised to Print the number of passes Print the number of failures If more than eight students passed Print “Raise tuition” © 2003 Prentice Hall, Inc. All rights reserved.
  • 26. 26 Initialize passes to zero Initialize failures to zero Initialize student to one While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes else Add one to failures Add one to student counter Print the number of passes Print the number of failures If more than eight students passed Print “Raise tuition” Fig 4.10 Pseudocode for examination-results problem. © 2003 Prentice Hall, Inc. All rights reserved.
  • 27. © 2003 Prentice Hall, Inc. All rights reserved. Outline 27 Analysis.java Line 19 Line 29 1 // Fig. 4.11: Analysis.java 2 // Analysis of examination results. 3 import javax.swing.JOptionPane; 4 5 public class Analysis { 6 7 public static void main( String args[] ) 8 { 9 // initializing variables in declarations 10 int passes = 0; // number of passes 11 int failures = 0; // number of failures 12 int studentCounter = 1; // student counter 13 int result; // one exam result 14 15 String input; // user-entered value 16 String output; // output string 17 18 // process 10 students using counter-controlled loop 19 while ( studentCounter <= 10 ) { 20 21 // prompt user for input and obtain value from user 22 input = JOptionPane.showInputDialog( 23 "Enter result (1 = pass, 2 = fail)" ); 24 25 // convert result to int 26 result = Integer.parseInt( input ); 27 28 // if result 1, increment passes; if...else nested in while 29 if ( result == 1 ) 30 passes = passes + 1; Loop until student counter is greater than 10 Nested control structure
  • 28. © 2003 Prentice Hall, Inc. All rights reserved. Outline 28 Analysis.java 31 32 else // if result not 1, increment failures 33 failures = failures + 1; 34 35 // increment studentCounter so loop eventually terminates 36 studentCounter = studentCounter + 1; 37 38 } // end while 39 40 // termination phase; prepare and display results 41 output = "Passed: " + passes + "nFailed: " + failures; 42 43 // determine whether more than 8 students passed 44 if ( passes > 8 ) 45 output = output + "nRaise Tuition"; 46 47 JOptionPane.showMessageDialog( null, output, 48 "Analysis of Examination Results", 49 JOptionPane.INFORMATION_MESSAGE ); 50 51 System.exit( 0 ); // terminate application 52 53 } // end main 54 55 } // end class Analysis
  • 30. The do/while Repetition Structure • The do/while repetition structure – Similar to the while structure – Condition for repetition tested after the body of the loop is performed • All actions are performed at least once – Format: do { statement(s); } while ( condition );
  • 31. 4.8 The do/while Repetition Structure • Flowchart of the do/while repetition structure true false action(s) condition
  • 32. 32 public class DoWhileTest { public static void main(String args[]) { int counter; counter = 1; do { System.out.println ("counter: "+ counter); counter ++; } while (counter <= 10); } }
  • 34. Summary of Looping • Two broad types of loops: – Counter-controlled repetition • A counter controls the number of repetitions. • Also known as a definite repetition, because we know in advance how many times the loop will be executed. – Sentinel-controlled repetition • A sentinel controls the number of repetitions • Also known as indefinite repetition, because we do not know in advance how many times the loop will be executed. • In either case, watch out for infinite loops! • If your program requires some kind of loop, first determine which kind of loop you want.
  • 35. Summary of Looping • Once you know which kind of loop you want, determine which while loop you want: – While loops • condition is tested first; then action occurs. • While loops are much more common than do/while loops. – Do/while loops • action is run first; then, condition is tested. • Use this if you want to make sure that your loop is guaranteed to be run at least once.