For Loop With Specific Inputs

I need to write a program that uses nested for loops to find the range for trajectory for initial velocities of 0, 1, 10, 100, and 1000. I can write a program that allows me to input whatever values I want, but I need it to compile and generate tables for ONLY these five values. How do I set up the loops to read only for these inputs and not prompt for them

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
#include <iostream>
#include <cmath>

using namespace std;

int main()
{

  int a;
                             
  const double g=-9.81;
  double pi=3.14159265358979323846;

cin>>a;
        for (int i=5; i<=85; i=i+5)
    {
      double radians=i*(pi/180);
      for (int j=0; j<=0; j++)
        {
          double range=(-2*(a*a)/g)*cos(radians)*sin(radians);
          cout<<i<<" "<<range<<endl;

  for (int i=5; i<=85; i=i+5)
    {
      double radians=i*(pi/180);
      for (int j=0; j<=0; j++)
        {
          double range=(-2*(a*a)/g)*cos(radians)*sin(radians);
          cout<<i<<" "<<range<<endl;
        }
    }
  return 0;
}
A couple of thoughts:

- You could move your calculations into a function and call the function 5 times. Once with each value.

- Except for 0, those values are the first 4 powers of 10. Create a for loop from 1 to 4 and calculate the appropriate power of 10.

p.s. Your program doesn't compile. You have unbalanced braces.

Lines 23-31: Appear to be redundant..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cmath>
using namespace std;

const double g=-9.81;
const double pi=3.14159265358979323846;
    
void compute_range (int a)
{   for (int i=5; i<=85; i=i+5)
    {   double radians=i*(pi/180);
        for (int j=0; j<=0; j++)
        {   double range=(-2*(a*a)/g)*cos(radians)*sin(radians);
            cout<<i<<" "<<range<<endl;
        }
    }      
}
    
int main()
{   compute_range (0);     
    for (int n=1; n<5; n++)
        compute_range ((int)pow((double)10,n));    
    system ("pause");    
    return 0;
}
Last edited on
Edit: I didn't see AbstractionAnon's post :+)

Hi,

You could have a std::vector with those numbers in it, then loop through that vector - it is just like an array.

std::vector<double> velocities = {0.0, 1.0, 10.0, 100.0, 1000.0};

velocities[0] is the first one, velocities[4] is the last. Although a velocity of zero seems pointless.

It looks like you a problem with your inner for loops, they only run once - what is the point of that?

Don't declare a variable inside a loop (radians), just calculate it once outside the loop. Declare the range variable before the loop.

I would recommend having a function to calculate the range.

The variable pi should also be const.

delete lines 15 to 21 they are missing braces and are almost a duplicate of lines 23 to 31

Good Luck !!
Last edited on
Topic archived. No new replies allowed.