SlideShare une entreprise Scribd logo
1  sur  21
Looping Statements
Prepared by:
Jean Michael Castor
5-1
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
5-2
The while Statement
• A while statement has the following syntax:
5-3
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
• The statement is executed repeatedly until the
condition becomes false
Logic of a while Loop
5-4
statement
true false
condition
evaluated
The while Statement
• An example of a while statement:
5-5
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
The while Statement
• Let's look at some examples of loop
processing
• A loop can be used to maintain a running sum
• A sentinel value is a special input value that
represents the end of input
• A loop can also be used for input validation,
making a program more robust
5-6
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 (semantic) error
• You should always double check the logic of a
program to ensure that your loops will terminate
normally
5-7
Infinite Loops
• An example of an infinite loop:
5-8
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
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
• Your second course project involves a while
loop nested inside of a for loop
5-9
Nested Loops
• How many times will the string "Here" be printed?
5-10
count1 = 1;
while (count1 <= 10){
count2 = 1;
while (count2 <= 20) {
System.out.println ("Here");
count2++;
}
count1++;
}
10 * 20 = 200
Outline
5-11
The while Statement
Other Repetition Statements
The do-while Statement
• A do-while statement (also called a do loop)
has the following syntax:
5-12
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
Logic of a do-while Loop
5-13
true
condition
evaluated
statement
false
The do Statement
• An example of a do loop:
5-14
• The body of a do loop executes at least once
int count = 0;
do{
count++;
System.out.println (count);
} while (count < 5);
Comparing while and do
5-15
statement
true false
condition
evaluated
The while Loop
true
condition
evaluated
statement
false
The do Loop
The for Statement
• A for statement has the following syntax:
5-16
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
Logic of a for loop
5-17
statement
true
condition
evaluated
false
increment
initialization
The for Statement
• A for loop is functionally equivalent to the
following while loop structure:
5-18
initialization;
while ( condition ){
statement;
increment;
}
The for Statement
• An example of a for loop:
5-19
for (int count=1; count <= 5; count++){
System.out.println (count);
}
• 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
The for Statement
• The increment section can perform any
calculation
5-20
• A for loop is well suited for executing statements
a specific number of times that can be calculated
or determined in advance
for (int num=100; num > 0; num -= 5){
System.out.println (num);
}
The for Statement
• Each expression in the header of a for loop is optional
• If the initialization is left out, no initialization is
performed
• If the condition is left out, it is always considered to be
true, and therefore creates an infinite loop
– We usually call this a “forever loop”
• If the increment is left out, no increment operation is
performed
5-21

Contenu connexe

Tendances

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 

Tendances (20)

Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
C#.NET
C#.NETC#.NET
C#.NET
 
Operators in java presentation
Operators in java presentationOperators in java presentation
Operators in java presentation
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
String in java
String in javaString in java
String in java
 
Loop(for, while, do while) condition Presentation
Loop(for, while, do while) condition PresentationLoop(for, while, do while) condition Presentation
Loop(for, while, do while) condition Presentation
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
C# basics
 C# basics C# basics
C# basics
 
OOP java
OOP javaOOP java
OOP java
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision Control
 
Java swing
Java swingJava swing
Java swing
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Data types in java
Data types in javaData types in java
Data types in java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
C Programming: Structure and Union
C Programming: Structure and UnionC Programming: Structure and Union
C Programming: Structure and Union
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 

Similaire à Looping statements in Java

Week04
Week04Week04
Week04
hccit
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
Amy Nightingale
 

Similaire à Looping statements in Java (20)

Looping statements
Looping statementsLooping statements
Looping statements
 
Programming loop
Programming loopProgramming loop
Programming loop
 
Looping statements
Looping statementsLooping statements
Looping statements
 
Week04
Week04Week04
Week04
 
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
 
15-Loops.ppt
15-Loops.ppt15-Loops.ppt
15-Loops.ppt
 
Looping
LoopingLooping
Looping
 
Loops c++
Loops c++Loops c++
Loops c++
 
3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf
 
Repetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesRepetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniques
 
Visula C# Programming Lecture 4
Visula C# Programming Lecture 4Visula C# Programming Lecture 4
Visula C# Programming Lecture 4
 
loops and iteration.docx
loops and iteration.docxloops and iteration.docx
loops and iteration.docx
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
 
Lesson 5
Lesson 5Lesson 5
Lesson 5
 
Unit II chapter 4 Loops in C
Unit II chapter 4 Loops in CUnit II chapter 4 Loops in C
Unit II chapter 4 Loops in C
 
Loops
LoopsLoops
Loops
 
