SlideShare a Scribd company logo
1 of 11
Download to read offline
Loops
Christopher Simpkins
chris.simpkins@gatech.edu
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 1 / 11
Loops and Iteration
Algorithms often call for repeated action or iteration, e.g. :
“repeat ... while (or until) some condition is true” (looping) or
“for each element of this array/list/etc. ...” (iteration)
Java provides three iteration structures:
while loop
do-while loop
for iteration statement
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 2 / 11
while and do-while
while loops are pre-test loops: the loop condition is tested before the
loop body is executed
while (condition) { // condition is any boolean expression
// loop body executes as long as condition is true
}
do-while loops are post-test loops: the loop condition is tested after
the loop body is executed
do {
// loop body executes as long as condition is true
} while (condition)
The body of a do-while loop will always execute at least once.
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 3 / 11
for Statements
The general for statement syntax is:
for(initializer; condition; update) {
// body executed as long as condition is true
}
intializer is a statement
Use this statement to initialize value of the loop variable(s)
condition is tested before executing the loop body to determine
whether the loop body should be executed. When false, the loop
exits just like a while loop
update is a statement
Use this statement to update the value of the loop variable(s) so
that the condition converges to false
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 4 / 11
for Statement vs. while Statement
The for statement:
for( int i = 0 ; i < 10 ; i++ ) {
// body executed as long as condition is true
}
is equivalent to:
int i = 0
while ( i < 10 ) {
// body
i++ ;
}
for is Java’s primary iteration structure. In the future we’ll see
generalized versions, but for now for statements are used primarily to
iterate through the indexes of data structures and to repeat code a
particular number of times.
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 5 / 11
for Statement Examples
Here’s an example adapted from Switch.java. We use the for loops
index variable to visit each character in a String and count the digits
and letters:
int digitCount = 0, letterCount = 0;
for (int i = 0; i < input.length(); ++i) {
char c = input.charAt(i);
if (Character.isDigit(c)) digitCount++;
if (Character.isAlphabetic(c)) letterCount++;
}
And here’s a simple example of repeating an action a fixed number of
times:
for (int i = 0; i < 10; ++i)
System.out.println("Meow!");
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 6 / 11
for Statement Subtleties
Better to declare loop index in for to limit it’s scope. Prefer:
for (int i = 0; i < 10; ++i)
to:
int i; // Bad. Looop index variable visible outside loop.
for (i = 0; i < 10; ++i)
You can have multiple loop indexes separated by commas:
String mystery = "mnerigpaba", solved = ""; int len = mystery.length();
for (int i = 0, j = len - 1; i < len/2; ++i, --j) {
solved = solved + mystery.charAt(i) + mystery.charAt(j);
}
Note that the loop above is one loop, not nested loops.
Beware of common “extra semicolon” syntax error:
for (int i = 0; i < 10; ++i); // oops! semicolon ends the statement
print(meow); // this will only execute once, not 10 times
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 7 / 11
Forever is a Long Time
Here are two idioms for indenite loops. First with for:
for (;;) {
// ever
}
and with while:
while (true) {
// forever
}
See Loops.java for loop examples.
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 8 / 11
break and continue
Java provides two non-structured-programming ways to alter loop
control flow:
break exits the loop, possibly to a labeled location in the program
continue skips the remainder of a loop body and continues with
the next iteration
Consider the following while loop:
Scanner kbd = new Scanner(in);
boolean shouldContinue = true;
while (shouldContinue) {
System.out.println("Enter some input (exit to quit):");
String input = kbd.nextLine();
doSomethingWithInput(input); // We do something with "exit" too.
keepGoing = (input.equalsIgnoreCase("exit")) ? false : true;
}
We don’t test for the termination sentinal, “exit,” until after we do
something with it. Situations like these often tempt us to use break ...
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 9 / 11
breaking out of a while Loop
We could test the sentinal before processing and break:
Scanner kbd = new Scanner(in);
boolean shouldContinue = true;
while (shouldContinue) {
System.out.println("Enter some input (exit to quit):");
String input = kbd.nextLine();
if (input.equalsIgnoreCase("exit")) break;
doSomethingWithInput(input);
}
But it’s better to use structured programming:
Scanner kbd = new Scanner(in);
boolean shouldContinue = true;
while (shouldContinue) {
System.out.println("Enter some input (exit to quit):");
String input = kbd.nextLine();
if (input.equalsIgnoreCase("exit")) {
shouldContinue = false;
} else {
doSomethingWithInput(input);
}
}
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 10 / 11
Programming Exercise: Palindromes
Write a program that determines whether a String is a palindrome. A
palindrome is a string of characters that reads the same when
reversed, e.g. “radar”.
Your program should use the rst command line argument as the
String to test
You should ignore case, e.g. ’R’ == ’r’
You should ignore spaces, e.g. “a but tuba” is a palindrome
Try to do this with a single for loop
Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 11 / 11

