Program to print the Ladder Pattern
Last Updated :
13 Mar, 2023
Given an integer N, the task is to print the ladder with N steps using ‘*’. The ladder will be with the gap of 3 spaces between two side rails.
Input: N = 3
Output:
* *
* *
*****
* *
* *
*****
* *
* *
*****
* *
* *
Input: N = 4
Output:
* *
* *
*****
* *
* *
*****
* *
* *
*****
* *
* *
*****
* *
* *
Approach: Dividing the pattern into two sub-pattern.
* *
* *
- which will be printed N+1 times
-
*****
* *
* *
- which will be printed N times.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void ladder_pattern( int N)
{
for ( int i = 0; i <= N; i++) {
cout << "* *" << endl;
cout << "* *" << endl;
if (i < N) {
cout << "*****" << endl;
}
}
}
int main()
{
int N = 3;
ladder_pattern(N);
return 0;
}
|
Java
class GFG
{
static void ladder_pattern( int N)
{
for ( int i = 0 ; i <= N; i++)
{
System.out.println( "* *" );
System.out.println( "* *" );
if (i < N)
{
System.out.println( "*****" );
}
}
}
public static void main(String args[])
{
int N = 3 ;
ladder_pattern(N);
}
}
|
Python3
def ladder_pattern(N) :
for i in range (N + 1 ) :
print ( "* *" );
print ( "* *" );
if (i < N) :
print ( "*****" );
if __name__ = = "__main__" :
N = 3 ;
ladder_pattern(N);
|
C#
using System;
class GFG
{
static void ladder_pattern( int N)
{
for ( int i = 0; i <= N; i++)
{
Console.WriteLine( "* *" );
Console.WriteLine( "* *" );
if (i < N)
{
Console.WriteLine( "*****" );
}
}
}
static public void Main ()
{
int N = 3;
ladder_pattern(N);
}
}
|
Javascript
<script>
function ladder_pattern(N) {
for ( var i = 0; i <= N; i++) {
document.write( "* *" + "<br>" );
document.write( "* *" + "<br>" );
if (i < N) {
document.write( "*****" + "<br>" );
}
}
}
var N = 3;
ladder_pattern(N);
</script>
|
Output:
* *
* *
*****
* *
* *
*****
* *
* *
*****
* *
* *
Time complexity: O(N) for given input N steps
Auxiliary Space: O(1) as constant extra space is used
Share your thoughts in the comments
Please Login to comment...