tom woods tom woods - 1 year ago 97
C++ Question

Plotting points using Nested For Loops

I'm relatively new to C++ and we have been given this task to do:

Write a C++ program which asks the user for a number n between 1 and 10. The program should then print out n lines. Each should consist of a number of stars of the same number as the current line number. For example:

Please enter a number: 5


The problem I am having is that when I use the code I've written it displays wrong.

The code I have right now reads like this:


using namespace std;

int main() {

int n;
cout << "Please enter a number between 1 and 10:" << endl;
cin >> n;

for (int x = 0; x <= n; x++)
for (int y = 0; y <= n; y++) {
cout << "*" ;
cout << "*" << endl;

return 0;

Dam Dam
Answer Source

The solution is exactly as '@Lightness Races in Orbit' just explained to you. Let me add that if the requirement is just print out what you showed us, then no need for the last '*' nor the 'cin.get()':

for (int x = 0; x <= n; ++x)
    for (int y = 0; y < x; ++y) {
        cout << "*" ;
    // No need for all the rest just print 'new line'
    std::cout << "\n";

Try it live!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download