Nested Loop Problem. Help me to figure out.

[Step 2] Modify your program from step 1 to now query the user for a value of Θ
between 15 and 75 (you can assume they will always comply and not give you a bad
value) then print a triangle given a particular value of Θ. To solve this problem, try to
derive a mathematical expression for the length of the x-axis (i.e. # of *'s) as a function of
Θ and the y-coordinates. Then iterate through every line (y-coordinate) and calculate the
appropriate x-coordinate (round down to get an integral value using the floor()
function in math.h / cmath, if desired). The x-coordinate you compute will directly
determine how many ‘*’s are printed. Your program should prompt the user for the
value of theta they would like to use.

Can anyone help me to figure out what I'm doing wrong. When I run this code, it starts the infinite loop. I cannot understand why it is not working. I assume that Y coordinate = 30. Thanks.

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>
#include <iomanip>
#include <string>
#include <cmath>

#define PI 3.14159265

using namespace std;

int main()
{
   char star = '*';
   int rows = 30;
   int angle_theta = 0;
   int length = 1;
   int x_arg = 0;
   
   cout <<"Enter angle between 15 - 75: ";
   cin >> angle_theta;
   cout << "Entered theta " << angle_theta << endl;
   
   x_arg = tan(angle_theta * PI/180.0);
   
  for(int i = 0; i < rows; i++)
   {   
       for(int j = 0; j < length; j++)
       {
           cout << star;
       }
       cout << endl;
       length++;
       length = floor(length * x_arg); 
   }
   return 0;
}
i suggest adding this:
 
cout << "Length: " <<length<< endl;


after line 25 and seeing what's printed out. Or step through the code.
Having a nested loop that relies on a condition that's calculated outside of that loop seems a bit non-intuitive to me.
Last edited on
Topic archived. No new replies allowed.