Skip to main content

Pattern 6

Problem​

Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern.

Help Geek to build a pattern.

Examples:​

Example 1:

Input: 5

Output:
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

Your task:​

You don't need to input anything. Complete the function printTriangle() which takes an integer n as the input parameter and print the pattern.

Constraints:​

  • 1<=N<=201<= N <= 20

Solution​

Python​

def printTriangle(self, N):
for i in range(N, 0, -1):
for j in range(1, i + 1):
if j == 1:
print(j, end='')
else:
print(' ' + str(j), end='')
print()

Java​

void printTriangle(int n) {
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
if (j == 1) {
System.out.print(j);
} else {
System.out.print(" " + j);
}
}
System.out.println();
}
}

C++​

void printTriangle(int n) {
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
if (j == 1) {
cout << j;
} else {
cout << " " << j;
}
}
cout << endl;
}
}

C​

void printTriangle(int n) {
int i, j;
for (i = n; i >= 1; i--) {
for (j = 1; j <= i; j++) {
if (j == 1) {
printf("%d", j);
} else {
printf(" %d", j);
}
}
printf("\n");
}
}