loops and nested loops

This program outputs a downwards facing arrow composed of a rectangle and a right triangle. The arrow dimensions are defined by user specified arrow base height, arrow base width, and arrow head width. This is what I have but turns out nothing like it is suppose to.

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
33
34
35
#include <iostream>
using namespace std;

int main() {
   int arrowBaseHeight = 0;
   int arrowBaseWidth  = 0;
   int arrowHeadWidth  = 0;
   int i = 0;
   int h = 0;
   int w = 0;
   int a = 0;
   
   cout << "Enter arrow base height: " << endl;
   cin >> arrowBaseHeight;
   
   cout << "Enter arrow base width: " << endl;
   cin >> arrowBaseWidth;
   
   cout << "Enter arrow head width: " << endl;
   cin >> arrowHeadWidth;
   
   // Draw arrow base (height = 3, width = 2)
   for (h = 0; h < arrowBaseHeight; ++h) {
      for ( w = 0; w < arrowBaseWidth; w++) {
         cout << "*";
      }
   }
   for ( a = arrowHeadWidth; a > 0; --a) {
      for (i = 0; i < a; ++i) {
         cout << "*";
      }
      cout << endl;
   }
   return 0;
}
closed account (iGLbpfjN)
The logic of your code: you enter 5 as height and 5 as width.
h = 0 and w = 0 to 5 --> print 5 "*".
As you didn't jump a line...
h = 1 and w = 0 to 5 --> print 5 "*" in the same line of the 5 "*" before.
So, to correct it you need to jump a line after each "w" cycle.

1
2
3
4
5
6
for (h = 0; h < arrowBaseHeight; ++h) {
      for ( w = 0; w < arrowBaseWidth; w++) {
         cout << "*";
      }
cout << endl;
   }

Last edited on
1
2
3
4
for (h = 0; h < arrowBaseHeight; ++h) {
      for ( w = 0; w < arrowBaseWidth; w++) {
         cout << "*";
      }

After your arrowBaseWidth is done you go straight to the arrorBaseHeight. If you declare
1
2
arrowBaseHeight = 3; 
arrowBaseWidth = 3;
the output would be ***|***|*** // The | is the separation of the loop You need to find a way to make the * go to the next line.
Topic archived. No new replies allowed.