×

Java Programs

Java Practice

Java program to print upper diamond pattern of numbers

In this java program, we are going to print a pattern of number (Upper half diamond) till given number of rows. Submitted by Preeti Jain, on March 30, 2018

Given number of rows and we have to print a pattern of numbers (upper diamond pattern) in java.

Example:

    Input: 
    Enter number or rows: 5

    Output:
            1
           121
          12321
         1234321
        123454321
    Input: 
    Enter number or rows: 6

    Output:
         1
        121
       12321
      1234321
     123454321
    12345654321

Print upper diamond pattern of numbers in java

import java.util.Scanner;

class Pattern1
{
	public static void main(String[] args)
	{
		int num_of_rows,i,j,temp;

		/* Scanner class is used to take input from user */
		Scanner sc = new Scanner(System.in);

		/* Display message for user */
		System.out.println("Enter Number Of Rows");

		/* Get input from user */
		num_of_rows = sc.nextInt();

		/* this loop is used for number of row */
		for(i=1;i<=num_of_rows;++i)
		{
			/* initially number should be starting from 1 at
			every row so we will take temp variable */
			temp = 1;
			/* this loop is used for column */
			for(j=1;j<=(2*num_of_rows-1);++j)
			{
				if(j>=(num_of_rows+1-i) && j<=(num_of_rows-1+i))
				{
					System.out.print(temp);			
					/* this statement will check number of column 
					is even if yes then if statement will execute 
					otherwise else will executes */
					if((2*num_of_rows-1)%2==0)
					{
						if(j<(2*num_of_rows-1)/2)
						{
							temp++;
						}
						else
						{
							temp--;
						}
					}
					else
					{
						if(j<(2*num_of_rows-1)/2+1)
						{
							temp++;
						}
						else
						{
							temp--;
						}
					}
				}
				else
					System.out.print(" ");
			}
			System.out.println();
		}
	}
}


Comments and Discussions!

Load comments ↻





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