While loop
While loopWhile loop
While loop
 
whileloop-161225171903.pdf
whileloop-161225171903.pdfwhileloop-161225171903.pdf
whileloop-161225171903.pdf
 
Lec7 - Loops updated.pptx
Lec7 - Loops updated.pptxLec7 - Loops updated.pptx
Lec7 - Loops updated.pptx
 

Plus de Jin Castor

Plus de Jin Castor (17)

Information security
 Information security Information security
Information security
 
Introduction to E-commerce
Introduction to E-commerceIntroduction to E-commerce
Introduction to E-commerce
 
Introduction to Infographics Designing
Introduction to Infographics DesigningIntroduction to Infographics Designing
Introduction to Infographics Designing
 
Creative designing using Adobe Products
Creative designing using Adobe ProductsCreative designing using Adobe Products
Creative designing using Adobe Products
 
Introduction to Adobe Illustrator
Introduction to Adobe IllustratorIntroduction to Adobe Illustrator
Introduction to Adobe Illustrator
 
SEO Advanced and scalable link building
SEO  Advanced and scalable link building SEO  Advanced and scalable link building
SEO Advanced and scalable link building
 
Introduction to Web Designing
Introduction to Web DesigningIntroduction to Web Designing
Introduction to Web Designing
 
Introduction to search engine optimization
Introduction to search engine optimizationIntroduction to search engine optimization
Introduction to search engine optimization
 
Web services protocols
Web services protocolsWeb services protocols
Web services protocols
 
Web application security
Web application securityWeb application security
Web application security
 
Introduction to xampp
Introduction to xamppIntroduction to xampp
Introduction to xampp
 
Drupal introduction
Drupal introductionDrupal introduction
Drupal introduction
 
Web security
Web securityWeb security
Web security
 
Control statements in Java
Control statements  in JavaControl statements  in Java
Control statements in Java
 
Switch statements in Java
Switch statements  in JavaSwitch statements  in Java
Switch statements in Java
 
Java input
Java inputJava input
Java input
 
Java arrays
Java arraysJava arrays
Java arrays
 

Dernier

Dernier (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

Looping statements in Java

  • 2. 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 5-2
  • 3. The while Statement • A while statement has the following syntax: 5-3 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 • The statement is executed repeatedly until the condition becomes false
  • 4. Logic of a while Loop 5-4 statement true false condition evaluated
  • 5. The while Statement • An example of a while statement: 5-5 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
  • 6. The while Statement • Let's look at some examples of loop processing • A loop can be used to maintain a running sum • A sentinel value is a special input value that represents the end of input • A loop can also be used for input validation, making a program more robust 5-6
  • 7. 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 (semantic) error • You should always double check the logic of a program to ensure that your loops will terminate normally 5-7
  • 8. Infinite Loops • An example of an infinite loop: 5-8 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
  • 9. 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 • Your second course project involves a while loop nested inside of a for loop 5-9
  • 10. Nested Loops • How many times will the string "Here" be printed? 5-10 count1 = 1; while (count1 <= 10){ count2 = 1; while (count2 <= 20) { System.out.println ("Here"); count2++; } count1++; } 10 * 20 = 200
  • 11. Outline 5-11 The while Statement Other Repetition Statements
  • 12. The do-while Statement • A do-while statement (also called a do loop) has the following syntax: 5-12 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
  • 13. Logic of a do-while Loop 5-13 true condition evaluated statement false
  • 14. The do Statement • An example of a do loop: 5-14 • The body of a do loop executes at least once int count = 0; do{ count++; System.out.println (count); } while (count < 5);
  • 15. Comparing while and do 5-15 statement true false condition evaluated The while Loop true condition evaluated statement false The do Loop
  • 16. The for Statement • A for statement has the following syntax: 5-16 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
  • 17. Logic of a for loop 5-17 statement true condition evaluated false increment initialization
  • 18. The for Statement • A for loop is functionally equivalent to the following while loop structure: 5-18 initialization; while ( condition ){ statement; increment; }
  • 19. The for Statement • An example of a for loop: 5-19 for (int count=1; count <= 5; count++){ System.out.println (count); } • 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
  • 20. The for Statement • The increment section can perform any calculation 5-20 • A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance for (int num=100; num > 0; num -= 5){ System.out.println (num); }
  • 21. The for Statement • Each expression in the header of a for loop is optional • If the initialization is left out, no initialization is performed • If the condition is left out, it is always considered to be true, and therefore creates an infinite loop – We usually call this a “forever loop” • If the increment is left out, no increment operation is performed 5-21