Print lower triangle with alternate ‘*’ and ‘#’
Last Updated :
14 Mar, 2023
Given a number N which denotes the number of rows, the task is to follow the below pattern to print the first N rows of it.
Pattern:
*
*#
*#*
*#*#
*#*#*
Examples:
Input: N = 2
Output:
*
*#
Input: N = 6
Output:
*
*#
*#*
*#*#
*#*#*
*#*#*#
Approach: Follow the below steps to implement the above pattern:
- Initialize two variables row and col to 1. These will be used to keep track of the current row and column that we are on in the pattern.
- Use a loop to iterate the row from 1 to N. This will be the outer loop and will represent each row of the pattern.
- Inside the outer loop, use another loop to iterate col from 1 to row. This will be the inner loop and will represent each column in the current row.
- Inside the inner loop, check if col is even or odd.
- If it is even, print a “#” character. If it is odd, print a “*” character.
- After the inner loop has been completed, move to the next line (this will start a new row in the pattern).
- After the outer loop has been completed, the pattern has been printed.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n = 6;
for ( int row = 1; row <= n; row++) {
for ( int col = 1; col <= row; col++) {
if (col % 2 == 0) {
cout << "#" ;
}
else {
cout << "*" ;
}
}
cout << endl;
}
return 0;
}
|
Python3
n = 6
for row in range ( 1 , n + 1 ):
for col in range ( 1 , row + 1 ):
if col % 2 = = 0 :
print ( "#" , end = "")
else :
print ( "*" , end = "")
print ()
|
C#
using System;
public class Gfg
{
public static void Main( string [] args)
{
int n = 6;
for ( int row = 1; row <= n; row++) {
for ( int col = 1; col <= row; col++) {
if (col % 2 == 0) {
Console.Write( "#" );
}
else {
Console.Write( "*" );
}
}
Console.Write( "\n" );
}
}
}
|
Javascript
let n = 6;
for (let row = 1; row <= n; row++) {
for (let col = 1; col <= row; col++) {
if (col % 2 == 0) {
console.log( "#" );
}
else {
console.log( "*" );
}
}
console.log( "<br>" );
}
|
Java
import java.util.*;
class GFG{
public static void main(String args[])
{
int n = 6 ;
for ( int row = 1 ; row <= n; row++) {
for ( int col = 1 ; col <= row; col++) {
if (col % 2 == 0 ) {
System.out.print( "#" );
}
else {
System.out.print( "*" );
}
}
System.out.print( "\n" );
}
}
}
|
Output
*
*#
*#*
*#*#
*#*#*
*#*#*#
Time Complexity: O(N2) // since two nested loops are used the time taken by the algorithm to complete all operations is quadratic.
Auxiliary Space: O(1) //since there is a basic arithmetic operation that takes constant time.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...