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

Burari Call Girls : ☎ 8527673949, Low rate Call Girls
Burari Call Girls : ☎ 8527673949, Low rate Call GirlsBurari Call Girls : ☎ 8527673949, Low rate Call Girls
Burari Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
San Jon Motel, Motel/Residence, San Jon NM
San Jon Motel, Motel/Residence, San Jon NMSan Jon Motel, Motel/Residence, San Jon NM
San Jon Motel, Motel/Residence, San Jon NMroute66connected
 
Bobbie goods colorinsssssssssssg book.pdf
Bobbie goods colorinsssssssssssg book.pdfBobbie goods colorinsssssssssssg book.pdf
Bobbie goods colorinsssssssssssg book.pdflunavro0105
 
Kishangarh Call Girls : ☎ 8527673949, Low rate Call Girls
Kishangarh Call Girls : ☎ 8527673949, Low rate Call GirlsKishangarh Call Girls : ☎ 8527673949, Low rate Call Girls
Kishangarh Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
Call Girls in Islamabad | 03070433345 | Call Girl Service
Call Girls in Islamabad | 03070433345 | Call Girl ServiceCall Girls in Islamabad | 03070433345 | Call Girl Service
Call Girls in Islamabad | 03070433345 | Call Girl ServiceAyesha Khan
 
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | DelhiMalviyaNagarCallGirl
 
Russian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts Service
Russian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts ServiceRussian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts Service
Russian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts Servicedoor45step
 
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Service
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts ServiceIndian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Service
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Servicedoor45step
 
Kristy Soto's Industrial design Portfolio
Kristy Soto's Industrial design PortfolioKristy Soto's Industrial design Portfolio
Kristy Soto's Industrial design PortfolioKristySoto
 
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Availabledollysharma2066
 
Russian⚡ Call Girls In Sector 39 Noida✨8375860717⚡Escorts Service
Russian⚡ Call Girls In Sector 39 Noida✨8375860717⚡Escorts ServiceRussian⚡ Call Girls In Sector 39 Noida✨8375860717⚡Escorts Service
Russian⚡ Call Girls In Sector 39 Noida✨8375860717⚡Escorts Servicedoor45step
 
Downtown Call Girls O5O91O128O Pakistani Call Girls in Downtown
Downtown Call Girls O5O91O128O Pakistani Call Girls in DowntownDowntown Call Girls O5O91O128O Pakistani Call Girls in Downtown
Downtown Call Girls O5O91O128O Pakistani Call Girls in Downtowndajasot375
 
Triangle Vinyl Record Store, Clermont Florida
Triangle Vinyl Record Store, Clermont FloridaTriangle Vinyl Record Store, Clermont Florida
Triangle Vinyl Record Store, Clermont FloridaGabrielaMiletti
 
Jvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call Girl
Jvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call GirlJvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call Girl
Jvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call Girllijeho2176
 
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857delhimodel235
 
How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?
How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?
How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?kexey39068
 
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call Girls
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call GirlsJagat Puri Call Girls : ☎ 8527673949, Low rate Call Girls
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...dajasot375
 
Faridabad Call Girls : ☎ 8527673949, Low rate Call Girls
Faridabad Call Girls : ☎ 8527673949, Low rate Call GirlsFaridabad Call Girls : ☎ 8527673949, Low rate Call Girls
Faridabad Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 

Último (20)

Burari Call Girls : ☎ 8527673949, Low rate Call Girls
Burari Call Girls : ☎ 8527673949, Low rate Call GirlsBurari Call Girls : ☎ 8527673949, Low rate Call Girls
Burari Call Girls : ☎ 8527673949, Low rate Call Girls
 
San Jon Motel, Motel/Residence, San Jon NM
San Jon Motel, Motel/Residence, San Jon NMSan Jon Motel, Motel/Residence, San Jon NM
San Jon Motel, Motel/Residence, San Jon NM
 
Bobbie goods colorinsssssssssssg book.pdf
Bobbie goods colorinsssssssssssg book.pdfBobbie goods colorinsssssssssssg book.pdf
Bobbie goods colorinsssssssssssg book.pdf
 
Kishangarh Call Girls : ☎ 8527673949, Low rate Call Girls
Kishangarh Call Girls : ☎ 8527673949, Low rate Call GirlsKishangarh Call Girls : ☎ 8527673949, Low rate Call Girls
Kishangarh Call Girls : ☎ 8527673949, Low rate Call Girls
 
Call Girls in Islamabad | 03070433345 | Call Girl Service
Call Girls in Islamabad | 03070433345 | Call Girl ServiceCall Girls in Islamabad | 03070433345 | Call Girl Service
Call Girls in Islamabad | 03070433345 | Call Girl Service
 
call girls in Noida New Ashok Nagar 🔝 >༒8448380779 🔝 genuine Escort Service 🔝...
call girls in Noida New Ashok Nagar 🔝 >༒8448380779 🔝 genuine Escort Service 🔝...call girls in Noida New Ashok Nagar 🔝 >༒8448380779 🔝 genuine Escort Service 🔝...
call girls in Noida New Ashok Nagar 🔝 >༒8448380779 🔝 genuine Escort Service 🔝...
 
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Gandhi Vihar | Delhi
 
Russian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts Service
Russian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts ServiceRussian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts Service
Russian⚡ Call Girls In Sector 104 Noida✨8375860717⚡Escorts Service
 
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Service
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts ServiceIndian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Service
Indian High Profile Call Girls In Sector 18 Noida 8375860717 Escorts Service
 
Kristy Soto's Industrial design Portfolio
Kristy Soto's Industrial design PortfolioKristy Soto's Industrial design Portfolio
Kristy Soto's Industrial design Portfolio
 
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available
8377087607, Door Step Call Girls In Gaur City (NOIDA) 24/7 Available
 
Russian⚡ Call Girls In Sector 39 Noida✨8375860717⚡Escorts Service
Russian⚡ Call Girls In Sector 39 Noida✨8375860717⚡Escorts ServiceRussian⚡ Call Girls In Sector 39 Noida✨8375860717⚡Escorts Service
Russian⚡ Call Girls In Sector 39 Noida✨8375860717⚡Escorts Service
 
Downtown Call Girls O5O91O128O Pakistani Call Girls in Downtown
Downtown Call Girls O5O91O128O Pakistani Call Girls in DowntownDowntown Call Girls O5O91O128O Pakistani Call Girls in Downtown
Downtown Call Girls O5O91O128O Pakistani Call Girls in Downtown
 
Triangle Vinyl Record Store, Clermont Florida
Triangle Vinyl Record Store, Clermont FloridaTriangle Vinyl Record Store, Clermont Florida
Triangle Vinyl Record Store, Clermont Florida
 
Jvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call Girl
Jvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call GirlJvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call Girl
Jvc Call Girl +971528604116 Indian Call Girl in Jvc By Dubai Call Girl
 
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857
Low Rate Call Girls in Laxmi Nagar Delhi Call 9990771857
 
How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?
How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?
How Can You Get Dubai Call Girls +971564860409 Call Girls Dubai?
 
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call Girls
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call GirlsJagat Puri Call Girls : ☎ 8527673949, Low rate Call Girls
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call Girls
 
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
 
Faridabad Call Girls : ☎ 8527673949, Low rate Call Girls
Faridabad Call Girls : ☎ 8527673949, Low rate Call GirlsFaridabad Call Girls : ☎ 8527673949, Low rate Call Girls
Faridabad Call Girls : ☎ 8527673949, Low rate Call Girls
 

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