More Related Content

What's hot (18)

Iteration Statement in C++
Iteration Statement in C++Iteration Statement in C++
Iteration Statement in C++
 
C lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareC lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshare
 
While loop
While loopWhile loop
While loop
 
Do...while loop structure
Do...while loop structureDo...while loop structure
Do...while loop structure
 
Loops in c
Loops in cLoops in c
Loops in c
 
Loop c++
Loop c++Loop c++
Loop c++
 
Looping statement
Looping statementLooping statement
Looping statement
 
C# loops
C# loopsC# loops
C# loops
 
Forloop
ForloopForloop
Forloop
 
Understand Decision structures in c++ (cplusplus)
Understand Decision structures in c++ (cplusplus)Understand Decision structures in c++ (cplusplus)
Understand Decision structures in c++ (cplusplus)
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming Language
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Looping in c++
Looping in c++Looping in c++
Looping in c++
 
Loops
LoopsLoops
Loops
 
The Loops
The LoopsThe Loops
The Loops
 
Conditions In C# C-Sharp
Conditions In C# C-SharpConditions In C# C-Sharp
Conditions In C# C-Sharp
 
Looping and Switchcase BDCR
Looping and Switchcase BDCRLooping and Switchcase BDCR
Looping and Switchcase BDCR
 

Viewers also liked

Motivation and desireEssay 4 presentation
Motivation and desireEssay 4 presentationMotivation and desireEssay 4 presentation
Motivation and desireEssay 4 presentationLeslie Klick
 
Lo1
Lo1Lo1
Lo1liankei
 
CaseStudy_4_Master
CaseStudy_4_MasterCaseStudy_4_Master
CaseStudy_4_MasterBrian Lawson
 
Lo6
Lo6Lo6
Lo6liankei
 
Cassandra Clark Resume[1]
Cassandra Clark Resume[1]Cassandra Clark Resume[1]
Cassandra Clark Resume[1]Cassandra Clark
 
Rpjmd20132018 ( sulsel )
Rpjmd20132018 ( sulsel ) Rpjmd20132018 ( sulsel )
Rpjmd20132018 ( sulsel ) royden hutapea
 
CURRICULUM VITAE CHRISTOS FYDANIS
CURRICULUM VITAE CHRISTOS FYDANISCURRICULUM VITAE CHRISTOS FYDANIS
CURRICULUM VITAE CHRISTOS FYDANISChristos Fydanis
 
new acorn website
new acorn websitenew acorn website
new acorn websiteJoe Gilbert
 
New acorn website
New acorn websiteNew acorn website
New acorn websiteJoe Gilbert
 
PLC BASED ELEVATOR PPT(GROUP-1)
PLC BASED ELEVATOR PPT(GROUP-1)PLC BASED ELEVATOR PPT(GROUP-1)
PLC BASED ELEVATOR PPT(GROUP-1)Krupal Bhoi
 

Viewers also liked (11)

Motivation and desireEssay 4 presentation
Motivation and desireEssay 4 presentationMotivation and desireEssay 4 presentation
Motivation and desireEssay 4 presentation
 
Lo1
Lo1Lo1
Lo1
 
J c-gupta-sons
J c-gupta-sonsJ c-gupta-sons
J c-gupta-sons
 
CaseStudy_4_Master
CaseStudy_4_MasterCaseStudy_4_Master
CaseStudy_4_Master
 
Lo6
Lo6Lo6
Lo6
 
Cassandra Clark Resume[1]
Cassandra Clark Resume[1]Cassandra Clark Resume[1]
Cassandra Clark Resume[1]
 
Rpjmd20132018 ( sulsel )
Rpjmd20132018 ( sulsel ) Rpjmd20132018 ( sulsel )
Rpjmd20132018 ( sulsel )
 
CURRICULUM VITAE CHRISTOS FYDANIS
CURRICULUM VITAE CHRISTOS FYDANISCURRICULUM VITAE CHRISTOS FYDANIS
CURRICULUM VITAE CHRISTOS FYDANIS
 
new acorn website
new acorn websitenew acorn website
new acorn website
 
New acorn website
New acorn websiteNew acorn website
New acorn website
 
