Nested For Loop
Apr 5, 2016 at 10:30am UTC
Ok so, my teacher want us to use 2 nested loops to output this
*
**
***
**
*
I gave it a try, and got this output. However, he didn't like the way I did it with since I used alot of cout's and if's.
And here's the code he wants us to follow
1 2 3 4 5 6 7 8
for ( ; ; )
{
for ( ; ; )
{
cout << "*" ;
}
cout << endl;
}
I'm not sure if I can use if or not, but not using it would be great.
Thanks in advance
Apr 5, 2016 at 10:55am UTC
The inner loop should print content of one row. How many stars? That has to be calculated from the row number.
The outer loop calls the inner loop once for each row and supplies the row number to the inner loop.
Apr 5, 2016 at 11:43am UTC
Here's a trick for the outer loop to compute the number of stars that you need to print:
1 2 3 4 5 6
#include <cstdlib>
...
for (x = -2; x <= 2; ++x) {
int n = 3 - abs(x);
// for loop to print n stars
}
Apr 5, 2016 at 2:52pm UTC
It works just fine dhayden, thanks. But I'm pretty sure he is not gonna like it because of the abs thing, since we haven't learnt it yet.
Apr 5, 2016 at 3:26pm UTC
Then do your own:
1 2 3
int n;
if (x < 0) n = 3+x;
else n = 3 - x;
Last edited on Apr 5, 2016 at 3:27pm UTC
Topic archived. No new replies allowed.