Java program to draw patterns

Theory

You have to use nested loops to draw patterns. Just like C, C+ and Python, Java too has basically two types of loops: the for loop and the while loop. The for loop has a specific format which is called for each loop. Likewise, the while loop has a specific format which is called the do while loop.

 

Pattern 1

Code

package com.physicsinfo;

import java.util.Scanner;

public class Main{
    public static void main(String args[]){
        System.out.print("Enter the number of rows: ");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i=n;i>=0;i--){
            for(int j=0;j<=i;j++){
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output

Java program to draw pattern

Pattern 2

Code

package com.physicsinfo;

import java.util.Scanner;

public class Main{
    public static void main(String args[]){
        System.out.print("Enter the number of rows: ");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i=0;i<n;i++){
            for(int j=0;j<=i;j++){
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output

Java program to draw pattern

Leave a Comment

Your email address will not be published.