PLC BASED ELEVATOR PPT(GROUP-1)
PLC BASED ELEVATOR PPT(GROUP-1)PLC BASED ELEVATOR PPT(GROUP-1)
PLC BASED ELEVATOR PPT(GROUP-1)
 

Similar to 09

Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio Zoppi
 
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)It Academy
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingaprilyyy
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxmonicafrancis71118
 
Cs1123 6 loops
Cs1123 6 loopsCs1123 6 loops
Cs1123 6 loopsTAlha MAlik
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition StructurePRN USM
 
Lec7 - Loops updated.pptx
Lec7 - Loops updated.pptxLec7 - Loops updated.pptx
Lec7 - Loops updated.pptxNaumanRasheed11
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...Doug Jones
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsIt Academy
 
06 Loops
06 Loops06 Loops
06 Loopsmaznabili
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
Java tut1
Java tut1Java tut1
Java tut1Ajmal Khan
 
Tutorial java
Tutorial javaTutorial java
Tutorial javaAbdul Aziz
 
Java Tutorial
Java TutorialJava Tutorial
Java TutorialVijay A Raj
 

Similar to 09 (20)

Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
 
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
 
Core java
Core javaCore java
Core java
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
1660213363910.pdf
1660213363910.pdf1660213363910.pdf
1660213363910.pdf
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
 
Cs1123 6 loops
Cs1123 6 loopsCs1123 6 loops
Cs1123 6 loops
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
Lec7 - Loops updated.pptx
Lec7 - Loops updated.pptxLec7 - Loops updated.pptx
Lec7 - Loops updated.pptx
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java Statements
 
06 Loops
06 Loops06 Loops
06 Loops
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Loops
LoopsLoops
Loops
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 

More from liankei

Lo 19
Lo 19Lo 19
Lo 19liankei
 
Lo 18
Lo 18Lo 18
Lo 18liankei
 
Lo 13
Lo 13Lo 13
Lo 13liankei
 
Lo 12
Lo 12Lo 12
Lo 12liankei
 
Lo 11
Lo 11Lo 11
Lo 11liankei
 
Lo 06
Lo 06Lo 06
Lo 06liankei
 
Lo 05
Lo 05Lo 05
Lo 05liankei
 
Lo 04
Lo 04Lo 04
Lo 04liankei
 
Lo 01
Lo 01Lo 01
Lo 01liankei
 
Lo 16
Lo 16Lo 16
Lo 16liankei
 
Lo 15
Lo 15Lo 15
Lo 15liankei
 
Lo 09
Lo 09Lo 09
Lo 09liankei
 
Lo 08
Lo 08Lo 08
Lo 08liankei
 
Lo 03
Lo 03Lo 03
Lo 03liankei
 
Lo 20
Lo 20Lo 20
Lo 20liankei
 
Lo19
Lo19Lo19
Lo19liankei
 
Lo20
Lo20Lo20
Lo20liankei
 
Lo17
Lo17Lo17
Lo17liankei
 
Lo18
Lo18Lo18
Lo18liankei
 
Lo15
Lo15Lo15
Lo15liankei
 

More from liankei (20)

Lo 19
Lo 19Lo 19
Lo 19
 
Lo 18
Lo 18Lo 18
Lo 18
 
Lo 13
Lo 13Lo 13
Lo 13
 
Lo 12
Lo 12Lo 12
Lo 12
 
Lo 11
Lo 11Lo 11
Lo 11
 
Lo 06
Lo 06Lo 06
Lo 06
 
Lo 05
Lo 05Lo 05
Lo 05
 
Lo 04
Lo 04Lo 04
Lo 04
 
Lo 01
Lo 01Lo 01
Lo 01
 
Lo 16
Lo 16Lo 16
Lo 16
 
Lo 15
Lo 15Lo 15
Lo 15
 
Lo 09
Lo 09Lo 09
Lo 09
 
Lo 08
Lo 08Lo 08
Lo 08
 
Lo 03
Lo 03Lo 03
Lo 03
 
Lo 20
Lo 20Lo 20
Lo 20
 
Lo19
Lo19Lo19
Lo19
 
Lo20
Lo20Lo20
Lo20
 
Lo17
Lo17Lo17
Lo17
 
Lo18
Lo18Lo18
Lo18
 
Lo15
Lo15Lo15
Lo15
 

Recently uploaded

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
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
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
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
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
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
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
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
#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
 
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
 
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
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 

Recently uploaded (20)

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
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
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...
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
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
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
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
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
#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
 
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...
 
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
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 

