ADVERTISEMENT
ADVERTISEMENT

Home » Java programs

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
ADVERTISEMENT

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 */
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.