Y shaped pattern
Last Updated :
26 Sep, 2022
Print a ‘Y’ shaped pattern from asterisks in N number of lines.
Examples:
Input: N = 12
Output:
* *
* *
* *
* *
* *
* *
* *
*
*
*
*
*
Input: 8
Output:
* *
* *
* *
* *
* *
*
*
*
Approach:
Follow the steps to solve this problem:
- Initialize two variable s = N / 2 and t = N / 2.
- Traverse a loop on i from 0 till N-1
- Check if i > s
- Traverse a loop on j from 0 till s-1 and print ” ” i.e., space
- Else,
- Iterate on j from 0 till i-1 and print ” ” i.e., space
- Then print “*” i.e., asterisk
- Iterate on k from 0 till 2*t-1 and print ” ” i.e., space
- Decrement t by 1.
- Print ” *” at the end of each iteration.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int main()
{
int N = 12;
int s = N / 2;
int t = s;
for ( int i = 0; i < N; i++) {
if (i > s) {
for ( int j = 0; j < s; j++)
cout << " " ;
}
else {
for ( int j = 0; j < i; j++)
cout << " " ;
cout << "*" ;
for ( int k = 0; k < 2 * t; k++)
cout << " " ;
t--;
}
cout << " *" << endl;
}
return 0;
}
|
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int N = 12 ;
int s = N / 2 ;
int t = s;
for ( int i = 0 ; i < N; i++) {
if (i > s) {
for ( int j = 0 ; j < s; j++)
System.out.print( " " );
}
else {
for ( int j = 0 ; j < i; j++)
System.out.print( " " );
System.out.print( "*" );
for ( int k = 0 ; k < 2 * t; k++)
System.out.print( " " );
t--;
}
System.out.println( " *" );
}
}
}
|
Python3
N = 12
s = N / 2
t = s
for i in range ( 0 , N):
if (i > s):
for j in range ( 0 , int (s)):
print ( " " , end = "")
else :
for j in range ( 0 , i):
print ( " " , end = "")
print ( "*" , end = "")
for k in range ( 0 , ( 2 * int (t))):
print ( " " , end = "")
t = t - 1
print ( " *" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static void Main()
{
int N = 12;
int s = N / 2;
int t = s;
for ( int i = 0; i < N; i++) {
if (i > s) {
for ( int j = 0; j < s; j++)
Console.Write( " " );
}
else {
for ( int j = 0; j < i; j++)
Console.Write( " " );
Console.Write( "*" );
for ( int k = 0; k < 2 * t; k++)
Console.Write( " " );
t--;
}
Console.WriteLine( " *" );
}
}
}
|
Javascript
<script>
let N = 12;
let s = Math.floor(N / 2);
let t = s;
for (let i = 0; i < N; i++) {
if (i > s) {
for (let j = 0; j < s; j++)
document.write( " " );
}
else {
for (let j = 0; j < i; j++)
document.write( " " );
document.write( "*" );
for (let k = 0; k < 2 * t; k++)
document.write( " " );
t--;
}
document.write( " *" + "<br/>" );
}
</script>
|
Output
* *
* *
* *
* *
* *
* *
* *
*
*
*
*
*
Time Complexity: O(N2), for using nested loops.
Auxiliary Space: O(1), as constant extra space is required.
Share your thoughts in the comments
Please Login to comment...