SlideShare une entreprise Scribd logo
1  sur  32
Télécharger pour lire hors ligne
Week 4
Loops
© 2004 Pearson Addison-Wesley. All rights reserved 5-2
Copyright Warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been copied and communicated to you by or
on behalf of Bond University pursuant to Part VB of the
Copyright Act 1968 (the Act).
The material in this communication may be subject to copyright
under the Act. Any further copying or communication of this
material by you may be the subject of copyright protection
under the Act.
© 2004 Pearson Addison-Wesley. All rights reserved 5-3
Repetition Statements
• Repetition statements allow us to execute a
statement multiple times
• Often they are referred to as loops
• Like conditional statements, they are controlled by
boolean expressions
• Java has three kinds of repetition statements:
 the while loop
 the do loop
 the for loop
• The programmer should choose the right kind of
loop for the situation
© 2004 Pearson Addison-Wesley. All rights reserved 5-4
The while Statement
• A while statement has the following syntax:
while ( condition )
statement;
• If the condition is true, the statement is
executed
• Then the condition is evaluated again, and if it is
still true, the statement is executed again until the
condition becomes false
• We use while loops when we cannot predict the
number of times the loop will execute, e.g.
•testing for bad user input
•processing input records from a database
© 2004 Pearson Addison-Wesley. All rights reserved 5-5
Logic of a while Loop
statement
true
false
condition
evaluated
© 2004 Pearson Addison-Wesley. All rights reserved 5-6
The while Statement
• An example of a while statement:
int count = 1;
while (count <= 5)
{
System.out.println (count);
count++;
}
• If the condition of a while loop is false initially,
the statement is never executed
• Therefore, the body of a while loop will execute
zero or more times
© 2004 Pearson Addison-Wesley. All rights reserved 5-7
How Often is the Body Run?
• If the condition of a while loop is false initially,
the statement is never executed
• Therefore, the body of a while loop will execute
zero or more times
• Once inside the body of the while loop, if nothing
is done to modify the loop condition, we get an
infinite loop
© 2004 Pearson Addison-Wesley. All rights reserved 5-8
Infinite Loops
• The body of a while loop eventually must make
the condition false
• If not, it is called an infinite loop, which will
execute until the user interrupts the program
• This is a common logical error
• You should always double check the logic of a
program to ensure that your loops will terminate
normally
© 2004 Pearson Addison-Wesley. All rights reserved 5-9
Infinite Loops
• An example of an infinite loop:
int count = 1;
while (count <= 25)
{
System.out.println (count);
count = count - 1;
}
• This loop will continue executing until interrupted
(Control-C) or until an underflow error occurs
© 2004 Pearson Addison-Wesley. All rights reserved 5-10
Running Sum, Count, Max, Min
• In the Average program from Week 3's lab, we saw
how to keep a running count of the numbers
entered by the user
• We also kept a running sum of the numbers
entered. This allowed us to calculate the average
of the numbers entered
• The same idea can be used to calculate the
maximum and minimum of the numbers entered;
see Average2 from Week 4's lab
• We must start the running maximum small so that
the first number entered overwrites it
• The same thing goes for the running minimum
• Can you think of numbers which will break it?
© 2004 Pearson Addison-Wesley. All rights reserved 5-11
Nested Loops
• Similar to nested if statements, loops can be
nested as well
• That is, the body of a loop can contain another
loop
• For each iteration of the outer loop, the inner loop
iterates completely
• See PalindromeTester.java (page 235)
© 2004 Pearson Addison-Wesley. All rights reserved 5-12
Nested Loops
• How many times will the string "Here" be printed?
count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 20)
{
System.out.println ("Here");
count2++;
}
count1++;
}
10 * 20 = 200
© 2004 Pearson Addison-Wesley. All rights reserved 5-13
The do Statement
• A do statement has the following syntax:
do
{
statement;
}
while ( condition )
• The statement is executed once initially, and then
the condition is evaluated
• The statement is executed repeatedly until the
condition becomes false
© 2004 Pearson Addison-Wesley. All rights reserved 5-14
Logic of a do Loop
true
condition
evaluated
statement
false
© 2004 Pearson Addison-Wesley. All rights reserved 5-15
The do Statement
• An example of a do loop:
• The body of a do loop executes at least once
• See ReverseNumber.java (page 244)
int count = 0;
do
{
count++;
System.out.println (count);
} while (count < 5);
© 2004 Pearson Addison-Wesley. All rights reserved 5-16
Comparing while and do
statement
true
falsecondition
evaluated
The while Loop
true
condition
evaluated
statement
false
The do Loop
© 2004 Pearson Addison-Wesley. All rights reserved 5-17
When to Use Do or While?
• Use a do loop when the loop body must be
executed at least once, e.g
• Get the user's input before we can tell that it is
invalid
• Use either of these two loop forms when the
number of times the loop must execute is
unknown
• When the number of iterations through the loop is
known in advance, you should use a for loop
© 2004 Pearson Addison-Wesley. All rights reserved 5-18
Looping N times, or over a range
• In many situations, you know in advance how many times
that you want to loop, e.g.
•Do something for every day in this month
• Alternatively, you need to loop over a range of values, e.g.
•Do some calculations for each possible age in the range 0
to 100 years old
• In these situations, we use the for loop.
• The for loop:
•has a loop counter, holding one value in the range each
time through the loop, and
•increments the loop counter for you
© 2004 Pearson Addison-Wesley. All rights reserved 5-19
The for Statement
• A for statement has the following syntax:
for ( initialization ; condition ; increment )
statement;
The initialization
is executed once
before the loop begins
The statement is
executed until the
condition becomes false
The increment portion is
executed at the end of each
iteration
© 2004 Pearson Addison-Wesley. All rights reserved 5-20
Logic of a for loop
statement
true
condition
evaluated
false
increment
initialization
© 2004 Pearson Addison-Wesley. All rights reserved 5-21
The for Statement
• A for loop is functionally equivalent to the
following while loop structure:
initialization;
while ( condition )
{
statement;
increment;
}
© 2004 Pearson Addison-Wesley. All rights reserved 5-22
The for Statement
• An example of a for loop:
for (int count=1; count <= 5; count++)
System.out.println (count);
• In this example, count goes from 1 to 5 in steps of 1,
and the count value is printed out
• The initialization section can be used to declare a
variable
• Like a while loop, the condition of a for loop is tested
prior to executing the loop body
• Therefore, the body of a for loop will execute zero or
more times
© 2004 Pearson Addison-Wesley. All rights reserved 5-23
The for Statement
• The increment section can perform any calculation
• What does the above loop print out?
• A for loop is well suited for executing statements
a specific number of times that can be calculated
or determined in advance
• See Multiples.java (page 248)
• See Stars.java (page 250)
for (int num=100; num > 0; num -= 5)
System.out.println (num);
© 2004 Pearson Addison-Wesley. All rights reserved 5-24
Nested For Loops
• Just like other control structures in Java, for loops
can be nested inside other loops or if statements
• What does this code do?
for (rows=1; rows<=10; rows++)
{
for (cols=1; cols<=20; cols++)
System.out.print(“*”);
System.out.println;
}
• Try it in the Java debugger and see
© 2004 Pearson Addison-Wesley. All rights reserved 5-25
Nested For Loops
• It's important here to remember to treat the outside
loop counter as constant
• Watch what happens when we use the outside
loop counter as a constant in the inner loop:
• What does this code do?
for (rows=1; rows<=10; rows++)
{
for (cols=1; cols<=rows; cols++)
System.out.print(“*”);
System.out.println;
}
• Try it in the Java debugger and see
© 2004 Pearson Addison-Wesley. All rights reserved 5-26
Nested For Loops
for (rows=1; rows<=10; rows++)
{
for (cols=1; cols<=rows; cols++)
System.out.print(“*”);
System.out.println;
}
• Note that the inner loop uses the value of the rows
variable to determine the number of stars to print
© 2004 Pearson Addison-Wesley. All rights reserved 5-27
Class Exercise
• Write a program to print out a multiplication table,
with columns 1 2 3 4 5 6 7 8 9 10, and rows 1 .. 10, e.g.
x 1 2 3 4 5 6 7 8
1 1 2 3 4 5 6 7 8
2 2 4 6 8 10 12 14 16
3 3 6 9 12 15 18 21 24
• Hint: we need 2 variables to multiply together. What
can we name them?
• Hint: do we need loops? How many loops?
• Hint: when do we print a newline?
• Suggestion: don't print the blue numbers to start with
© 2004 Pearson Addison-Wesley. All rights reserved 5-28
Class Exercise
• Modify the program to print out the row and
column labels. Include horizontal and vertical bars
if possible.
• Modify the program to ask the user for the upper
bound for the table size, instead of using 10.
• Modify the program to ensure that the user's input
is between 5 and 15.
© 2004 Pearson Addison-Wesley. All rights reserved 5-29
Program Development Tips
• Think about the problem BEFORE you start writing
code!!
• What variables will be needed, how will they
change over time?
• What control structures do you think you'll need:
IF, WHILE, DO, FOR, and where?
• Develop your program one bit at a time. Test what
you have written before adding new stuff.
• Use the debugger to show you what the code is
actually doing. Remember: a computer DWIS not
DWIW.
© 2004 Pearson Addison-Wesley. All rights reserved 5-30
Program Development Tips
• Use a top-down approach, e.g.
 Get the input from the user, make sure it's between 5 and
