In this Java tutorial we are going to see how to display four patterns using the while and for loops.
Notice that this example works in every language as well, just change the print() method depending on yours.
It seems easy, but it demands a certain reflection before finding the solution.
Of course if you are a beginner, don’t be afraid, practising is the key of everything!
Code
public class PrintingFourPatternUsingLoops {
/**
* @param args
*/
public static void main(String[] args)
{
/**
* First with for
*/
for (int i = 1; i < 7; i++) {
for (int j = 1; j < i + 1; j++) {
System.out.print(j);
}
System.out.println();
}
/**
* Second with for
*/
System.out.println();
for(int k = 8; k > 1; k--) {
for(int l = 1; l < k - 1; l++){
System.out.print(l);
}
System.out.println();
}
/**
* Third with while
*/
int i = 1;
int j = 1;
int k = 1;
int max = 7;
while (i < max) {
k = 1;
while (k < max - i) {
System.out.print(' ');
++k;
}
while (j > 0) {
System.out.print(max - (max - j));
--j;
}
++i;
j+=i;
System.out.println("");
}
System.out.println("");
/**
* Fourth with while
*/
i = 1;
j = 1;
k = 1;
max = 7;
int max2 = 8;
int tmp = 0;
while (i < max) {
k = 1;
while (k < max - (max - i)) {
System.out.print(' ');
++k;
}
tmp = max2 - i;
j = 1;
while (j < tmp) {
System.out.print(max - (max - j));
++j;
}
++i;
System.out.println("");
}
}
}
Output
1
12
123
1234
12345
123456
123456
12345
1234
123
12
1
1
21
321
4321
54321
654321
123456
12345
1234
123
12
1
Finally
Once again, nothing is impossible, this example shows it.
Great job, you made it.