Program to print half Diamond star pattern
Last Updated :
13 Mar, 2023
Given an integer N, the task is to print half-diamond-star pattern.
*
**
***
****
*****
******
*****
****
***
**
*
Examples:
Input: N = 3
Output:
*
**
***
**
*
Input: N = 6
Output:
*
**
***
****
*****
******
*****
****
***
**
*
Approach: The idea is to break the pattern into two halves that is upper half and lower half. Then print them separately with the help of the loops. The key observation for printing the upper half and lower half is described as below:
- Upper half: The upper half of the pattern contains star ‘*’ in increasing order where ith line contains following number of star:
Number of '*' in ith line =
- Lower Half: The lower half of the pattern contains star ‘*’ in decreasing order where ith line contains following number of star:
Number of '*' in ith line =
C++
#include <iostream>
using namespace std;
void halfDiamondStar( int N)
{
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < i + 1; j++)
cout << "*" ;
cout << "\n" ;
}
for (i = 1; i < N; i++) {
for (j = i; j < N; j++)
cout << "*" ;
cout << "\n" ;
}
}
int main()
{
int N = 5;
halfDiamondStar(N);
}
|
Java
import java.util.*;
class GFG{
static void halfDiamondStar( int N)
{
int i, j;
for (i = 0 ; i < N; i++)
{
for (j = 0 ; j < i + 1 ; j++)
System.out.print( "*" );
System.out.print( "\n" );
}
for (i = 1 ; i < N; i++)
{
for (j = i; j < N; j++)
System.out.print( "*" );
System.out.print( "\n" );
}
}
public static void main(String[] args)
{
int N = 5 ;
halfDiamondStar(N);
}
}
|
Python3
def halfDiamondStar(N):
for i in range (N):
for j in range ( 0 , i + 1 ):
print ( "*" , end = "")
print ()
for i in range ( 1 , N):
for j in range (i, N):
print ( "*" , end = "")
print ()
N = 5 ;
halfDiamondStar(N);
|
C#
using System;
class GFG{
static void halfDiamondStar( int N)
{
int i, j;
for (i = 0; i < N; i++)
{
for (j = 0; j < i + 1; j++)
Console.Write( "*" );
Console.Write( "\n" );
}
for (i = 1; i < N; i++)
{
for (j = i; j < N; j++)
Console.Write( "*" );
Console.Write( "\n" );
}
}
public static void Main(String[] args)
{
int N = 5;
halfDiamondStar(N);
}
}
|
Javascript
function halfDiamondStar(N)
{
let i, j;
for (i = 0; i < N; i++)
{
for (j = 0; j < i + 1; j++)
console.log( "*" );
console.log( "<br>" );
console.log( "\n" );
}
for (i = 1; i < N; i++)
{
for (j = i; j < N; j++)
console.log( "*" );
console.log( "<br>" );
console.log( "\n" );
}
}
let N = 5;
halfDiamondStar(N);
|
Output*
**
***
****
*****
****
***
**
*
Time complexity: O(N2) where N is given integer
Auxiliary Space: O(1)
Please Login to comment...