10
 Print out the heading (need a loop here, probably a FOR
loop as we know the table size)
 We need a loop for each line, again a FOR loop
 FOR each line
• We need another variable to be the column variable, and
we're going to need an inner loop now
• Do the multiplication inside the inner loop and print out the
result
• At the end of the line, i.e. when the inner loop has finished,
print out the newline
• Alternatively, if you know the code to write to do a
specific thing, then do it (bottom-up).
• You will usually do a bit top-down and a bit
bottom-up.
© 2004 Pearson Addison-Wesley. All rights reserved 5-31
Break and Continue
• Inside a loop body, the break command instantly
exits the loop and starts the code following the
loop.
• Inside a loop body, the continue command
instantly takes you to the top of the loop. Any
condition at the top of the loop is evaluated.
• The textbook suggests you should avoid these two
commands. I disagree.
• Example: ask user for number between 1 and 100.
If they enter something else, tell them that they are
stupid and ask again.
© 2004 Pearson Addison-Wesley. All rights reserved 5-32
The Break Command
int value;
while (true)
{
System.out.print(“Enter num 1-100: “);
value=scan.nextInt();
if ((value>=1) && (value<=100)
break;
System.out.println(“Idiot! Try again”);
}
• Note the loop looks like an infinite loop. But the
loop breaks when the user gets it right.
• Try doing the same with a normal WHILE or DO
loop

Contenu connexe

Similaire à Week04

Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in JavaJin Castor
 
Cso gaddis java_chapter4
Cso gaddis java_chapter4Cso gaddis java_chapter4
Cso gaddis java_chapter4mlrbrown
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While LoopAbhishek Choksi
 
Eo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eEo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eGina Bullock
 
Eo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eEo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eGina Bullock
 
Introduction to Repetition Structures
Introduction to Repetition StructuresIntroduction to Repetition Structures
Introduction to Repetition Structuresprimeteacher32
 
C++ unit-1-part-14
C++ unit-1-part-14C++ unit-1-part-14
C++ unit-1-part-14Jadavsejal
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxAmy Nightingale
 
Java Chapter 05 - Conditions & Loops: part 5
Java Chapter 05 - Conditions & Loops: part 5Java Chapter 05 - Conditions & Loops: part 5
Java Chapter 05 - Conditions & Loops: part 5DanWooster1
 
Java Chapter 05 - Conditions & Loops: part 2
Java Chapter 05 - Conditions & Loops: part 2Java Chapter 05 - Conditions & Loops: part 2
Java Chapter 05 - Conditions & Loops: part 2DanWooster1
 

Similaire à Week04 (20)

Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
 
Looping statements
Looping statementsLooping statements
Looping statements
 
Programming loop
Programming loopProgramming loop
Programming loop
 
Cso gaddis java_chapter4
Cso gaddis java_chapter4Cso gaddis java_chapter4
Cso gaddis java_chapter4
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
 
cpu.pdf
cpu.pdfcpu.pdf
cpu.pdf
 
Lesson 5
Lesson 5Lesson 5
Lesson 5
 
Eo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eEo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5e
 
Eo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eEo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5e
 
Chapter05
Chapter05Chapter05
Chapter05
 
Introduction to Repetition Structures
Introduction to Repetition StructuresIntroduction to Repetition Structures
Introduction to Repetition Structures
 
Loops
LoopsLoops
Loops
 
Looping statements
Looping statementsLooping statements
Looping statements
 
C++ unit-1-part-14
C++ unit-1-part-14C++ unit-1-part-14
C++ unit-1-part-14
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
 
Slide 6_Control Structures.pdf
Slide 6_Control Structures.pdfSlide 6_Control Structures.pdf
Slide 6_Control Structures.pdf
 
Java Chapter 05 - Conditions & Loops: part 5
Java Chapter 05 - Conditions & Loops: part 5Java Chapter 05 - Conditions & Loops: part 5
Java Chapter 05 - Conditions & Loops: part 5
 
Java chapter 3
Java chapter 3Java chapter 3
Java chapter 3
 
Java Chapter 05 - Conditions & Loops: part 2
Java Chapter 05 - Conditions & Loops: part 2Java Chapter 05 - Conditions & Loops: part 2
Java Chapter 05 - Conditions & Loops: part 2
 
C language (Part 2)
C language (Part 2)C language (Part 2)
C language (Part 2)
 

Plus de hccit

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syllhccit
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guidehccit
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11hccit
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014hccit
 
Photoshop
PhotoshopPhotoshop
Photoshophccit
 
Flash
FlashFlash
Flashhccit
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overviewhccit
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochurehccit
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exerciseshccit
 
Repairs questions
Repairs questionsRepairs questions
Repairs questionshccit
 
Movies questions
Movies questionsMovies questions
Movies questionshccit
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questionshccit
 
Section b
Section bSection b
Section bhccit
 
Section a
Section aSection a
Section ahccit
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5hccit
 
Case study report mj
Case study report mjCase study report mj
Case study report mjhccit
 
Mj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedqMj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedqhccit
 
Case study plan mj
Case study plan mjCase study plan mj
Case study plan mjhccit
 

Plus de hccit (20)

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syll
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guide
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014
 
Photoshop
PhotoshopPhotoshop
Photoshop
 
Flash
FlashFlash
Flash
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overview
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochure
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exercises
 
Repairs questions
Repairs questionsRepairs questions
Repairs questions
 
Movies questions
Movies questionsMovies questions
Movies questions
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questions
 
Section b
Section bSection b
Section b
 
B
BB
B
 
A
AA
A
 
Section a
Section aSection a
Section a
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5
 
Case study report mj
Case study report mjCase study report mj
Case study report mj
 
Mj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedqMj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedq
 
Case study plan mj
Case study plan mjCase study plan mj
Case study plan mj
 

Dernier

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Dernier (20)

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Week04

  • 2. © 2004 Pearson Addison-Wesley. All rights reserved 5-2 Copyright Warning COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING This material has been copied and communicated to you by or on behalf of Bond University pursuant to Part VB of the Copyright Act 1968 (the Act). The material in this communication may be subject to copyright under the Act. Any further copying or communication of this material by you may be the subject of copyright protection under the Act.
  • 3. © 2004 Pearson Addison-Wesley. All rights reserved 5-3 Repetition Statements • Repetition statements allow us to execute a statement multiple times • Often they are referred to as loops • Like conditional statements, they are controlled by boolean expressions • Java has three kinds of repetition statements:  the while loop  the do loop  the for loop • The programmer should choose the right kind of loop for the situation
  • 4. © 2004 Pearson Addison-Wesley. All rights reserved 5-4 The while Statement • A while statement has the following syntax: while ( condition ) statement; • If the condition is true, the statement is executed • Then the condition is evaluated again, and if it is still true, the statement is executed again until the condition becomes false • We use while loops when we cannot predict the number of times the loop will execute, e.g. •testing for bad user input •processing input records from a database
  • 5. © 2004 Pearson Addison-Wesley. All rights reserved 5-5 Logic of a while Loop statement true false condition evaluated
  • 6. © 2004 Pearson Addison-Wesley. All rights reserved 5-6 The while Statement • An example of a while statement: int count = 1; while (count <= 5) { System.out.println (count); count++; } • If the condition of a while loop is false initially, the statement is never executed • Therefore, the body of a while loop will execute zero or more times
  • 7. © 2004 Pearson Addison-Wesley. All rights reserved 5-7 How Often is the Body Run? • If the condition of a while loop is false initially, the statement is never executed • Therefore, the body of a while loop will execute zero or more times • Once inside the body of the while loop, if nothing is done to modify the loop condition, we get an infinite loop
  • 8. © 2004 Pearson Addison-Wesley. All rights reserved 5-8 Infinite Loops • The body of a while loop eventually must make the condition false • If not, it is called an infinite loop, which will execute until the user interrupts the program • This is a common logical error • You should always double check the logic of a program to ensure that your loops will terminate normally
  • 9. © 2004 Pearson Addison-Wesley. All rights reserved 5-9 Infinite Loops • An example of an infinite loop: int count = 1; while (count <= 25) { System.out.println (count); count = count - 1; } • This loop will continue executing until interrupted (Control-C) or until an underflow error occurs
  • 10. © 2004 Pearson Addison-Wesley. All rights reserved 5-10 Running Sum, Count, Max, Min • In the Average program from Week 3's lab, we saw how to keep a running count of the numbers entered by the user • We also kept a running sum of the numbers entered. This allowed us to calculate the average of the numbers entered • The same idea can be used to calculate the maximum and minimum of the numbers entered; see Average2 from Week 4's lab • We must start the running maximum small so that the first number entered overwrites it • The same thing goes for the running minimum • Can you think of numbers which will break it?
  • 11. © 2004 Pearson Addison-Wesley. All rights reserved 5-11 Nested Loops • Similar to nested if statements, loops can be nested as well • That is, the body of a loop can contain another loop • For each iteration of the outer loop, the inner loop iterates completely • See PalindromeTester.java (page 235)
  • 12. © 2004 Pearson Addison-Wesley. All rights reserved 5-12 Nested Loops • How many times will the string "Here" be printed? count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 <= 20) { System.out.println ("Here"); count2++; } count1++; } 10 * 20 = 200
  • 13. © 2004 Pearson Addison-Wesley. All rights reserved 5-13 The do Statement • A do statement has the following syntax: do { statement; } while ( condition ) • The statement is executed once initially, and then the condition is evaluated • The statement is executed repeatedly until the condition becomes false
  • 14. © 2004 Pearson Addison-Wesley. All rights reserved 5-14 Logic of a do Loop true condition evaluated statement false
  • 15. © 2004 Pearson Addison-Wesley. All rights reserved 5-15 The do Statement • An example of a do loop: • The body of a do loop executes at least once • See ReverseNumber.java (page 244) int count = 0; do { count++; System.out.println (count); } while (count < 5);
  • 16. © 2004 Pearson Addison-Wesley. All rights reserved 5-16 Comparing while and do statement true falsecondition evaluated The while Loop true condition evaluated statement false The do Loop
  • 17. © 2004 Pearson Addison-Wesley. All rights reserved 5-17 When to Use Do or While? • Use a do loop when the loop body must be executed at least once, e.g • Get the user's input before we can tell that it is invalid • Use either of these two loop forms when the number of times the loop must execute is unknown • When the number of iterations through the loop is known in advance, you should use a for loop
  • 18. © 2004 Pearson Addison-Wesley. All rights reserved 5-18 Looping N times, or over a range • In many situations, you know in advance how many times that you want to loop, e.g. •Do something for every day in this month • Alternatively, you need to loop over a range of values, e.g. •Do some calculations for each possible age in the range 0 to 100 years old • In these situations, we use the for loop. • The for loop: •has a loop counter, holding one value in the range each time through the loop, and •increments the loop counter for you
  • 19. © 2004 Pearson Addison-Wesley. All rights reserved 5-19 The for Statement • A for statement has the following syntax: for ( initialization ; condition ; increment ) statement; The initialization is executed once before the loop begins The statement is executed until the condition becomes false The increment portion is executed at the end of each iteration
  • 20. © 2004 Pearson Addison-Wesley. All rights reserved 5-20 Logic of a for loop statement true condition evaluated false increment initialization
  • 21. © 2004 Pearson Addison-Wesley. All rights reserved 5-21 The for Statement • A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; }
  • 22. © 2004 Pearson Addison-Wesley. All rights reserved 5-22 The for Statement • An example of a for loop: for (int count=1; count <= 5; count++) System.out.println (count); • In this example, count goes from 1 to 5 in steps of 1, and the count value is printed out • The initialization section can be used to declare a variable • Like a while loop, the condition of a for loop is tested prior to executing the loop body • Therefore, the body of a for loop will execute zero or more times
  • 23. © 2004 Pearson Addison-Wesley. All rights reserved 5-23 The for Statement • The increment section can perform any calculation • What does the above loop print out? • A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance • See Multiples.java (page 248) • See Stars.java (page 250) for (int num=100; num > 0; num -= 5) System.out.println (num);
  • 24. © 2004 Pearson Addison-Wesley. All rights reserved 5-24 Nested For Loops • Just like other control structures in Java, for loops can be nested inside other loops or if statements • What does this code do? for (rows=1; rows<=10; rows++) { for (cols=1; cols<=20; cols++) System.out.print(“*”); System.out.println; } • Try it in the Java debugger and see
  • 25. © 2004 Pearson Addison-Wesley. All rights reserved 5-25 Nested For Loops • It's important here to remember to treat the outside loop counter as constant • Watch what happens when we use the outside loop counter as a constant in the inner loop: • What does this code do? for (rows=1; rows<=10; rows++) { for (cols=1; cols<=rows; cols++) System.out.print(“*”); System.out.println; } • Try it in the Java debugger and see
  • 26. © 2004 Pearson Addison-Wesley. All rights reserved 5-26 Nested For Loops for (rows=1; rows<=10; rows++) { for (cols=1; cols<=rows; cols++) System.out.print(“*”); System.out.println; } • Note that the inner loop uses the value of the rows variable to determine the number of stars to print
  • 27. © 2004 Pearson Addison-Wesley. All rights reserved 5-27 Class Exercise • Write a program to print out a multiplication table, with columns 1 2 3 4 5 6 7 8 9 10, and rows 1 .. 10, e.g. x 1 2 3 4 5 6 7 8 1 1 2 3 4 5 6 7 8 2 2 4 6 8 10 12 14 16 3 3 6 9 12 15 18 21 24 • Hint: we need 2 variables to multiply together. What can we name them? • Hint: do we need loops? How many loops? • Hint: when do we print a newline? • Suggestion: don't print the blue numbers to start with
  • 28. © 2004 Pearson Addison-Wesley. All rights reserved 5-28 Class Exercise • Modify the program to print out the row and column labels. Include horizontal and vertical bars if possible. • Modify the program to ask the user for the upper bound for the table size, instead of using 10. • Modify the program to ensure that the user's input is between 5 and 15.
  • 29. © 2004 Pearson Addison-Wesley. All rights reserved 5-29 Program Development Tips • Think about the problem BEFORE you start writing code!! • What variables will be needed, how will they change over time? • What control structures do you think you'll need: IF, WHILE, DO, FOR, and where? • Develop your program one bit at a time. Test what you have written before adding new stuff. • Use the debugger to show you what the code is actually doing. Remember: a computer DWIS not DWIW.
  • 30. © 2004 Pearson Addison-Wesley. All rights reserved 5-30 Program Development Tips • Use a top-down approach, e.g.  Get the input from the user, make sure it's between 5 and 10  Print out the heading (need a loop here, probably a FOR loop as we know the table size)  We need a loop for each line, again a FOR loop  FOR each line • We need another variable to be the column variable, and we're going to need an inner loop now • Do the multiplication inside the inner loop and print out the result • At the end of the line, i.e. when the inner loop has finished, print out the newline • Alternatively, if you know the code to write to do a specific thing, then do it (bottom-up). • You will usually do a bit top-down and a bit bottom-up.
  • 31. © 2004 Pearson Addison-Wesley. All rights reserved 5-31 Break and Continue • Inside a loop body, the break command instantly exits the loop and starts the code following the loop. • Inside a loop body, the continue command instantly takes you to the top of the loop. Any condition at the top of the loop is evaluated. • The textbook suggests you should avoid these two commands. I disagree. • Example: ask user for number between 1 and 100. If they enter something else, tell them that they are stupid and ask again.
  • 32. © 2004 Pearson Addison-Wesley. All rights reserved 5-32 The Break Command int value; while (true) { System.out.print(“Enter num 1-100: “); value=scan.nextInt(); if ((value>=1) && (value<=100) break; System.out.println(“Idiot! Try again”); } • Note the loop looks like an infinite loop. But the loop breaks when the user gets it right. • Try doing the same with a normal WHILE or DO loop