ICSE Class 9 Computer Applications Question 5 of 17

Nested for loops — Question 5

Back to all questions
5
Question

Question 3(iii)

Write a program in Java to display the following patterns.

#
* *
# # #
* * * * 
# # # # #
Answer
public class KboatPattern
{
    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)
                    System.out.print(ch2 + " ");
                else
                    System.out.print(ch1 + " ");
            }
            System.out.println();
        }
    }
}
Output
BlueJ output of KboatPattern.java