#include <iostream>using namespace std;int main() { int n; cin >> n; if (n < 1) { return 1; } int current_num = n * (n + 1) / 2; for (int row = 1; row <= n; row++) { int col_offset = 0; for (int col = 1; col <= row; col++) { cout << current_num - col_offset; if (col < row) { cout << " "; } else { cout << endl; } col_offset++; } current_num -= row; } return 0;}
Question
#include <iostream>using namespace std;int main() { int n; cin >> n; if (n < 1) { return 1; } int current_num = n * (n + 1) / 2; for (int row = 1; row <= n; row++) { int col_offset = 0; for (int col = 1; col <= row; col++) { cout << current_num - col_offset; if (col < row) { cout << " "; } else { cout << endl; } col_offset++; } current_num -= row; } return 0;}
Solution
This is a C++ program. It reads an integer n from the input, and if n is less than 1, it returns 1 and ends the program. If n is greater than or equal to 1, it calculates the sum of the first n natural numbers and stores it in current_num.
Then it starts a loop from 1 to n (inclusive), where each iteration represents a row. For each row, it starts another loop from 1 to the current row number (inclusive), where each iteration represents a column.
In each column of each row, it prints the value of current_num minus the column offset (which starts from 0 and increments by 1 in each column), followed by three spaces if it's not the last column, or a newline character if it is.
After each row, it subtracts the row number from current_num.
The program ends by returning 0.
Similar Questions
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.