fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. using namespace std;
  4.  
  5. void printPyramid(int final);
  6.  
  7. int main() {
  8. int final;
  9.  
  10. cout << "Please enter an integer from 1 to 15: ";
  11. cin >> final;
  12.  
  13. if (cin.fail()) { // ALWAYS check for errors
  14. cerr << "Invalid input" << endl;
  15. return -1;
  16. }
  17. if (final < 1 || final > 15) {
  18. cerr << "Number must be between 1 and 15" << endl;
  19. return -1;
  20. }
  21. cout << endl; // (not really needed)
  22.  
  23. printPyramid(final);
  24. }
  25.  
  26. void printPyramid(int final) {
  27. int width = (final < 10) ? 2 : 3; // num over 10 need column size of 3
  28.  
  29. for (int row = 1; row <= final; row++) {
  30. // Print spaces.
  31. // There are final - row columns before the first number
  32. for (int col = 1; col <= final - row; col++) {
  33. cout << setw(width) << " ";
  34. }
  35.  
  36. // Prints numbers decending from row to 1
  37. for (int num = row; num > 0; num--) {
  38. cout << setw(width) << num;
  39. }
  40.  
  41. // Prints numbers ascending from 2 to row
  42. for (int num = 2; num <= row; num++) {
  43. cout << setw(width) << num;
  44. }
  45. cout << endl;
  46. }
  47. }
  48.  
Success #stdin #stdout 0s 3460KB
stdin
15
stdout
Please enter an integer from 1 to 15: 
                                            1
                                         2  1  2
                                      3  2  1  2  3
                                   4  3  2  1  2  3  4
                                5  4  3  2  1  2  3  4  5
                             6  5  4  3  2  1  2  3  4  5  6
                          7  6  5  4  3  2  1  2  3  4  5  6  7
                       8  7  6  5  4  3  2  1  2  3  4  5  6  7  8
                    9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9
                10  9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9 10
             11 10  9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9 10 11
          12 11 10  9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9 10 11 12
       13 12 11 10  9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9 10 11 12 13
    14 13 12 11 10  9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9 10 11 12 13 14
 15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15