SlideShare une entreprise Scribd logo
1  sur  17
ORGANIZED BY MAJID JHATIAL
JAVA PROGRAMMER
My majid2936@gmail.com
Only for loop exercise and a lot of example in
For loop
Coming soon upload while-loop do-while loop
LOOP REPETITION STATEMENTS
Repetition of statements allow us to
execute a statements multiple time.
Java has three kinds repetition
statements
1 for loop
2 While loop
3 Do-while loop
WHAT IS FOR LOOP ?
For loop is also known as counter loop
There are three part of for loop.
following syntax:
For(initialization ,condition; increment )
1 Initialization is executed once before the loop
begins
2 The statement is executed until the condition
becomes false
3 The increment portion is executed at the end of each
teration
THE FOR STATEMENTS
Example for loop
For(int count=1 ;count<=5; count++){
System.out.println(count);
}
1 Initialization section can be declare the variable
2 Increment section can be performed any calculation
for (int num=100; num > 0; num -= 5){
System.out.println (num);
}
INFINITE LOOP
For example infinite loop
for(int count=1; count<=14; i--){
System.out.println(count);
}
Infinite loop will continue execute until interrupter
(Ctrl-c)
ENDING LOOPING PROGRAM
Break
Break statements result in the terminate of
statements .which applies(Do-while,for,while, switch) . The
break statements gets you out of loop. No meter what the
loop e ending condition. Break immediately says. I am out
here.
Continue
continue skips the statements after the continue
statement and keeps looping.
Continue perform a jump to the next test condition in a loop
the condition statement may be used only in iteration
statements (loop)
THE BREAK
Break example in for loop syntax
for(int i=1; i<=30; i++){ output : 1,2,3
if(i==3){
break;
}
System.out.println(i);
}
Int count=0;
for(int i=1; i<=30; i++){
if(i==16){
break;
}
System.out.println(i);
count++;
}
System.out.println(“Totle=”+count);
CONTINUE EXAMPLE
for(int count=1; count<=30; i++){
if(count==13){
continue;
}
System.out.print(count);
}
int a=0;
for(int count=1; i<=22; count++){
if(count==13){
continue;
}
System.out.oprintln(count);
a++;
}
System.out.println(a);
FIBONACCI SERIES
Enter number 5 then output 1,1,2,3
Scanner ob=new Scanner(System.in);
System.out.println(“Enter the number”);
int i,a=0,b=1,c=0;
int num=ob.nextInt();
for( i=1; i<=num; i++){
System.out.println(c);
a=b;
b=c;
c=a+b;
}
FACTORIAL SERIES
Example factorial number and enter the 5 number t then
output 120..
Scanner bo = new Scanner(System.in);
System.out.println(“Enter the number”);
int fact=1;
int num = ob.nextInt();
for(int i=1; i<=num; i++){
fact=fact*i;
System.out.println(“this factorial number ”+fact);
}
PRIME NUMBER
int n;
int status = 1, num = 3;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of n:");
n = scanner.nextInt();
if (n >= 1) {
System.out.println("First "+n+" prime numbers are:");
System.out.println(2); }
for ( int i = 2 ; i <=n ; ) {
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ ) {
if ( num%j == 0 ) {
status = 0;
break; }
}
if ( status != 0){
System.out.println(num);
i++; }
status = 1;
num++; }
NEST FOR LOOP
For loop inside for loop is called nested for loop
A for loop can contain any kind of statement in its body,
including another for loop.
follow syntax
for( outer ){
for(inner){
}
for(----; ---; ){
}
}
practice nest loop
PATRICE NEST LOOP SAME EXAMPLE
class Test{
public static void main(String arg[]){
for(int i=1 ; i=4; i++ ){
f(int j=1; j<=4; j++ ){
}// inner loop close
System.out.println(j);
}// outer loop close;
}
}
another example
for(int i=2 i<5; i++ ){
for(int j=i; j<=5; j++){
System.out.println(i);
}
System.out.println();
}
for( int i=1; i<=10 ; i++){
for(int j=1; j<10; j++ ){
System.out.println(j);
j++;
}
}
for( int i=1; i<=10 ; i++){
for(int j=1; j>10; j++ ){
System.out.println(j);
j++;
}
System.out.println(i);
}
for( int i=1; i>=10 ; i--){
for(int j=1; j<10; j++ ){
System.out.println(j);
j++;
}
}
Nested for loop exercise
What is the output of the following nested for
loop?
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
Output:
*
**
***
****
*****
******
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.println();
}
Output?
What is the output of the following nested for loops?
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= (5 - i); j++) {
System.out.print(" ");
}
for (int k = 1; k <= i; k++) {
System.out.print(i);
}
System.out.println();
}
Answer:
1
22
333
4444
55555
This loop repeats 10 times, with i from 1 to 10.
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 5; j++) { // loop goes 5 times
System.out.print(j); // print the j
}
System.out.println();
}
Better:
// Prints 12345 ten times on ten separate lines.
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 5; j++) {
System.out.print(j);
}
System.out.println(); // end the line of output
}

