Buster023
Buster023

Reputation: 9

Nested For Loops and outputting asterisks

i have to write a c++ program that asks the user to enter an integer k and then outputs k lines of asterisks with the first line starting at 1 asterisk and the last line finishing with k asterisks.

i can get the program to output a square of asterisks such as: (k=5)

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

when it should look like this:

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

how should i adjust my program to accomplish this? (Note: i have to use two for loops.)

int main() {
    int k, cols, rows;
    cout << " Please enter a number: ";
    cin >> k;

    for (cols = 1; cols < k + 1; cols++) {
        for (rows = 1; rows < k + 1; rows++)
            cout << "*";
        cout << endl;
    }

    getchar();
    getchar();
    return 0;
}

Upvotes: 0

Views: 1914

Answers (1)

David G
David G

Reputation: 96845

The inner loop should run col+1 times. So you need change the condition in the inner loop to rows < cols and have rows be one less than cols by changing its starting value to 0:

for (cols = 1; cols < k+1; cols++) {
    for (rows = 0; rows < cols; rows++)
        cout << "*";
    cout << endl;
}

Upvotes: 1

Related Questions