SlideShare a Scribd company logo
1 of 15
Programming in Java
5-day workshop
Loops
Matt Collison
JP Morgan Chase 2021
PiJ1.4: Loops
Session overview
Loops
• for loops
• while loops
break and continue
Loops
• A loop can be used to execute a block of statements repeatedly. If the
repeating time is:
• predictable: usually use for loop
• unpredictable: usually use while or do-while loop
for ( initialization; condition; expression ){ ... }
• Example:
for( int i=1 ; i<10 ; i++ ){
...
}
Alternatives for loops
• Q1: How about only printing the odd numbers smaller than 10?
for ( initialization; condition; expression ){ ... }
for( int i=1; i<10; i++ ){
if( I % 2 != 0 ){
System.out.println( i );
}
}
• Q2: How about printing the numbers in a descending order?
for( int i=9; i>=1; i--){ ... }
for-each loops
for ( Type var : array ) {
...
}
• Example:
int[] numArray = {7,2,6,0}
for ( int i : numArray ) {
System.out.println("number is: " + i);
}
Note: the use of a colon
while and do while loops
while(Boolean expression) {
...
}
do {
...
} while ( <Boolean expression> )
• When the condition becomes false, program control passes to the line
immediately following the loop.
• while loop might not ever run.
• do-while loop runs at least once.
Examples
Calculate the factorial of n (=1*2*...*n) using the three types of loops.
Option 1: for loop:
int n = 5;
int factorial = 1;
for (int number = 1; number <= n; ++number) {
factorial *= number;
}
Examples
Calculate the factorial of n (=1*2*...*n) using the three types of loops.
Option 2: while loop:
int n = 5;
int factorial = 1;
int number = 1;
while (number<=n) {
factorial *= number;
number++; //update
}
Examples
Calculate the factorial of n (=1*2*...*n) using the three types of loops.
Option 3: do-while loop:
int n = 5;
int factorial = 1;
int number = 1;
do{
factorial *= number;
number++; //update
} while (number<=n);
Should we print or return
the factorial?
break and continue
• The break statement is used to jump out of the loop or switch
statement.
• The continue statement is used to skip to the next iteration of the
loop.
break
• Note: Only jump out of the innermost enclosing loop of the statement.
int n = 5;
for ( int i = 1 ; i < n ; i++ ){
for ( int j = 1 ; j < n ; j++ ){
if ( j > i) {
break;
} else {
System.out.print( j + " ");
}
} // break comes here if it runs
System.out.println();
}
What is the output?
continue
• The continue statement skips the current iteration of a loop. Only skip the
innermost enclosing loop of the statement.
for (int i=0;i<=10;i++){
if (i==5) {
continue;
}
System.out.println(i);
}
System.out.println("Done!");
1. What is the output?
2. What is the output if replacing continue; with break;?
3. What is the output if replacing continue; with return;?
Summary
• Loop control statements
• for loop
• for ( int i=0; i<n; i++) { … }
• while loop and do-while loop
• Both for and while loops might not ever run, do-while loop runs at least once
• break and continue
• break: jump out of the loop or switch statement.
• continue: skips the current iteration of a loop.
• Both only have effect on the innermost enclosing loop.
Learning resources
The workshop homepage
https://mcollison.github.io/JPMC-java-intro-2021/
The course materials
https://mcollison.github.io/java-programming-foundations/
• Session worksheets – updated each week
Additional resources
• Think Java: How to think like a computer scientist
• Allen B Downey (O’Reilly Press)
• Available under Creative Commons license
• https://greenteapress.com/wp/think-java-2e/
• Oracle central Java Documentation –
https://docs.oracle.com/javase/8/docs/api/
• Other sources:
• W3Schools Java - https://www.w3schools.com/java/
• stack overflow - https://stackoverflow.com/
• Coding bat - https://codingbat.com/java

More Related Content

Similar to Pi j1.4 loops

Java Programming: Loops
Java Programming: LoopsJava Programming: Loops
Java Programming: Loops
Karwan Mustafa Kareem
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
jahanullah
 

Similar to Pi j1.4 loops (20)

python ppt.pptx
python ppt.pptxpython ppt.pptx
python ppt.pptx
 
Week2 ch4 part1edited 2020
Week2 ch4 part1edited 2020Week2 ch4 part1edited 2020
Week2 ch4 part1edited 2020
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
 
Control structures repetition
Control structures   repetitionControl structures   repetition
Control structures repetition
 
Chapter 9 Flow Of Control Knowledge Boat.pdf
Chapter 9 Flow Of Control Knowledge Boat.pdfChapter 9 Flow Of Control Knowledge Boat.pdf
Chapter 9 Flow Of Control Knowledge Boat.pdf
 
Loops c++
Loops c++Loops c++
Loops c++
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
 
Object oriented programming18 control structures looping
Object oriented programming18 control structures loopingObject oriented programming18 control structures looping
Object oriented programming18 control structures looping
 
This is all about control flow in python intruducing the Break and Continue.pptx
This is all about control flow in python intruducing the Break and Continue.pptxThis is all about control flow in python intruducing the Break and Continue.pptx
This is all about control flow in python intruducing the Break and Continue.pptx
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
 
Java Programming: Loops
Java Programming: LoopsJava Programming: Loops
Java Programming: Loops
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
 
