so i want output like this
1
123
12345
123
1
i already make the program but it only output these, and im confused how to output the bottom triangle
1
123
12345
here's my program
#include <iostream>
using namespace std;
int main() {
int n = 3 ;
int i, j, k;
for (i = 1; i <= n; i ) {
for (j = n; j > i; j--) {
cout << " ";
}
for (k = 1; k <= (2 * i - 1); k ) {
cout << k;
}
cout <<endl;
}
return 0;
}
CodePudding user response:
@Mojtaba's answer is a perffect extension to your approach.
However, I wanted to provide another method that is generally used in creating such strings that are formatted in a particular manner. It is common to create the entire pattern line by line and then print to the console all at once.
I have appropriately commented the code for your reference and it should be easy to understand:
#include <iostream>
#include <vector>
void pattern(int n) {
std::vector<std::string> lines; // store the first n lines to print later
int length = 2*n - 1; // length of each line
for(int i = 0; i < n; i ) {
std::string str = std::string(length, ' ');
for(int j = 1; j <= 2*i 1; j ) {
str[n - i j - 2] = j '0';
// indexing can be figured by observing the pattern
}
lines.emplace_back(str);
}
for(int i = 0; i < n; i ) {
std::cout << lines[i] << std::endl;
}
for(int i = n-2; i >= 0; i--) {
std::cout << lines[i] << std::endl;
}
return;
}
int main() {
int n;
std::cin >> n;
pattern(n);
}
CodePudding user response:
I added another for loop exactly like yours with different order from n-1. I modified your code to this:
int main() {
int n = 3 ;
int i, j, k;
for (i = 1; i <= n; i ) {
for (j = n; j > i; j--) {
cout << " ";
}
for (k = 1; k <= (2 * i - 1); k ) {
cout << k;
}
cout <<endl;
}
for (i = n - 1; i >= 1; i--) {
for (j = n; j > i; j--) {
cout << " ";
}
for (k = 1; k <= (2 * i - 1); k ) {
cout << k;
}
cout <<endl;
}
return 0;
}
Now it returns:
1
123
12345
123
1