Home > Enterprise >  How to display this pyramid of numbers?
How to display this pyramid of numbers?

Time:11-13

I have this task: A user inputs a number N and you have to output this pyramid:

    0
   101
  21012
 .......
N.21012.N
For N=5 it will be :
     0
    101
   21012
  3210123
 432101234
54321012345

I managed to only get it working for N<10 with this code:

int n;
cin >> n;
for (int i = 0; i < n   1; i  ) {
    for (int j = 0; j < n - i; j  )
        cout << " ";
    int dir = -1;
    for (int k = i; k <= i; k  = dir) {
        cout << k;
        if (k == 0)
            dir = 1;
    }
    cout << endl;
}

For N=10 it will look like this :

           0
          101
         21012
        3210123
       432101234
      54321012345
     6543210123456
    765432101234567
   87654321012345678
  9876543210123456789
10987654321012345678910

CodePudding user response:

int padding(int n) {
    constexpr auto singleDigitNumbersCount = 9;
    constexpr auto doubleDigitNumbersCount = 90; // from 10 to 99
    if (n < 10) return n;
    if (n < 100) return 2*n - singleDigitNumbersCount;
    return 3*n - doubleDigitNumbersCount - 2*singleDigitNumbersCount;
}

int main() {
    int n;
    cin >> n;

    for (int i = 0; i < n   1; i  ) {
        std::cout << std::string(padding(n) - padding(i), ' ');
        for (int k = i; k >= 0; k--) {
            cout << k;
        }
        for (int k = 1; k <= i; k  ) {
            cout << k;
        }
        cout << '\n';
    }

    return 0;
}

https://godbolt.org/z/EEaeWEvf4

CodePudding user response:

After the answers I settled on this :

#include <iostream>
#include <cmath>
#include <string>
using namespace std;

int main()
{
  int n, spaces;
  string number;
  cin >> n;
  if (n < 10)
    spaces = n;
  else
  {
    spaces = 9;
    int pwr = 0, k = n;
    while (k > 9)
    {
      pwr  ;
      k /= 10;
    }
    for (int i = 1; i < pwr; i  )
    {
      spaces  = pow(10, i) * 9 * (i   1);
    }
    spaces  = (n - pow(10, pwr)   1) * (pwr   1);
  }
  // cout << spaces << endl;
  for (int i = 0; i < n   1; i  )
  {
    for (int j = i; j > -1; j--)
      number  = to_string(j);
    int len = number.length() - 1;
    for (int j = 0; j < spaces - len; j  )
      cout << " ";
    for (int j = 1; j <= i; j  )
      number  = to_string(j);
    cout << number << endl;
    number.clear();
  }
  cout << endl;
  return 0;
}

CodePudding user response:

I made this a bit ago Compiler Explorer Not sure if that'd help

  •  Tags:  
  • c
  • Related