SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

for loop in java
for loop in java for loop in java
for loop in java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
Loops c++
Loops c++Loops c++
Loops c++
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Java package
Java packageJava package
Java package
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Loops in c++ programming language
Loops in c++ programming language Loops in c++ programming language
Loops in c++ programming language
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
The Loops
The LoopsThe Loops
The Loops
 
Type casting in java
Type casting in javaType casting in java
Type casting 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
 

Semelhante a Looping statements in Java

Semelhante a 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
 
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
 
Ch4_part1.ppt
Ch4_part1.pptCh4_part1.ppt
Ch4_part1.ppt
 

Mais de Jin Castor

Information security
 Information security Information security
Information securityJin Castor
 
Introduction to E-commerce
Introduction to E-commerceIntroduction to E-commerce
Introduction to E-commerceJin Castor
 
Introduction to Infographics Designing
Introduction to Infographics DesigningIntroduction to Infographics Designing
Introduction to Infographics DesigningJin Castor
 
Creative designing using Adobe Products
Creative designing using Adobe ProductsCreative designing using Adobe Products
Creative designing using Adobe ProductsJin Castor
 
Introduction to Adobe Illustrator
Introduction to Adobe IllustratorIntroduction to Adobe Illustrator
Introduction to Adobe IllustratorJin Castor
 
SEO Advanced and scalable link building
SEO  Advanced and scalable link building SEO  Advanced and scalable link building
SEO Advanced and scalable link building Jin Castor
 
Introduction to Web Designing
Introduction to Web DesigningIntroduction to Web Designing
Introduction to Web DesigningJin Castor
 
Introduction to search engine optimization
Introduction to search engine optimizationIntroduction to search engine optimization
Introduction to search engine optimizationJin Castor
 
Web services protocols
Web services protocolsWeb services protocols
Web services protocolsJin Castor
 
Web application security
Web application securityWeb application security
Web application securityJin Castor
 
Introduction to xampp
Introduction to xamppIntroduction to xampp
Introduction to xamppJin Castor
 
Drupal introduction
Drupal introductionDrupal introduction
Drupal introductionJin Castor
 
Control statements in Java
Control statements  in JavaControl statements  in Java
Control statements in JavaJin Castor
 
Switch statements in Java
Switch statements  in JavaSwitch statements  in Java
Switch statements in JavaJin Castor
 

Mais de Jin Castor (16)

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 arrays
Java arraysJava arrays
Java arrays
 

Último

Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 

Último (20)

Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 

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