Loops
LoopsLoops
Loops
 
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
 
M C6java6
M C6java6M C6java6
M C6java6
 
Cs1123 6 loops
Cs1123 6 loopsCs1123 6 loops
Cs1123 6 loops
 
Looping statements
Looping statementsLooping statements
Looping statements
 
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KRLoops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
 
12 lec 12 loop
12 lec 12 loop 12 lec 12 loop
12 lec 12 loop
 

More from mcollison (11)

Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
Pi j4.1 packages
Pi j4.1 packagesPi j4.1 packages
Pi j4.1 packages
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Pi j3.4 data-structures
Pi j3.4 data-structuresPi j3.4 data-structures
Pi j3.4 data-structures
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
Pi j2.2 classes
Pi j2.2 classesPi j2.2 classes
Pi j2.2 classes
 
Pi j1.0 workshop-introduction
Pi j1.0 workshop-introductionPi j1.0 workshop-introduction
Pi j1.0 workshop-introduction
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignment
 
Pi j1.1 what-is-java
Pi j1.1 what-is-javaPi j1.1 what-is-java
Pi j1.1 what-is-java
 

Recently uploaded

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 

Recently uploaded (20)

Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

Pi j1.4 loops

  • 1. Programming in Java 5-day workshop Loops Matt Collison JP Morgan Chase 2021 PiJ1.4: Loops
  • 2. Session overview Loops • for loops • while loops break and continue
  • 3. Loops • A loop can be used to execute a block of statements repeatedly. If the repeating time is: • predictable: usually use for loop • unpredictable: usually use while or do-while loop for ( initialization; condition; expression ){ ... } • Example: for( int i=1 ; i<10 ; i++ ){ ... }
  • 4. Alternatives for loops • Q1: How about only printing the odd numbers smaller than 10? for ( initialization; condition; expression ){ ... } for( int i=1; i<10; i++ ){ if( I % 2 != 0 ){ System.out.println( i ); } } • Q2: How about printing the numbers in a descending order? for( int i=9; i>=1; i--){ ... }
  • 5. for-each loops for ( Type var : array ) { ... } • Example: int[] numArray = {7,2,6,0} for ( int i : numArray ) { System.out.println("number is: " + i); } Note: the use of a colon
  • 6. while and do while loops while(Boolean expression) { ... } do { ... } while ( <Boolean expression> ) • When the condition becomes false, program control passes to the line immediately following the loop. • while loop might not ever run. • do-while loop runs at least once.
  • 7. Examples Calculate the factorial of n (=1*2*...*n) using the three types of loops. Option 1: for loop: int n = 5; int factorial = 1; for (int number = 1; number <= n; ++number) { factorial *= number; }
  • 8. Examples Calculate the factorial of n (=1*2*...*n) using the three types of loops. Option 2: while loop: int n = 5; int factorial = 1; int number = 1; while (number<=n) { factorial *= number; number++; //update }
  • 9. Examples Calculate the factorial of n (=1*2*...*n) using the three types of loops. Option 3: do-while loop: int n = 5; int factorial = 1; int number = 1; do{ factorial *= number; number++; //update } while (number<=n); Should we print or return the factorial?
  • 10. break and continue • The break statement is used to jump out of the loop or switch statement. • The continue statement is used to skip to the next iteration of the loop.
  • 11. break • Note: Only jump out of the innermost enclosing loop of the statement. int n = 5; for ( int i = 1 ; i < n ; i++ ){ for ( int j = 1 ; j < n ; j++ ){ if ( j > i) { break; } else { System.out.print( j + " "); } } // break comes here if it runs System.out.println(); } What is the output?
  • 12. continue • The continue statement skips the current iteration of a loop. Only skip the innermost enclosing loop of the statement. for (int i=0;i<=10;i++){ if (i==5) { continue; } System.out.println(i); } System.out.println("Done!"); 1. What is the output? 2. What is the output if replacing continue; with break;? 3. What is the output if replacing continue; with return;?
  • 13. Summary • Loop control statements • for loop • for ( int i=0; i<n; i++) { … } • while loop and do-while loop • Both for and while loops might not ever run, do-while loop runs at least once • break and continue • break: jump out of the loop or switch statement. • continue: skips the current iteration of a loop. • Both only have effect on the innermost enclosing loop.
  • 14. Learning resources The workshop homepage https://mcollison.github.io/JPMC-java-intro-2021/ The course materials https://mcollison.github.io/java-programming-foundations/ • Session worksheets – updated each week
  • 15. Additional resources • Think Java: How to think like a computer scientist • Allen B Downey (O’Reilly Press) • Available under Creative Commons license • https://greenteapress.com/wp/think-java-2e/ • Oracle central Java Documentation – https://docs.oracle.com/javase/8/docs/api/ • Other sources: • W3Schools Java - https://www.w3schools.com/java/ • stack overflow - https://stackoverflow.com/ • Coding bat - https://codingbat.com/java

Editor's Notes

  1. Answer: 1 1 2 1 2 3 1 2 3 4
  2. Answer 1: 0 1 2 3 4 Done Answer 2: 0 1 2 3 4 Answer 3: 0 1 2 3 4
  3. All resources hang from the ELE pages. How many of you have looked through them?