-1

I want a pattern in which for n=4 in 1st row it has 4 stars and in 2nd row I has 1 space & 3 stars and in 3rd row, it has 2 spaces and 2 stars and so on.

****
 ***
  **
   *

The code, I tried to solve this.

#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;
    cout << endl;

    int i = 1;
    while (i <= n)
    {
        //Printing Spaces

        int space = i - 1;
        while (space)
        {
            cout << " ";
            space++;
        }

        //Printing Stars

        int j = 1;
        while (j <= n)
        {
            cout << "*";
            j++;
        }
        cout << endl;
        i++;
    }

    return 0;
}

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • `int space = i - 1; while (space) { cout << " "; space++; }` If space starts out as a positive number and you add 1 to space inside the loop, when will `while (space)` ever be false? (especially since rolling over a signed integer is undefined behaviour: https://stackoverflow.com/questions/16188263/is-signed-integer-overflow-still-undefined-behavior-in-c) – Jerry Jeremiah Nov 25 '21 at 20:39

2 Answers2

0

In your while (space) loop you aren't comparing space to anything, so it assumes that the expression is always true.

Here's a simplified way to do it:

#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;
    cout << endl;

    int i = 1;
    while (i <= n)
    {
        // print i-1 spaces
        for (int j = i-1; j >= 1; j--)
        {
            cout << " ";
        }
        // print n-i+1 stars
        for (int j = n; j >= i; j--){
            cout << "*";
        }
        cout << endl;
        i++;
    }

    return 0;
}
Joseph Balnt
  • 130
  • 9
0
#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;
    cout << endl;

    int i = 1;
    while (i <= n)
    {

        int space = i - 1;  
        while (space>=1)  // change 1.1
        {
            cout << " ";
            space--;      // change 1.2
        }

        int j = i;        // change2
        while (j <= n)
        {
            cout << "*";
            j++;
        }
        cout << endl;
        i++;
    }

    return 0;
}

I made only 2 changes in your code so it can work. 1st one

while (space>=1)

what you are doing is you are trying to add space in output so you add space variable in while() loop but that's not going to work because you have to decide first how many spaces you have to print according to that you have to put condition in while() loop. To achieve this space--; added .

For ex. line 4 i=4; space want 3, so space=3; while(space>=1); space--; so while loop runs 3 time and print 3 gaps/spaces.

2nd one

int j = i;

while (j <= n)

if you put j=1; then your gaps print properly but all stars print 4 times as loop runs 4 times always. Due to this condition for i=1; But if you make j=i; loop runs 4 times for 1st line, 3 times for 2nd line,.....

Abhishek Mane
  • 619
  • 7
  • 20