A for loop with another for loop is called nested for loop.
Syntax:
for(initialization;condition;increment/decrement){
for(initialization;condition;increment/decrement;){
}//inner for loop
}//outer for loop
Example:
public class nestedForloop{
public static void main(String[] args) {
for(int y=1;y<=3;y++){
for(int x=1;x<=5;x++){
System.out.println(y+" "+x);
}//inner loop
} //outer loop
System.out.print(“Nested For loop”);
}
Pyramid
*
* *
* * *
* * * *
* * * * *
public class Pyramid { public static void main(String[] args) { for(int i=1;i<=5;i++){ for(int j=1;j<=i;j++){ System.out.print("* "); } System.out.println() } } }
* * * * * *
* * * * *
* * * *
* * *
* *
*
public class Pyramid2 { public static void main(String[] args) { int n=6; for(int i=1;i<=n;i++){ for(int j=n;j>=i;j--){ System.out.print("* "); } System.out.println(); } } }
Comments
Post a Comment