SlideShare una empresa de Scribd logo
1 de 11
Descargar para leer sin conexión
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 indefinite 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 first 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

Más contenido relacionado

La actualidad más candente (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
 

Similar a Lo43

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
 
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
 
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
 

Similar a Lo43 (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
 

Más de lksoo

Más de lksoo (20)

Lo48
Lo48Lo48
Lo48
 
Lo39
Lo39Lo39
Lo39
 
Lo37
Lo37Lo37
Lo37
 
Lo27
Lo27Lo27
Lo27
 
Lo17
Lo17Lo17
Lo17
 
Lo12
Lo12Lo12
Lo12
 
T3
T3T3
T3
 
T2
T2T2
T2
 
T1
T1T1
T1
 
T4
T4T4
T4
 
P5
P5P5
P5
 
P4
P4P4
P4
 
P3
P3P3
P3
 
P1
P1P1
P1
 
P2
P2P2
P2
 
L10
L10L10
L10
 
L9
L9L9
L9
 
L7
L7L7
L7
 
L6
L6L6
L6
 
L5
L5L5
L5
 

Último

Jeremy Casson - Top Tips for Pottery Wheel Throwing
Jeremy Casson - Top Tips for Pottery Wheel ThrowingJeremy Casson - Top Tips for Pottery Wheel Throwing
Jeremy Casson - Top Tips for Pottery Wheel ThrowingJeremy Casson
 
Lucknow 💋 Call Girl in Lucknow | Whatsapp No 8923113531 VIP Escorts Service A...
Lucknow 💋 Call Girl in Lucknow | Whatsapp No 8923113531 VIP Escorts Service A...Lucknow 💋 Call Girl in Lucknow | Whatsapp No 8923113531 VIP Escorts Service A...
Lucknow 💋 Call Girl in Lucknow | Whatsapp No 8923113531 VIP Escorts Service A...anilsa9823
 
Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...
Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...
Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...anilsa9823
 
Alex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson StoryboardAlex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson Storyboardthephillipta
 
exhuma plot and synopsis from the exhuma movie.pptx
exhuma plot and synopsis from the exhuma movie.pptxexhuma plot and synopsis from the exhuma movie.pptx
exhuma plot and synopsis from the exhuma movie.pptxKurikulumPenilaian
 
AaliyahBell_themist_v01.pdf .
AaliyahBell_themist_v01.pdf             .AaliyahBell_themist_v01.pdf             .
AaliyahBell_themist_v01.pdf .AaliyahB2
 
Deconstructing Gendered Language; Feminist World-Making 2024
Deconstructing Gendered Language; Feminist World-Making 2024Deconstructing Gendered Language; Feminist World-Making 2024
Deconstructing Gendered Language; Feminist World-Making 2024samlnance
 
Indira Nagar Lucknow #Call Girls Lucknow ₹7.5k Pick Up & Drop With Cash Payme...
Indira Nagar Lucknow #Call Girls Lucknow ₹7.5k Pick Up & Drop With Cash Payme...Indira Nagar Lucknow #Call Girls Lucknow ₹7.5k Pick Up & Drop With Cash Payme...
Indira Nagar Lucknow #Call Girls Lucknow ₹7.5k Pick Up & Drop With Cash Payme...akbard9823
 
Turn Lock Take Key Storyboard Daniel Johnson
Turn Lock Take Key Storyboard Daniel JohnsonTurn Lock Take Key Storyboard Daniel Johnson
Turn Lock Take Key Storyboard Daniel Johnsonthephillipta
 
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...anilsa9823
 
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...gurkirankumar98700
 
Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...
Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...
Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...akbard9823
 
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...akbard9823
 
Jeremy Casson - How Painstaking Restoration Has Revealed the Beauty of an Imp...
Jeremy Casson - How Painstaking Restoration Has Revealed the Beauty of an Imp...Jeremy Casson - How Painstaking Restoration Has Revealed the Beauty of an Imp...
Jeremy Casson - How Painstaking Restoration Has Revealed the Beauty of an Imp...Jeremy Casson
 
Lucknow 💋 Virgin Call Girls Lucknow | Book 8923113531 Extreme Naughty Call Gi...
Lucknow 💋 Virgin Call Girls Lucknow | Book 8923113531 Extreme Naughty Call Gi...Lucknow 💋 Virgin Call Girls Lucknow | Book 8923113531 Extreme Naughty Call Gi...
Lucknow 💋 Virgin Call Girls Lucknow | Book 8923113531 Extreme Naughty Call Gi...anilsa9823
 
RAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAKRAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAKedwardsara83
 
Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...
Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...
Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...anilsa9823
 
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort ServiceYoung⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Servicesonnydelhi1992
 
Call girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room serviceCall girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room servicediscovermytutordmt
 
Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...
Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...
Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...gurkirankumar98700
 

Último (20)

Jeremy Casson - Top Tips for Pottery Wheel Throwing
Jeremy Casson - Top Tips for Pottery Wheel ThrowingJeremy Casson - Top Tips for Pottery Wheel Throwing
Jeremy Casson - Top Tips for Pottery Wheel Throwing
 
Lucknow 💋 Call Girl in Lucknow | Whatsapp No 8923113531 VIP Escorts Service A...
Lucknow 💋 Call Girl in Lucknow | Whatsapp No 8923113531 VIP Escorts Service A...Lucknow 💋 Call Girl in Lucknow | Whatsapp No 8923113531 VIP Escorts Service A...
Lucknow 💋 Call Girl in Lucknow | Whatsapp No 8923113531 VIP Escorts Service A...
 
Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...
Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...
Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...
 
Alex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson StoryboardAlex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson Storyboard
 
exhuma plot and synopsis from the exhuma movie.pptx
exhuma plot and synopsis from the exhuma movie.pptxexhuma plot and synopsis from the exhuma movie.pptx
exhuma plot and synopsis from the exhuma movie.pptx
 
AaliyahBell_themist_v01.pdf .
AaliyahBell_themist_v01.pdf             .AaliyahBell_themist_v01.pdf             .
AaliyahBell_themist_v01.pdf .
 
Deconstructing Gendered Language; Feminist World-Making 2024
Deconstructing Gendered Language; Feminist World-Making 2024Deconstructing Gendered Language; Feminist World-Making 2024
Deconstructing Gendered Language; Feminist World-Making 2024
 
Indira Nagar Lucknow #Call Girls Lucknow ₹7.5k Pick Up & Drop With Cash Payme...
Indira Nagar Lucknow #Call Girls Lucknow ₹7.5k Pick Up & Drop With Cash Payme...Indira Nagar Lucknow #Call Girls Lucknow ₹7.5k Pick Up & Drop With Cash Payme...
Indira Nagar Lucknow #Call Girls Lucknow ₹7.5k Pick Up & Drop With Cash Payme...
 
Turn Lock Take Key Storyboard Daniel Johnson
Turn Lock Take Key Storyboard Daniel JohnsonTurn Lock Take Key Storyboard Daniel Johnson
Turn Lock Take Key Storyboard Daniel Johnson
 
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...
 
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...
 
Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...
Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...
Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...
 
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
 
Jeremy Casson - How Painstaking Restoration Has Revealed the Beauty of an Imp...
Jeremy Casson - How Painstaking Restoration Has Revealed the Beauty of an Imp...Jeremy Casson - How Painstaking Restoration Has Revealed the Beauty of an Imp...
Jeremy Casson - How Painstaking Restoration Has Revealed the Beauty of an Imp...
 
Lucknow 💋 Virgin Call Girls Lucknow | Book 8923113531 Extreme Naughty Call Gi...
Lucknow 💋 Virgin Call Girls Lucknow | Book 8923113531 Extreme Naughty Call Gi...Lucknow 💋 Virgin Call Girls Lucknow | Book 8923113531 Extreme Naughty Call Gi...
Lucknow 💋 Virgin Call Girls Lucknow | Book 8923113531 Extreme Naughty Call Gi...
 
RAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAKRAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAK
 
Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...
Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...
Lucknow 💋 Call Girls in Lucknow | Service-oriented sexy call girls 8923113531...
 
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort ServiceYoung⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Service
 
Call girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room serviceCall girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room service
 
Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...
Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...
Charbagh ! (Call Girls) in Lucknow Finest Escorts Service 🥗 8923113531 🏊 Avai...
 

Lo43

  • 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 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
  • 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 indefinite 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 first 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