Write a program which will ask the user to input a choice ch and the height of the triangle h and print either of the following patterns based on the user’s selection. Ch=1 h=4
output :
1
12
123
1234
Ch=2 h=5 output :
12345
1234
123
12
1
Answers
Answer:
// C++ code to demonstrate printing
// pattern of numbers
#include <iostream>
using namespace std;
// Function to demonstrate printing
// pattern
void numpat(int n)
{
// initializing starting number
int num = 1;
// Outer loop to handle number of rows
// n in this case
for (int i = 0; i < n; i++) {
// Inner loop to handle number of columns
// values changing acc. to outer loop
for (int j = 0; j <= i; j++)
cout << num << " ";
// Incrementing number at each column
num = num + 1;
// Ending line after each row
cout << endl;
}
}
// Driver Function
int main()
{
int n = 5;
numpat(n);
return 0;
}
Answer:
I have written a python program for this. I hope this is helpful for you. It works 100% as per your choice and height.
Explanation:
ch = int(input("Enter your choice for the type of triangle (1 or 2): "))
h = int(input("Enter height of the triangle"))
if ch == 1:
i = 1
while i <= h:
j = 1
while j <= i:
print(j, end=' ')
j = j+1
print()
i = i+1
else:
i = h
while i >= 1:
j = 1
while j <= i:
print(j, end=' ')
j = j+1
print()
i = i-1