PATTERNS IN JAVA
NESTED LOOPS
Question 1
Write a program to generate the following output.
*
* #
* # *
* # * #
* # * # *
Answer
class pattern1
{
public static void main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
if (j % 2 == 0)
[Link]("# ");
else
[Link]("* ");
}
[Link]();
}
}
}
Question 2
Write a program to print the series given below.
5 55 555 5555 55555 555555
Answer
class series1
{
public static void main(String args[]) {
for (int i = 1; i <= 6; i++) {
for (int j = 0; j < i; j++) {
[Link]('5');
}
[Link](' ');
}
}
}
Output
Question 3
Write a program in Java to display the following patterns.
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Answer
class pattern2
{
public static void main(String args[]) {
int a = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
[Link](a++ + "\t");
}
[Link]();
}
}
}
Output
Question 4
Write a program in Java to display the following patterns.
1 * * * *
* 2 * * *
* * 3 * *
* * * 4 *
* * * * 5
Answer
class pattern3
{
public static void main(String args[]) {
char ch = '*';
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5 ; j++) {
if(i == j)
[Link](i + " ");
else
[Link](ch + " ");
}
[Link]();
}
}
}
Output :
Question 5
Write a program in Java to display the following patterns.
#
* *
# # #
* * * *
# # # # #
Answer
class pattern4
{
public static void main(String args[]) {
char ch1 = '#', ch2 = '*';
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
if (i % 2 == 0)
[Link](ch2 + " ");
else
[Link](ch1 + " ");
}
[Link]();
}
}
}
Output