Contenu connexe

Tendances

Java Programming: Loops
Java Programming: LoopsJava Programming: Loops
Java Programming: Loops
Karwan Mustafa Kareem
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 

Tendances (20)

Loops Basics
Loops BasicsLoops Basics
Loops Basics
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Decision making and loop in C#
Decision making and loop in C#Decision making and loop in C#
Decision making and loop in C#
 
Methods in C#
Methods in C#Methods in C#
Methods in C#
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Java Programming: Loops
Java Programming: LoopsJava Programming: Loops
Java Programming: Loops
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Loops c++
Loops c++Loops c++
Loops c++
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
OOP java
OOP javaOOP java
OOP java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Command line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialCommand line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorial
 
Loops in java script
Loops in java scriptLoops in java script
Loops in java script
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Loop(for, while, do while) condition Presentation
Loop(for, while, do while) condition PresentationLoop(for, while, do while) condition Presentation
Loop(for, while, do while) condition Presentation
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Loops in c++ programming language
Loops in c++ programming language Loops in c++ programming language
Loops in c++ programming language
 

En vedette

MEDC6000ThesisResearchProject_Lane
MEDC6000ThesisResearchProject_LaneMEDC6000ThesisResearchProject_Lane
MEDC6000ThesisResearchProject_Lane
Kristina Lane
 

En vedette (17)

Java Basics
Java BasicsJava Basics
Java Basics
 
La valla
La vallaLa valla
La valla
 
1426 1001 олимпиадн. и занимат. задачи по математике балаян э.н-2008 -364с
1426  1001 олимпиадн. и занимат. задачи по математике балаян э.н-2008 -364с1426  1001 олимпиадн. и занимат. задачи по математике балаян э.н-2008 -364с
1426 1001 олимпиадн. и занимат. задачи по математике балаян э.н-2008 -364с
 
русский язык. справочник 2013 224с
русский язык. справочник 2013  224срусский язык. справочник 2013  224с
русский язык. справочник 2013 224с
 
108 грамматика русского языка в таблицах и схемах новичёнок и.к-2008 -96с
108  грамматика русского языка в таблицах и схемах новичёнок и.к-2008 -96с108  грамматика русского языка в таблицах и схемах новичёнок и.к-2008 -96с
108 грамматика русского языка в таблицах и схемах новичёнок и.к-2008 -96с
 
744 геометрия за 24 часа жалпанова, калинина, мальянц-2009 -304с
744  геометрия за 24 часа жалпанова, калинина, мальянц-2009 -304с744  геометрия за 24 часа жалпанова, калинина, мальянц-2009 -304с
744 геометрия за 24 часа жалпанова, калинина, мальянц-2009 -304с
 
Pae etapa 4 ejecucion
Pae  etapa 4 ejecucionPae  etapa 4 ejecucion
Pae etapa 4 ejecucion
 
Editie Speciala Alegeri 2016
Editie Speciala Alegeri 2016Editie Speciala Alegeri 2016
Editie Speciala Alegeri 2016
 
1065 2 уравнения и нерав. с модулями и метод. их решен.-севрюков, смоляков_2...
1065 2  уравнения и нерав. с модулями и метод. их решен.-севрюков, смоляков_2...1065 2  уравнения и нерав. с модулями и метод. их решен.-севрюков, смоляков_2...
1065 2 уравнения и нерав. с модулями и метод. их решен.-севрюков, смоляков_2...
 
