Hollow lower triangular pattern
Given the value of n, i.e, the number of rows/columns for a square, print the pattern.
Examples :
Input : n = 8
Output :
* * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* * * * * * * *
Input : n = 15
Output :
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* * * * * * * * * * * * * * *
Below is the implementation to print hollow lower triangular pattern :
C++
#include <bits/stdc++.h>
using namespace std;
void print_pattern( int n)
{
int k = 1;
for ( int i = 1; i <= n; i++) {
for ( int j = 1; j <= n; j++) {
if (i == n || j == 1)
cout << " "
<< "*" ;
else if (j < k)
cout << " "
<< " " ;
else
cout << " "
<< "*" ;
}
cout << endl;
k++;
}
}
int main()
{
int n = 8;
print_pattern(n);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void print_pattern( int n)
{
int k = 1 ;
for ( int i = 1 ; i <= n; i++) {
for ( int j = 1 ; j <= n; j++) {
if (i == n || j == 1 )
System.out.print( " "
+ "*" );
else if (j < k)
System.out.print( " "
+ " " );
else
System.out.print( " "
+ "*" );
}
System.out.println();
k++;
}
}
public static void main(String[] args)
{
int n = 8 ;
print_pattern(n);
}
}
|
Python3
def print_pattern(n):
k = 1 ;
for i in range ( 1 , n + 1 ):
for j in range ( 1 , n + 1 ):
if (i = = n or j = = 1 ):
print ( " *" , end = "");
elif (j < k):
print ( " " , end = " " );
else :
print ( " *" , end = "");
print ();
k + = 1 ;
n = 8 ;
print_pattern(n);
|
C#
using System;
class GFG {
static void print_pattern( int n)
{
int k = 1;
for ( int i = 1; i <= n; i++) {
for ( int j = 1; j <= n; j++) {
if (i == n || j == 1)
Console.Write( " "
+ "*" );
else if (j < k)
Console.Write( " "
+ " " );
else
Console.Write( " "
+ "*" );
}
Console.WriteLine();
k++;
}
}
public static void Main()
{
int n = 8;
print_pattern(n);
}
}
|
PHP
<?php
function print_pattern( $n )
{
$k = 1;
for ( $i = 1; $i <= $n ; $i ++)
{
for ( $j = 1; $j <= $n ; $j ++)
{
if ( $i == $n || $j == 1)
echo " *" ;
else if ( $j < $k )
echo " " ;
else
echo " *" ;
}
echo "\n" ;
$k ++;
}
}
$n = 8;
print_pattern( $n );
?>
|
Javascript
<script>
function print_pattern(n) {
var k = 1;
for ( var i = 1; i <= n; i++)
{
for ( var j = 1; j <= n; j++)
{
if (i == n || j == 1) document.write( " " + "*" );
else if (j < k) document.write( " " + " " );
else document.write( " " + "*" );
}
document.write( "<br>" );
k++;
}
}
var n = 8;
print_pattern(n);
</script>
|
Output :
* * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* * * * * * * *
Time Complexity : O(n2) ,where n is number of rows in the pattern.
Auxiliary Space : O(1) ,as we are not using any extra space.
Last Updated :
20 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...