-3

How is it possible to print the following pattern?

    *
   **
  ***
 ****
*****
****
***
**
*

How can we add the spaces during the first half of the pattern? I only managed to get the second half of the pattern right:

#include <iostream>

using namespace std;

void printpattern(int n)
{
    for (int r = 0; r <= n; r++)
    {
        for (int z = 0; z <= r; z++) {
            cout << "*";
        }

        cout << endl;
    }
}

int main()
{
    int n = 5;
    printpattern(n);
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43
Sarah_Xx
  • 123
  • 2
  • 10

3 Answers3

2

If one is afraid of using loops such thingies can of course always be solved with recursion and a little math:

#include <iostream>

void pattern(int n, int p = 0)
{   
    if (!n) return;
    if (!p) { pattern(2 * n * n - n, n); return; }
    int k = --n / p, o = n % p + 1, t = o - (p - k);
    std::cout.put(" *"[k >= p && t < p || k < p && t >= 0]);
    --o || std::cout.put('\n');
    pattern(n, p);
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43
1

Although comments suggest using std::string, I believe this was intended to be written using only loops. This works:

void printpattern(int n)
{
  // print first half.
  for (int i = 0; i < n; ++i) {
    // print spaces
    for (int r = n - i; r > 0; --r)
      std::cout << ' ';

    // print stars.
    for (int j = i; j > 0; --j) 
      std::cout << '*';

    std::cout << '\n';
  }

  /// print second half. No need to print spaces here.
  for (int i = 1; i <= n; ++i) {
    for (int r = n - i; r >= 0; --r) 
      std::cout << '*';

    std::cout << '\n';
  }
}
sstefan
  • 385
  • 4
  • 15
  • wow that is fascinating how did you analyze it? i really tried but couldn't is it because i am still a beginner or what – Sarah_Xx Nov 22 '18 at 20:17
1

It's easier to do this by composing a longer string and using a sliding view.

That's pretty straightforward in C++:

#include <iostream>
#include <string>
#include <string_view>

void printpattern(std::size_t n)
{
    const auto s = std::string(n, ' ') + std::string(n, '*') + std::string(n, ' ');
    for (std::size_t i = 1;  i < n*2;  ++i)
        std::cout << std::string_view(s.data()+i, n) << '\n';
}

int main()
{
    printpattern(5);
}

You could of course make the space padding be of length n-1 on both sides, and use a more conventional loop starting i at zero:

    const auto s = std::string(n - 1, ' ') + std::string(n, '*')
                 + std::string(n-1, ' ');
    for (std::size_t i = 0;  i < n * 2 - 1;  ++i)

It's up to you whether saving two characters of temporary string is worthwhile.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103