1230 2 сборник задач по матем. с реш. 8-11кл- п.р. сканави м.и_2012 -624с
1230 2  сборник задач по матем. с реш. 8-11кл- п.р. сканави м.и_2012 -624с1230 2  сборник задач по матем. с реш. 8-11кл- п.р. сканави м.и_2012 -624с
1230 2 сборник задач по матем. с реш. 8-11кл- п.р. сканави м.и_2012 -624с
 
761 задачи с параметрами. иррац. уравнения, нерав., системы, задачи с модуле...
761  задачи с параметрами. иррац. уравнения, нерав., системы, задачи с модуле...761  задачи с параметрами. иррац. уравнения, нерав., системы, задачи с модуле...
761 задачи с параметрами. иррац. уравнения, нерав., системы, задачи с модуле...
 
106 грамотность за 12 занятий. русский язык фролова т.я-2004 -64с
106  грамотность за 12 занятий. русский язык фролова т.я-2004 -64с106  грамотность за 12 занятий. русский язык фролова т.я-2004 -64с
106 грамотность за 12 занятий. русский язык фролова т.я-2004 -64с
 
русский язык. весь курс школьн. прогр. в схемах и таблицах 2007 95с
русский язык. весь курс школьн. прогр. в схемах и таблицах 2007  95срусский язык. весь курс школьн. прогр. в схемах и таблицах 2007  95с
русский язык. весь курс школьн. прогр. в схемах и таблицах 2007 95с
 
MEDC6000ThesisResearchProject_Lane
MEDC6000ThesisResearchProject_LaneMEDC6000ThesisResearchProject_Lane
MEDC6000ThesisResearchProject_Lane
 
Trabajo sena 1
Trabajo sena 1Trabajo sena 1
Trabajo sena 1
 
762 задачи с параметрами. примен. свойств функций, преобр. неравенств локоть...
762  задачи с параметрами. примен. свойств функций, преобр. неравенств локоть...762  задачи с параметрами. примен. свойств функций, преобр. неравенств локоть...
762 задачи с параметрами. примен. свойств функций, преобр. неравенств локоть...
 
Letra Inicial e Imagens
Letra Inicial e ImagensLetra Inicial e Imagens
Letra Inicial e Imagens
 

Similaire à for loop in java

Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
Vince Vo
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
jahanullah
 
First come first serve scheduling algorithm (FCFS) is the process th.pdf
First come first serve scheduling algorithm (FCFS) is the process th.pdfFirst come first serve scheduling algorithm (FCFS) is the process th.pdf
First come first serve scheduling algorithm (FCFS) is the process th.pdf
apjewellers
 
Project_Euler_No_104_Pandigital_Fibonacci_ends
Project_Euler_No_104_Pandigital_Fibonacci_endsProject_Euler_No_104_Pandigital_Fibonacci_ends
Project_Euler_No_104_Pandigital_Fibonacci_ends
? ?
 

Similaire à for loop in java (20)

Pi j1.4 loops
Pi j1.4 loopsPi j1.4 loops
Pi j1.4 loops
 
DSA 103 Object Oriented Programming :: Week 3
DSA 103 Object Oriented Programming :: Week 3DSA 103 Object Oriented Programming :: Week 3
DSA 103 Object Oriented Programming :: Week 3
 
Comp102 lec 6
Comp102   lec 6Comp102   lec 6
Comp102 lec 6
 
06.Loops
06.Loops06.Loops
06.Loops
 
Ch5(loops)
Ch5(loops)Ch5(loops)
Ch5(loops)
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
130707833146508191
130707833146508191130707833146508191
130707833146508191
 
Week2 ch4 part1edited 2020
Week2 ch4 part1edited 2020Week2 ch4 part1edited 2020
Week2 ch4 part1edited 2020
 
Week2 ch4 part1edited 2020
Week2 ch4 part1edited 2020Week2 ch4 part1edited 2020
Week2 ch4 part1edited 2020
 
Algorithms with-java-1.0
Algorithms with-java-1.0Algorithms with-java-1.0
Algorithms with-java-1.0
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
 
