×

Java Programs

Java Practice

Java program to print upper diamond pattern of numbersand dollars

In this java program, we are going to print a pattern of number and dollars (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 and dollars (upper diamond pattern) in java.

Example:

    Input: 
    Enter number or rows: 4

    Output:
       1
      $2$
     3$4$5
    $6$7$8$
    Input: 
    Enter number or rows: 5

    Output:
         1
        $2$
       3$4$5
      $6$7$8$
    9$10$11$12$13

Print upper diamond pattern of numbers and dollars in java

import java.util.Scanner;

class Pattern2{
	public static void main(String[] args)
	{
		int num_of_rows,i,j,num=1,b=0;
		/* create Scanner class object for user input */
		Scanner sc = new Scanner(System.in);
		/* Display message for user */
		System.out.println("Enter Number Of Rows");
		num_of_rows = sc.nextInt();

		/* Loop for row */
		for(i=1;i<=num_of_rows;++i)
		{
			/*Loop for column */
			for(j=1;j<=(2*num_of_rows-1);++j)
			{
				/* Logic is written in this if ... else */
				if(j>=(num_of_rows+1-i) && 	j<=(num_of_rows-1+i))
					if(b==0)
					{
						System.out.print(num);
						b=1;
						num++;
					}
					else
					{
						System.out.print("$");
						b=0;
					}
					else
						System.out.print(" ");
			}/* End column loop */
			/* This statement is for line change */
			System.out.println();
		}/* End Row Loop */
	}/* End main() */
}/* End class */


Comments and Discussions!

Load comments ↻





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