Search code examples
c++algorithmconsole

Load n-number of stars from user (pieces to display - not rows)


I have following problem in C++: Basiclly this code:

#include<iostream>   

using namespace std; 

int main() { 

int n=5;

for(int rows = 1; rows <= n; rows++){

for(int col = rows; col <= n; col++){

   cout << "*";

     }

cout << endl;

}

  return 0; 

}

Shows this output:

*****

****

***

**

*

When I added to the code input from user it doesn't work this is the code with input:



#include<iostream>   

using namespace std; 

int main() { 


while(n>0){

int n;

cin >> n;

for(int rows = 1; rows <= n; rows++){

for(int col = rows; col <= n; col++){

   cout << "*";

    n--;

     }

cout << endl;

   }

}        

  return 0; 

}

What am I doing wrong? I want get such a result for input n = 6:

***
**
*

for 5:

***
**

for 15:

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

As you can see patterns basing on the numbers of stars not the num of rows.


Solution

  • That's the problem, my task is not to about how many rows I need but to print stars till they re gone

    The problem is that you think your task is not about how many rows to print, but it is. How else are you going to print some number of rows, when you do not know how many rows to print?

    Rather than doing it all at once and starting with a loop to print the stars, you should first determine what to print. The total number of stars in this kind of pattern is

     #stars( #rows ) = ( #rows - 1) * #rows
    

    For example, in 3 rows you have 3*2 = 6 stars. This is a quadratic equation that for given #stars you can solve for #rows. Alternatively, we know that adding a n-th row adds n more stars:

    int num_stars_to_print;
    std::cin >> num_stars_to_print;
    
    int rows_to_print = 1;
    int total_stars = 1;
    while ( total_stars < num_stars_to_print ) {
          rows_to_print += 1; 
          total_stars  += rows_to_print;
    }
    

    After this loop you know how many rows you have to print: rows_to_print. The number of stars in this first row is rows_to_print. I'll leave it for you to actually print the stars.