Search code examples
c++loopsshapesnested-for-loop

I need help to writing a program that prints out shape that takes number of rows from user


The shape should look like this: shape

For example, this figure has 10 lines. And the shape should continue with this pattern.

Here is my code so far:

#include <iostream>
using namespace std;
int main()
{
    int rows, a, b, c, d;
    cout << "Enter the number of the rows: ";
    cin >> rows;
    for (a = 1; a <= rows; a++) {
        for (b = 1; b <= a; b = a + 4) {
            cout << "   ******" << endl;
        }
        for (c = 2; c <= rows; c += 2) {
            cout << " **********" << endl;
        }
        for (d = 3; d <= rows; d += 4) {
            cout << "************" << endl;
        }
    }
    return 0;
}

I'm having trouble getting it back in order. For example, when I enter the value 5, each row repeats 5 times, but I want the number of rows to be 5.


Solution

  • Here is a solution:

    #include <iostream>
    #include <iomanip>
    
    
    int main( )
    {
        std::cout << "Enter the number of the rows: ";
        std::size_t rowCount { };
        std::cin >> rowCount;
    
        constexpr std::size_t initialAsteriskCount { 6 };
        std::size_t asteriskCount { initialAsteriskCount };
        bool isIncreasing { };
        int fieldWidth { initialAsteriskCount + 3 };
    
        for ( std::size_t row = 0; row < rowCount; ++row )
        {
            std::cout << std::right << std::setw( fieldWidth ) << std::setfill(' ')
                      << std::string( asteriskCount, '*' ) << '\n';
    
            switch ( asteriskCount )
            {
                break; case 6:
                    isIncreasing = true;
                    asteriskCount += 4;
                    fieldWidth = 11;
                break; case 10:
                    asteriskCount += ( isIncreasing ) ? 2 : -4;
                    fieldWidth = ( isIncreasing ) ? 12 : 9;
                break; case 12:
                    isIncreasing = false;
                    asteriskCount -= 2;
                    fieldWidth = 11;
            }
        }
    
        return 0;
    }
    

    This can probably be simplified a bit more. But it's working properly.

    Also, note that the syntax of the switch statement might seem a bit strange at first sight. But it's the new and safer way of writing a switch block and recommended by experts.