I was posted with this problem by my programming teacher:
We are to preset 3 arrays, each having 3 elements (9 total elements) and are to calculate the distance from center to corner of the prisms that are formed by these arrays (one array for length, one for width, one for height). We were given this after learning about for loops, so the project was to consider all combinations of these numbers within the arrays.
Here is the code I came up with:
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <iostream>
#include <math.h>
using namespace std;
//preset arrays
int a[3] = {2,5,7}; //lengths
int b[3] = {20,100,180}; //widths
int c[3] = {1,2,3}; //heights
//loop variables
int counta = 0, countb = 0, countc = 0;
int test1 = 0, test2 = 0, test3 = 0;
//calculation variables
double diagonal_prism = 0;
double distance_c2c = 0;
double d = 0, e = 0, f = 0;
int main()
{
//display the preset values
for (; counta < 3; counta++)
cout<<"preset value a["<<counta<<"] = "<<a[counta]<<"\n";
cout<<"\n";
for (; countb < 3; countb++)
cout<<"preset value b["<<countb<<"] = "<<b[countb]<<"\n";
cout<<"\n";
for (; countc < 3; countc++)
cout<<"preset value c["<<countc<<"] = "<<c[countc]<<"\n";
//the for loops for the matchings
for (; test1 < 3; test1++)
{
test2 = 0;
for (; test2 < 3; test2++)
{
test3 = 0;
for (; test3 < 3; test3++)
{
d = a[test1];
e = b[test2];
f = c[test3];
diagonal_prism = sqrt(pow(d, 2) + pow(e, 2) + pow(f, 2));
distance_c2c = diagonal_prism / 2;
cout<<d<<"\t"<<e<<"\t"<<f<<"\t"<<distance_c2c<<"\n";
}
}
}
cin.ignore()
cin.get();
return 0;
}
|
this code will do the calculations and display the 27 possibilities
Two questions I have:
1) Is this the most efficient way to write this code? Or is there another way thats more condense?
2) How would I go about creating an array with a length defined by user input? Say for example I wanted to make this program completely user defined and let them input each of the side lengths for as many prisms as they wanted to calculate, how would I go about establishing these arrays and filling them?
The code I had in mind for my example starts like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
using namespace std;
int index;
int main()
{
cout<<"how many prisms would you like to calculate? ";
cin>>index;
int a[index];
cin.ignore();
cin.get();
return 0;
}
|
This gives me 3 errors at the line where the variable is declared:
1 error C2057: expected constant expression
2 error C2466: cannot allocate an array of constant size 0
3 error C2133: 'a' : unknown size
Any help on this matter would be greatly appreciated.