×

Java Programs

Java Practice

Java program to print patterns (2 Examples based on numbers pattern)

Here, we are implementing two java programs that will print two different patterns based on given input; input will be the numbers of rows to print in the patterns.
Submitted by IncludeHelp, on December 14, 2017

Pattern 1

    1 
    1 2 
    1 2 3 
    1 2 3 4 
    1 2 3 4 5 
    1 2 3 4 5 6 
    1 2 3 4 5 6 7 
    1 2 3 4 5 6 7 8 
    1 2 3 4 5 6 7 8 9 
    1 2 3 4 5 6 7 8 9 10 

Pattern 2

    1 2 3 4 5 
    1 2 3 4 
    1 2 3 
    1 2 
    1 
    1 2 
    1 2 3 
    1 2 3 4 
    1 2 3 4 5 

Program to print pattern 1 in java

import java.util.Scanner;

public class Pattern27 
{
	public static void main(String[] args) 
    {
		// create scanner class object.
        Scanner sc = new Scanner(System.in);
         
        // input row for printing pattern.
        System.out.print("Enter row for pattern : ");
         
        int rows = sc.nextInt();
        
        System.out.println("Here is your pattern....!!!");
         
        // loop for printing pattern.
        for (int i = 1; i <= rows; i++) 
        {
            for (int j = 1; j <= i; j++)
            {
                System.out.print(j+" ");
            }            
            System.out.println();
        }
        sc.close();
    }
}

Output

Enter row for pattern : 10
Here is your pattern....!!!
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
1 2 3 4 5 6 
1 2 3 4 5 6 7 
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8 9 
1 2 3 4 5 6 7 8 9 10 

Program to print pattern 2 in java

import java.util.Scanner;

public class Pattern28 
{
	public static void main(String[] args) 
    {
		// create scanner class object.
        Scanner sc = new Scanner(System.in);
         
        // input row for printing pattern.
        System.out.print("Enter row for pattern : ");
         
        int rows = sc.nextInt();
         
        System.out.println("Here is your pattern....!!!");
        
        // this loop will print the pattern in two parts first half and second half.
        for (int i = rows; i >= 1; i--) 
        {
            for (int j = 1; j <= i; j++)
            {
                System.out.print(j+" ");
            }      
            System.out.println();
        }
        
        for (int i = 2; i <= rows; i++) 
        {
            for (int j = 1; j <= i; j++)
            {
                System.out.print(j+" ");
            }             
            System.out.println();
        }
        sc.close();
    }
}

Output

Enter row for pattern : 5
Here is your pattern....!!!
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.