Print Diamond in Java
Advertisements
Java Program to Print Diamond Pattern
In Java language you can print diamond shape by using for loop or by using while loop, this pattern achieve through nested loop concept. Here no need to use new concept just follow c programming concept only use java programming syntax in place of c programming syntax. In below code i will show you how to design java program to print diamond pattern
Java Program to Print Diamond Pattern
import java.util.Scanner; class Dimond { public static void main(String[] args) { int n, c, k, space = 1; Scanner s=new Scanner(System.in); System.out.println("Enter number of rows: "); n=s.nextInt(); space = n - 1; for (k = 1; k<=n; k++) { for (c = 1; c<=space; c++) System.out.print(" "); space--; for (c = 1; c<= 2*k-1; c++) System.out.print("*"); System.out.print("\n"); } space = 1; for (k = 1; k<= n - 1; k++) { for (c = 1; c<= space; c++) System.out.print(" "); space++; for (c = 1 ; c<= 2*(n-k)-1; c++) System.out.print("*"); System.out.println(""); } } }
Output
Enter nubmer of rows: 5 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Syntax to compile and run java program
Syntax
for compile -> c:/>javac Diamond.java for run -> c:/>java Diamond
Explanation of Code
- Scanner s=new Scanner(System.in): are used for receive input from keyboard.
- nextInt(): method are used for get integer type value from keyboard.
- System.out.println("....."): are used for display message on screen or console.
- System.out.print("....."): are used for display message on screen or console but cursor not move in new line.
- System.out.println("....."): are used for display message on screen or console cursor move in new line.
Google Advertisment