Here is a collection of few examples for NESTED FOR LOOP.
Simple codes in how to use nested loops,
1.Get the following output :
a.
1
12
123
1234
12345
123456
1234567
12345678
123456789
public class testFor
{
public static void main(String [] args)
{
for (int i=1; i<=9; i++)
{System.out.println();
for (int j=1; j<=i; j++)
{
System.out.print(j);}}System.out.println();
}
}
b.
*
**
***
****
*****
******
*******
********
*********
Star Pattern using nested for loop
public class starForTest
{
public static void main(String [] args)
{
for (int i=1; i<=9; i++)
{
System.out.println();
for (int j=9; j>=i; j--)
{
System.out.print(" ");
}
for (int k=1; k<=i; k++)
{System.out.print("*");
}
}
System.out.println();
}
}
2.A program for sorting an array elements (ascending sort)
public class arrSort
{
public static void main(String args [])
{
int num[]=new int[]
{
20,50,10,70,40,80,30,90,60
};
int t=0;
for (int i=0;
i<num.length; i++)
{
for (int j=i+1;
j<num.length; j++)
if (num[i]>num[j])
{t=num[i];
num[i]=num[j];
num[j]=t;
}
}
System.out.println("Sorting elements in Ascending Order :\n");
for (int i=0; i<num.length; i++)System.out.println(num[i]);
}
}