Hello ayanokoji,
Thank you for fixing your OP, (Original Post), That helps.
I would say that if you are writing the code to benefit the compiler then there is to much white space in your code. If you want someone to read and understand you code then you need some blank lines.
It took me a little while, but I came up with this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
int main()
{
int numOfRows{};
int firstNumber{}; // <--- Why is this a "char" when the name suggests an "int"?
std::cout << "Number of rows?: "; // <--- Comment these 2 lines and uncomment for a complete triangle.
std::cin >> numOfRows;
std::cout << "First number (< 10): ";
std::cin >> firstNumber;
//numOfRows = firstNumber;
for (int row = 0; row < numOfRows; row++) // <--- Better to define the itterators' type in the for loop. This keeps it local to the for loop.
{
for (int colSpace = row; colSpace; colSpace--, std::cout << ' ')
{
std::cout << " ";
}
for (int colNum = firstNumber; colNum > row; colNum--)
{
std::cout << colNum << ' ';
}
std::cout << '\n';
}
// <--- Keeps console window open when running in debug mode on Visual Studio. Or a good way to pause the program.
// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.
std::cout << "\n\n Press Enter to continue: ";
std::cin.get();
return 0; // <--- Not required, but makes a good break point.
}
|
I want you to notice how the blank lines and a good variable make the code easier to read and follow.
With a variable like like "numOfRows". You do not have to use it. It is just an idea of what could be done. "numRows" would work just as well. And do not be afraid to use long variable names. The point is to use something that makes it easy to understand.
When I run the above program I get this:
Number of rows?: 5
First number (< 10): 8
8 7 6 5 4 3 2 1
8 7 6 5 4 3 2
8 7 6 5 4 3
8 7 6 5 4
8 7 6 5
Press Enter to continue:
|
Line 2, the end part, may appear strange to you and I will admit that for now I do not understand how it works, but it does. I think it is because that the "cout" is done after the "colSpace--", so it starts the next line with a space B4 anything else is added to the next line.
I also that when "numOfRows" is less than "firstNumber" you get the above output. When I comment lines comment out lines 11 and 2 and uncomment line 17 It does make a proper triangle.
In you example output you are limiting the number of columns to be the same as the number of rows. It will take a little work, but you can achieve what you want.
Andy
P.S., Excuse the header files. They are just something I consider as standard for a program and since you did not originally provide them I used what I had. Just forgot to delete what was not needed.