Don’t worry, unlock all articles / blogs on PrepInsta by just simply logging in on our website
Java Program for Half Diamond Star Pattern
May 24, 2020
Printing Half Diamond Star Pattern
In this program we’re going to code half diamond star pattern
In this program take a input from user and store in inside the variable as no and then take for loop start from i=1 to i<=no and then take another for loop to print star which is start from j=1 to j<=i , and then take second another inner for loop start from i=no-1 to i>0 and then take j inner for loop start from i=1 to j<=i then print star statement after that take line changement
Algorithm:
Enter the number as input from the user and store it in any variable.(‘no‘ in this case).
Run a loop ‘no’ number of times to iterate through each of the rows. From i=1 to i<=no. The loop should be structured as for (int i = 1; i <= no; i++)
Inside the main loop take another loop start with j=1 to j<=i and print above stars as System.out.print(“*”); after this inside loop take System.out.println(); to take a new line
After the main loop take another loop to make downwards stars loop start with int i = no-1 to i >0; inside this take another loop to print stars for (int j = 1; j <=i; j++)
Code in Java:
import java.util.Scanner;
public class Pattern1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no");
int no=sc.nextInt();
for (int i = 1; i <= no; i++) {
for (int j = 1; j <= i; j++)
System.out.print("*");
System.out.println();
}
for (int i = no-1; i >0; i--) {
for (int j = 1; j <=i; j++)
System.out.print("*");
System.out.println();
}
}
}
This code is contributed by Shubham Nigam (Prepinsta Placement Cell Student)
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the limit");
int n = sc.nextInt();
pattern(n);
}
import java.util.Scanner;
public class DiamondPattern{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print(“Enter row :”);
int r = sc.nextInt();
for(int i =1;i<=r;i++){
if(i<=(r/2+1)) {
for(int j =1;j<=i;j++){
System.out.print("*");
}
}else {
for(int k = 1;k<=(r+1-i);k++){
System.out.print("*");
}
}
System.out.println();
}
}
}
import java.util.Scanner;
public class Pattern {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=1;i<=n;i++){
for(int j=1;j=1;i–){
for(int j=1;j<=i;j++){
System.out.print("*");
}
System.out.println();
}
}}
import java.util.*;
public class Testing_file
{
static void pattern(int n)
{
for(int i =1;i<=2*n-1;i++)
{
if(i<=n)
{
for(int j =1;j<=i;j++)
{
System.out.print("* ");
}
}
else
{
for(int j =1;j<=n-(i-n);j++)
{
System.out.print("* ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the limit");
int n = sc.nextInt();
pattern(n);
}
}
Thank you prepinsta for publishing my code…