09

  • 1. Loops Christopher Simpkins chris.simpkins@gatech.edu Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 1 / 11
  • 2. Loops and Iteration Algorithms often call for repeated action or iteration, e.g. : “repeat ... while (or until) some condition is true” (looping) or “for each element of this array/list/etc. ...” (iteration) Java provides three iteration structures: while loop do-while loop for iteration statement Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 2 / 11
  • 3. while and do-while while loops are pre-test loops: the loop condition is tested before the loop body is executed while (condition) { // condition is any boolean expression // loop body executes as long as condition is true } do-while loops are post-test loops: the loop condition is tested after the loop body is executed do { // loop body executes as long as condition is true } while (condition) The body of a do-while loop will always execute at least once. Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 3 / 11
  • 4. for Statements The general for statement syntax is: for(initializer; condition; update) { // body executed as long as condition is true } intializer is a statement Use this statement to initialize value of the loop variable(s) condition is tested before executing the loop body to determine whether the loop body should be executed. When false, the loop exits just like a while loop update is a statement Use this statement to update the value of the loop variable(s) so that the condition converges to false Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 4 / 11
  • 5. for Statement vs. while Statement The for statement: for( int i = 0 ; i < 10 ; i++ ) { // body executed as long as condition is true } is equivalent to: int i = 0 while ( i < 10 ) { // body i++ ; } for is Java’s primary iteration structure. In the future we’ll see generalized versions, but for now for statements are used primarily to iterate through the indexes of data structures and to repeat code a particular number of times. Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 5 / 11
  • 6. for Statement Examples Here’s an example adapted from Switch.java. We use the for loops index variable to visit each character in a String and count the digits and letters: int digitCount = 0, letterCount = 0; for (int i = 0; i < input.length(); ++i) { char c = input.charAt(i); if (Character.isDigit(c)) digitCount++; if (Character.isAlphabetic(c)) letterCount++; } And here’s a simple example of repeating an action a xed number of times: for (int i = 0; i < 10; ++i) System.out.println("Meow!"); Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 6 / 11
  • 7. for Statement Subtleties Better to declare loop index in for to limit it’s scope. Prefer: for (int i = 0; i < 10; ++i) to: int i; // Bad. Looop index variable visible outside loop. for (i = 0; i < 10; ++i) You can have multiple loop indexes separated by commas: String mystery = "mnerigpaba", solved = ""; int len = mystery.length(); for (int i = 0, j = len - 1; i < len/2; ++i, --j) { solved = solved + mystery.charAt(i) + mystery.charAt(j); } Note that the loop above is one loop, not nested loops. Beware of common “extra semicolon” syntax error: for (int i = 0; i < 10; ++i); // oops! semicolon ends the statement print(meow); // this will only execute once, not 10 times Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 7 / 11
  • 8. Forever is a Long Time Here are two idioms for indenite loops. First with for: for (;;) { // ever } and with while: while (true) { // forever } See Loops.java for loop examples. Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 8 / 11
  • 9. break and continue Java provides two non-structured-programming ways to alter loop control flow: break exits the loop, possibly to a labeled location in the program continue skips the remainder of a loop body and continues with the next iteration Consider the following while loop: Scanner kbd = new Scanner(in); boolean shouldContinue = true; while (shouldContinue) { System.out.println("Enter some input (exit to quit):"); String input = kbd.nextLine(); doSomethingWithInput(input); // We do something with "exit" too. keepGoing = (input.equalsIgnoreCase("exit")) ? false : true; } We don’t test for the termination sentinal, “exit,” until after we do something with it. Situations like these often tempt us to use break ... Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 9 / 11
  • 10. breaking out of a while Loop We could test the sentinal before processing and break: Scanner kbd = new Scanner(in); boolean shouldContinue = true; while (shouldContinue) { System.out.println("Enter some input (exit to quit):"); String input = kbd.nextLine(); if (input.equalsIgnoreCase("exit")) break; doSomethingWithInput(input); } But it’s better to use structured programming: Scanner kbd = new Scanner(in); boolean shouldContinue = true; while (shouldContinue) { System.out.println("Enter some input (exit to quit):"); String input = kbd.nextLine(); if (input.equalsIgnoreCase("exit")) { shouldContinue = false; } else { doSomethingWithInput(input); } } Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 10 / 11
  • 11. Programming Exercise: Palindromes Write a program that determines whether a String is a palindrome. A palindrome is a string of characters that reads the same when reversed, e.g. “radar”. Your program should use the rst command line argument as the String to test You should ignore case, e.g. ’R’ == ’r’ You should ignore spaces, e.g. “a but tuba” is a palindrome Try to do this with a single for loop Chris Simpkins (Georgia Tech) CS 1331 Introduction to Object Oriented Programming 11 / 11