ch04-conditional-execution.ppt
ch04-conditional-execution.pptch04-conditional-execution.ppt
ch04-conditional-execution.ppt
 
First come first serve scheduling algorithm (FCFS) is the process th.pdf
First come first serve scheduling algorithm (FCFS) is the process th.pdfFirst come first serve scheduling algorithm (FCFS) is the process th.pdf
First come first serve scheduling algorithm (FCFS) is the process th.pdf
 
ICP - Lecture 9
ICP - Lecture 9ICP - Lecture 9
ICP - Lecture 9
 
Project_Euler_No_104_Pandigital_Fibonacci_ends
Project_Euler_No_104_Pandigital_Fibonacci_endsProject_Euler_No_104_Pandigital_Fibonacci_ends
Project_Euler_No_104_Pandigital_Fibonacci_ends
 
For Loops and Nesting in Python
For Loops and Nesting in PythonFor Loops and Nesting in Python
For Loops and Nesting in Python
 
Loops
LoopsLoops
Loops
 
Java presentation
Java presentationJava presentation
Java presentation
 
For loop java
For loop javaFor loop java
For loop java
 

Dernier

No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
Sheetaleventcompany
 
Uncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac FolorunsoUncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac Folorunso
Kayode Fayemi
 

Dernier (20)

The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdfThe workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
 
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
 
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
 
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night EnjoyCall Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
 
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdfAWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
 
SaaStr Workshop Wednesday w/ Lucas Price, Yardstick
SaaStr Workshop Wednesday w/ Lucas Price, YardstickSaaStr Workshop Wednesday w/ Lucas Price, Yardstick
SaaStr Workshop Wednesday w/ Lucas Price, Yardstick
 
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
 
ICT role in 21st century education and it's challenges.pdf
ICT role in 21st century education and it's challenges.pdfICT role in 21st century education and it's challenges.pdf
ICT role in 21st century education and it's challenges.pdf
 
Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510
 
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
 
lONG QUESTION ANSWER PAKISTAN STUDIES10.
lONG QUESTION ANSWER PAKISTAN STUDIES10.lONG QUESTION ANSWER PAKISTAN STUDIES10.
lONG QUESTION ANSWER PAKISTAN STUDIES10.
 
Presentation on Engagement in Book Clubs
Presentation on Engagement in Book ClubsPresentation on Engagement in Book Clubs
Presentation on Engagement in Book Clubs
 
Report Writing Webinar Training
Report Writing Webinar TrainingReport Writing Webinar Training
Report Writing Webinar Training
 
Uncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac FolorunsoUncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac Folorunso
 
Dreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video TreatmentDreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video Treatment
 
My Presentation "In Your Hands" by Halle Bailey
My Presentation "In Your Hands" by Halle BaileyMy Presentation "In Your Hands" by Halle Bailey
My Presentation "In Your Hands" by Halle Bailey
 
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara ServicesVVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
 
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
 
Causes of poverty in France presentation.pptx
Causes of poverty in France presentation.pptxCauses of poverty in France presentation.pptx
Causes of poverty in France presentation.pptx
 
Dreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio IIIDreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio III
 

