Print the pattern 2 2 1 1 $2 1
Last Updated :
13 Mar, 2023
Given the number N, the task is to print a pattern such that in each line all the digits from N to 1 are present in decreasing order and the frequency of the elements in ith line is N-i (the lines are 0 based i.e., i varies in the range [0, N-1]).
Note: Instead of printing a new line print a “$” without quotes. After printing the total output, the end of the line is expected.
Examples:
Input: 2
Output: 2 2 1 1 $2 1 $
Input: 3
Output: 3 3 3 2 2 2 1 1 1 $3 3 2 2 1 1 $3 2 1 $
Approach: Follow the steps to solve this problem:
- Run a loop from k = 0 to N-1:
- Run a nested loop from i = N to 1:
- Run a loop from 0 to N-k and print i.
- After executing the i loop for every k, print ‘$‘.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void printPat( int n)
{
int i, j, k;
for (k = 0; k < n; k++) {
for (i = n; i > 0; i--) {
for (j = 0; j < n - k; j++) {
cout << i << " " ;
}
}
cout << '$' ;
}
}
int main()
{
int N = 2;
printPat(2);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void printPat( int n)
{
int i, j, k;
for (k = 0 ; k < n; k++) {
for (i = n; i > 0 ; i--) {
for (j = 0 ; j < n - k; j++) {
System.out.print(i + " " );
}
}
System.out.print( "$" );
}
}
public static void main(String[] args)
{
int N = 2 ;
printPat( 2 );
}
}
|
Python3
def printPat(n):
for k in range (n):
for i in range (n, 0 , - 1 ):
for j in range ( 0 ,n - k):
print (i,end = " " )
print ( "$" ,end = "")
N = 2
printPat(N)
|
C#
using System;
public class GFG{
static void printPat( int n)
{
int i, j, k;
for (k = 0; k < n; k++) {
for (i = n; i > 0; i--) {
for (j = 0; j < n - k; j++) {
Console.Write(i + " " );
}
}
Console.Write( "$" );
}
}
static public void Main (){
int N = 2;
printPat(2);
}
}
|
Javascript
function printPat(n)
{
let i = 0, j = 0, k = 0;
for (k = 0; k < n; k++) {
for (i = n; i > 0; i--) {
for (j = 0; j < n - k; j++) {
console.log(i + " " );
}
}
console.log( '$' );
}
}
let N = 2;
printPat(2);
|
Time Complexity: O(N3)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...