Hourglass from asterisks

I got totally confused with the nestled for statements.
I am trying to write a program which prints a hourglass from asterisks:
First line: 7 asterisks, next line: 5, then 3, then 1, next 3, next 5 and 7.
Please could someone explain what I am doing wrong. I know there is a big confusion but I don't wanna give up.



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
26
  #include <iostream>
using namespace std;

int main(){


for(int row=1; row <=7; row+=2){
  for(int space=1; space<row; space++){
    cout << " ";
  } 
    for(int star=7; star>=row; star--){
      cout<<"*";
    }
    cout<<endl;
}

for(int brow=3; brow<=7; brow+=2){
  for(int bspace=3; bspace>=brow; bspace--){
    cout<< " ";
  }
    for(int bstar=3; bstar<=brow; bstar++){
        cout << "*";
    }
    cout << endl;
}
}
You're simply getting your logic wrong. On each line, you need to output some spaces, then some stars, then the same number of spaces again.

How about something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
for outputLine 0 to 3
{
  output  outPutLine spaces
  output  7 - ( 2 * outPutLine) stars
  output  outPutLine spaces
}

for outputLine 4 to 6
{
  output (6 - outputLine) spaces
  output (2 * outputLine - 5) stars
  output (6 - outputLine) spaces
}


Each of those "output" lines is itself a little for loop, or even better, a function call that contains a little for loop. You should start by writing that simple output function so that you can then easily experiement with the logic of your code.
Last edited on
Thank you, it helped a lot;

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
26
27
28
29
30
31
32
 #include <iostream>
using namespace std;

int main(){


for(int row=0; row <=3; row++){
  for(int space=1; space<=row; space++){
      cout << " ";
   }
     for(int star=1; star<= 7-(2*row); star++){
     cout << "*";
     }
     for(int space2=1; space2<row; space2++){
         cout << " ";
     }
     cout << endl;
}
for(int rowb=4; rowb<=6; rowb++){
    for(int spaceb=1; spaceb<=6-rowb; spaceb++){
      cout<< " ";
    }
    for(int starb=1; starb<=2*rowb-5; starb++){
        cout << "*";
    }
    for(int spaceb2=1; spaceb2<=6-rowb; spaceb2++){
        cout << " ";
    }
    cout<< endl;
}
}
  
Topic archived. No new replies allowed.