for loops

Using 2 for loops, one inside the other, and a cout that only prints 1 asterisk, print a hill shaped triangle like this:
Input a Number: 5
*
**
***
****
*****

I have no idea how to set this kind of code up.
There are 3 followups asking to print the above upside down,
another to print the following:
Input a Number: 5
*
***
*****
and the upside down of that^^
Please read the loops section of: http://www.cplusplus.com/doc/tutorial/control/
And also, read the "standard input" section of: http://www.cplusplus.com/doc/tutorial/basic_io/
You use "cin" to get the user input, and store it in a variable.

Do you know how to write one for loop, that counts from 1 to N? Show us that first.
Last edited on
int loop1;

for ( loop1 = 1; loop1 <= 10; loop1++ )
{
cout << loop1 << " ";
}
cout << endl;
this would print:
1 2 3 4 5 6 7 8 9 10

this was an earlier part which it asked to only print up until 10 in which i could set a variable if i wanted to go to a user inputted number

my biggest confusion right now is how and why i need 2 for loops and not 1
Last edited on

Imagine printing out the following:
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10

Let's do that with a slight modification of the code you showed in your latest post:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Example program
#include <iostream>

int main()
{
    using std::cout;

    for ( int loop1 = 1; loop1 <= 8; loop1++ )
    {
        cout << loop1 << " ";
    }
    cout << '\n';

    for ( int loop1 = 1; loop1 <= 9; loop1++ )
    {
        cout << loop1 << " ";
    }
    cout << '\n';
    
    for ( int loop1 = 1; loop1 <= 10; loop1++ )
    {
        cout << loop1 << " ";
    }
    cout << '\n';
}

This is understandable, so far, right?

But you can already see that there's a lot of repetition here. You're essentially doing the same thing 3 times, but with one number changing. This is where the second layer of for loops come in, instead of hardcoding those three different numbers, make that number change in its own for loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Example program
#include <iostream>

int main()
{
    using std::cout;

    // outer loop:
    for ( int i = 8; i <= 10; i++)
    {
        // original, inner loop:
        for ( int j = 1; j <= i; j++ )
        {
            cout << j << " ";
        }
        cout << '\n';
    }
}
Last edited on
Okay thanks I see how it works
Does my case require 2 or 3 variables? cause i've been trying to get it to work but i feel like i need 3 variables
Your original problem requires the two variables, one for each for loop. If adding in more variables helps you understand the logic happening, you can always add in more!

Edit: Typo
Last edited on
Topic archived. No new replies allowed.