for loop in java

  • 1. ORGANIZED BY MAJID JHATIAL JAVA PROGRAMMER My majid2936@gmail.com Only for loop exercise and a lot of example in For loop Coming soon upload while-loop do-while loop
  • 2. LOOP REPETITION STATEMENTS Repetition of statements allow us to execute a statements multiple time. Java has three kinds repetition statements 1 for loop 2 While loop 3 Do-while loop
  • 3. WHAT IS FOR LOOP ? For loop is also known as counter loop There are three part of for loop. following syntax: For(initialization ,condition; increment ) 1 Initialization is executed once before the loop begins 2 The statement is executed until the condition becomes false 3 The increment portion is executed at the end of each teration
  • 4. THE FOR STATEMENTS Example for loop For(int count=1 ;count<=5; count++){ System.out.println(count); } 1 Initialization section can be declare the variable 2 Increment section can be performed any calculation for (int num=100; num > 0; num -= 5){ System.out.println (num); }
  • 5. INFINITE LOOP For example infinite loop for(int count=1; count<=14; i--){ System.out.println(count); } Infinite loop will continue execute until interrupter (Ctrl-c)
  • 6. ENDING LOOPING PROGRAM Break Break statements result in the terminate of statements .which applies(Do-while,for,while, switch) . The break statements gets you out of loop. No meter what the loop e ending condition. Break immediately says. I am out here. Continue continue skips the statements after the continue statement and keeps looping. Continue perform a jump to the next test condition in a loop the condition statement may be used only in iteration statements (loop)
  • 7. THE BREAK Break example in for loop syntax for(int i=1; i<=30; i++){ output : 1,2,3 if(i==3){ break; } System.out.println(i); } Int count=0; for(int i=1; i<=30; i++){ if(i==16){ break; } System.out.println(i); count++; } System.out.println(“Totle=”+count);
  • 8. CONTINUE EXAMPLE for(int count=1; count<=30; i++){ if(count==13){ continue; } System.out.print(count); } int a=0; for(int count=1; i<=22; count++){ if(count==13){ continue; } System.out.oprintln(count); a++; } System.out.println(a);
  • 9. FIBONACCI SERIES Enter number 5 then output 1,1,2,3 Scanner ob=new Scanner(System.in); System.out.println(“Enter the number”); int i,a=0,b=1,c=0; int num=ob.nextInt(); for( i=1; i<=num; i++){ System.out.println(c); a=b; b=c; c=a+b; }
  • 10. FACTORIAL SERIES Example factorial number and enter the 5 number t then output 120.. Scanner bo = new Scanner(System.in); System.out.println(“Enter the number”); int fact=1; int num = ob.nextInt(); for(int i=1; i<=num; i++){ fact=fact*i; System.out.println(“this factorial number ”+fact); }
  • 11. PRIME NUMBER int n; int status = 1, num = 3; Scanner scanner = new Scanner(System.in); System.out.println("Enter the value of n:"); n = scanner.nextInt(); if (n >= 1) { System.out.println("First "+n+" prime numbers are:"); System.out.println(2); } for ( int i = 2 ; i <=n ; ) { for ( int j = 2 ; j <= Math.sqrt(num) ; j++ ) { if ( num%j == 0 ) { status = 0; break; } } if ( status != 0){ System.out.println(num); i++; } status = 1; num++; }
  • 12. NEST FOR LOOP For loop inside for loop is called nested for loop A for loop can contain any kind of statement in its body, including another for loop. follow syntax for( outer ){ for(inner){ } for(----; ---; ){ } } practice nest loop
  • 13. PATRICE NEST LOOP SAME EXAMPLE class Test{ public static void main(String arg[]){ for(int i=1 ; i=4; i++ ){ f(int j=1; j<=4; j++ ){ }// inner loop close System.out.println(j); }// outer loop close; } } another example for(int i=2 i<5; i++ ){ for(int j=i; j<=5; j++){ System.out.println(i); } System.out.println(); }
  • 14. for( int i=1; i<=10 ; i++){ for(int j=1; j<10; j++ ){ System.out.println(j); j++; } } for( int i=1; i<=10 ; i++){ for(int j=1; j>10; j++ ){ System.out.println(j); j++; } System.out.println(i); } for( int i=1; i>=10 ; i--){ for(int j=1; j<10; j++ ){ System.out.println(j); j++; } }
  • 15. Nested for loop exercise What is the output of the following nested for loop? for (int i = 1; i <= 6; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); } Output: * ** *** **** ***** ****** for (int i = 1; i <= 6; i++) { for (int j = 1; j <= i; j++) { System.out.print(i); } System.out.println(); } Output?
  • 16. What is the output of the following nested for loops? for (int i = 1; i <= 5; i++) { for (int j = 1; j <= (5 - i); j++) { System.out.print(" "); } for (int k = 1; k <= i; k++) { System.out.print(i); } System.out.println(); } Answer: 1 22 333 4444 55555
  • 17. This loop repeats 10 times, with i from 1 to 10. for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 5; j++) { // loop goes 5 times System.out.print(j); // print the j } System.out.println(); } Better: // Prints 12345 ten times on ten separate lines. for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 5; j++) { System.out.print(j); } System.out.println(); // end the line of output }