Passing an array by reference

I have a program that is supposed to calculate a person's weight on a new planet and the time it takes to get to the planet. The problem is that I want to try to use an array just for practice. The guidelines ask to have a user enter their name, weight, and travel speed, then I am supposed to use a switch statement to assign the planet data (gravity and distance from earth) for whichever planet they pick, then I am supposed to use a function to calculate the data. Since a function can not return more than one value, and I have to return two, I decided to use an array to carry the input data and constant planet data, I would then process the data in the array in the function by reference, and then display the new array values as the solution.

It is really getting confusing! The logic of what I want to do is so simple, but getting the code to do it is really getting to me. Also, I should not have to include any files outside of <iomanip> <string> or <iostream> to do this. Please help me out. I am not totally against doing this without an array, but we've been given very little opportunity to work with arrays and functions because this is an online class. Also, I know that a function called "data" to store all this stuff, carry it to calculation, and then return new values in it isn't the best way to do this, but I really need to get some array experience in conjunction with function experience. 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// This program calculates a person's travel time
// to a planet, and weight on that planet when given
// travel speed from Earth, and weight on Earth

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;
void calculate(double a[]);

int main()

 {
		
// Place holders for input data
char name[30];
string planetName; 
      int planet = 0;
double data[6];

// Planet menu choices
const int  mercury = 1, venus = 2, earth = 3,
           mars = 4, jupiter = 5, saturn = 6,
           uranus = 7, neptune = 8;

// Get input from user

cout << "Enter your name: ";
cin.getline (name,30);
cout << "\n";
cout << "Well, hello there, " << name << "! \n"
     << "\n"
     << "Please enter your weight, in pounds, and \n"
	 << "then press enter: ";
cin >> data[2];
cout << "\n";

// Check for positive weight value

   if(data[2] < 0)
	    {
		cout << "That is not a valid entry. Please rerun the \n"
		     << "program and enter only positive values. ";
		cout << endl;
        }
		
// Get speed of user's spacecraft
		
cout << "Enter the speed, in mph, at which your spacecraft will be \n"
     << "traveling from Earth to the destination planet: ";
 cin >> data[3];
cout <<	"\n";

// Check for positive speed

	if(data[3] < 0)
		{
		cout << "That is not a valid entry. Please rerun the \n"
		     << "program and enter only positive values. ";
		cout << endl;
        }
		
// List planet menu for user to make selection		
				
cout << "\tPlanets you may visit from Earth\n\n"
	 << " 1. Mercury \n"
	 << " 2. Venus \n"
	 << " 3. Earth \n"
	 << " 4. Mars \n"
	 << " 5. Jupiter \n"
	 << " 6. Saturn \n"
	 << " 7. Uranus \n"
	 << " 8. Neptune \n"
	 << "\n"
	 << "Please select the planet from the above list \n"
     << "that you will be traveling to. Enter a number, \n"
     << "and press enter: ";
 cin >> planet;
cout << "\n";

// Check for number within range of list

	if(planet > 8 || planet < 0)
		{
		cout << "Invalid entry! Please rerun the program, and \n"
		     << "enter a number 1-8 from the list to select a \n"
			 << " destination planet: ";
		cout << endl;
		}
	
// Display User's planet selection and prompt for distance
	    
switch(planet)
	{
	case mercury:
		planetName = "Mercury";
		data[0]= 57000000;
		data[1]=.27;	
			 break;
	case venus:
		planetName = "Venus";
		data[0]= 26000000;
		data[1]=.086;	
			break;
	case earth:
		planetName = "Earth";
		data[0]= 0;
		data[1]=1;		 
			 break;
    case mars:
		planetName = "Mars";
		data[0]= 48000000;
		data[1]=.37;	 
			 break;
	case jupiter:
		planetName = "Jupiter";
		data[0]= 390000000;
		data[1]=2.64;		
			 break;
	case saturn:
		planetName = "Saturn";
		data[0]= 793000000;
		data[1]=1.17;	
			 break;
    case uranus:
		planetName = "Uranus";
		data[0]= 1689000000;
		data[1]=.092;	
			 break;
	case neptune:
		planetName = "Neptune";
		data[0]= 2700000000;
		data[1]=1.44;		
			 break;
}

//Begin output

cout << setprecision(2) << fixed;
	
cout << "\tProgram Output\n\n"
	 << "Name: " << name << endl
	 << "Weight on Earth: " << data[2] << "lbs \n"
	 << "Planet Destination: " << planetName;
	 
void calculate(double data[]);	 

//Output weight on new planet
 cout << "\nWeight on Planet: "
      << data[2] << " lbs"
	  << "\nTravel Time: ";
	  
//Format output of travel time for hours, days, or years
if ((data[3] / 24) < 1)
	{
		cout << data[3] << " hours";
	}	  
else if ((data[3] / 8760) < 1)
	{
		(data[3] /= 24);
		cout << data[3] << " days";
	}
else if((data[3] / 8760) > 1)	
	{
		(data[3] /= 8760);
		cout << data[3]<< " years";
	}		
	
return 0;         
    
}
		
		// Here is where I am confused about what to do

void calculate(data[])
      {
	   data[4] = (data[0]/data[3]); 
      data[5] = (data[1]*data[2]);
}		
		


	
			
			
			
			
				
You can see I already got confused about my array in lines 149-170 I had previously wanted to overwrite my old array data when it was referenced in the function, then I decided to do that in a couple of blank array positions just to be safe. In those lines data [2] and data[3] should be data[4] and data[5].

One of a hundred mistakes.
Are you allowed to use classes and enums?
Every time I have used anything from further in the book than we are, it has ultimately works against me, doesn't hurt, but I keep getting comments back like you could have done this without using this this or that. In other words, simple as dirt is what I am going for. I just wanted to try passing an array to a function so I get some practice before the final. Here is what it has to do:

Ask user name, store in variable
Ask user weight, store
Data is checked, if negative prompt user to rerun program*
Ask user speed of travel, check*
Display list of planets for switch
User picks planet or quits program
Check for value from list, prompt to rerun for bad input
Run switch
Switch has planet gravity and distance from earth and assigns a planet name to a string variable

Call function to multiply earth weight times new planet gravity and to divide distance by speed of travel

Display results:

User name
User destination
Weight on earth
Weight on new planet
Travel time

So, if what I want to do is not the o oh way I can do all of this, but still definitely use a function for the calculations, and if possible use an array wherever I can. I actually already have a functioning program without either, which is why I think the teacher wants the function, to see me use it.
I see. Alright, I'll try to slap together an example using an array in just a bit. As much as I'd like to, I'll refrain from using classes, enums and loops, since you're not using any.

I'll edit this post when I'm back.

*edit* I don't think what you're trying to do is a good way of using arrays, because you're storing arbitrary things that don't really have anything to with one another. Since you've already written a functioning program without arrays, I would just submit that.
Again, I think that, in this particular program, storing user input in an array to be processed in a function is a bad idea.
Last edited on
I'm sorry, I really wasn't clear. The project was divided into midterm and final project, and I felt like the instructions were ambiguous so I ended up writing two functioning programs that used loops, while statements, and a switch.

One had the user input all the data, and then the other had it stored as constant variables.

The midterm part of the assignment was only to do half the work, but I wasn't sure to what extent, so I pretty much finished the thing. Now I have two finished programs, and the teacher wants a function and data checking that asks the user to rerun the program, so if statements instead of while loops, and the function to run calculations for any planet selected.

With your input, I suspect that I should probably just keep the part of my old program that had the user input their name, weight, and speed, and then in the menu switch for their destination choice, run a calculator function in each switch that processes the data for that planet, it would return nothing, just process data?

Then do my program output as previously described. My biggest problem with this is getting into my switch, and then handling the constant data with a function. Should I declare the planet gravities and distances globally for all planets or within the function inside of each switch choice? Either way, is it necessary to have an array at all? My understanding of functions is severely limiting what was a simple problem the first two times I wrote the program.
O.K. Just to recap then, your requirements are the following:

- Write a function which calculates the user's weight and travel speed
- Whenever bad input is supplied, ask the user to re-run the program.

Is this correct? I wonder if you could do any of the following for bad input:

1.) Ask the user to quit and start over (re-run)
2.) Simply state that any bad input will terminate the program (warning)
3.) Use a loop, which only exits when the user gives valid input

I'd say choice number three is the most natural.

Here's how I would do it, without classes:

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <iostream>
#include <string>

/*

Storing arbitrary data - things that don't have much to do with one another - in an array, is somewhat strange, and it encourages bad design choices.
Typically, in your case, you would write a class to contain the data, and then pass an instance of that class to a function for modification.
But, here's my example, with an array.

Things I did differently:

You chose to store the user input in an array, while I chose to store constant planetary properties, such as gravitational acceleration, names and distances.
However, this design choice makes a switch control structure useless.


*/

void printTravelTime(unsigned short speed, unsigned long int distance);
double calculateWeight(unsigned short initialWeight, double modifier);

int main() {

	std::string name = "";
	unsigned short weight = 0;
	unsigned short speed = 0;
	unsigned short selection = 0;

	const unsigned short num_planets = 8;

	std::cout << "Enter your name:\t";
	std::getline(std::cin, name);

	std::cout << "Enter your weight (lbs): ";
	while (true) {
		std::cin >> weight;
		if (weight > 0) {
			break;
		}
		std::cout << "Invalid input, try again:\t";
	}

	std::cout << "Enter your speed(MPH):\t";
	while (true) {
		std::cin >> speed;
		if (speed > 0) {
			break;
		}
		std::cout << "Invalid input, try again:\t";
	}

	system("cls");

	std::cout << "Here is a list of the planets you can visit." << std::endl;

	std::cout << "(1)Mercury\n(2)Venus\n(3)Earth\n(4)Mars\n(5)Jupiter\n(6)Saturn\n(7)Uranus\n(8)Neptune" << std::endl;

	std::cout << "Enter the corresponding number of the planet you'd like to visit:\t";
	while (true) {
		std::cin >> selection;
		if (selection >= 1 && selection <= num_planets) {
			break;
		}
		std::cout << "Invalid input, try again:\t";
	}


	//Here's where I would use classes
	std::string planet_names[num_planets] = {
		"Mercury",
		"Venus",
		"Earth",
		"Mars",
		"Jupiter",
		"Saturn",
		"Uranus",
		"Neptune"
	};

	double planet_accelerations[num_planets] = {
		0.378,//Mercury
		0.907,//Venus
		1.000,//Earth
		0.377,//Mars
		2.360,//Jupiter
		0.916,//Saturn
		0.889,//Uranus
		1.120//Neptune
	};

	long int planet_distances[num_planets] = {
		57000000,//Mercury
		26000000,//Venus
		0,//Earth
		48000000,//Mars
		390000000,//Jupiter
		793000000,//Saturn
		1689000000,//Uranus
		2700000000//Neptune

	};

	system("cls");
	std::cout << "Name:\t\t" << name << std::endl;
	std::cout << "Destination:\t" << planet_names[selection - 1] << std::endl;
	std::cout << "Weight on Earth: " << weight << std::endl;
	std::cout << "Weight on " << planet_names[selection - 1] << ": " << calculateWeight(weight, planet_accelerations[selection - 1]) << std::endl;
	printTravelTime(speed, planet_distances[selection - 1]);

	std::cin.ignore();
	std::cin.get();
	return 0;
}

void printTravelTime(unsigned short speed, unsigned long int distance) {

	unsigned long int hours = distance / speed;
	unsigned long int days = hours / 24;
	hours -= (days * 24);
	unsigned long int years = days / 365;
	days -= (years * 365);

	std::cout << "Travel time:\t" << years << " years, " << days << " days and " << hours << " hours." << std::endl;
}

double calculateWeight(unsigned short initialWeight, double modifier) {
	return (initialWeight * modifier);
}


Note that, I used the distances you supplied in your original program. They might not be very accurate, because the planets are in orbit around the sun, not the earth.
Thanks for writing that. It's late to go over it tonight, but I have three days. Like I said, I can't use while loops, although they are the most efficient here. There are some other things, but all in all, your code answers my question, and is definitely designed better. Previously, I had also used separate arrays, and it worked fine. I don't know why I was trying to force all that disjointed data into one array. Maybe trying to make it uber efficient, and doing the opposite in the process. Anyway, thanks again, I'll check it out in more detail tomorrow.
Okay, this is what I ended up doing. One single function was used, and no arrays, but as you said, the arrays were not the best way to go in this program. I just wanted to practice 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// This program calculates a person's travel time
// to a planet, and weight on that planet when given
// travel speed from Earth, and weight on Earth
// it then prints all data to a file named 

#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

//function prototypes
double weightCalc(double weight, double gravity);

int main()

{
	char name[20], choice; // Char variables
	double weight, speed, newWeight, // Double variables 
		   travelTime, days, years;
	int planet; //Intenger variables
	string planetName = " ", //String Variables
	tUnit = " ";
	
	//Flush old input
	fflush(stdin);
	
//Ask for user's name
cout << "To begin interplanetary travel computations please \n"
     << "Enter your name: ";
cin.getline ( name, 20 ); //store name for output and file writing 
cout << "\n";
cout << "Hello, " << name << ". Please enter your weight, \n"
     << "in pounds, and then press enter: "; //ask user to input weight
cin >> weight; //store name for calculations, output, and file writing
cout << "\n";

//check the input data, prompt user to rerun program with instructions
if(weight < 0)
	    {
		cout << "That is not a valid entry. Please rerun program \n"
		     << "and enter only positive numbers.";
		cout << endl;
		return 0;
        }
	
// Ask for speed of user's spacecraft in mph
cout << "Enter the speed, in mph, at which your spacecraft will be \n"
     << "traveling from Earth to the destination planet: ";
 cin >> speed; //store speed for travel calculations
cout <<	"\n";

// Check for positive speed and prompt user to rerun with instructions
	if(speed < 0)
		{
		cout << "That is not a valid entry. Please rerun program \n"
		     << "and enter only positive numbers.";
		cout << endl;
		return 0;
        }
        
 // List planet menu for user to make selection		
cout << "\tPlanets you may visit from Earth\n\n"
	 << " 1. Mercury \n"
	 << " 2. Venus \n"
	 << " 3. Earth \n"
	 << " 4. Mars \n"
	 << " 5. Jupiter \n"
	 << " 6. Saturn \n"
	 << " 7. Uranus \n"
	 << " 8. Neptune \n"
	 << " 9. Quit program \n"
	 << "\n"
	 
// Ask user to choose a number for planet selection	 
	 << "Please select the planet from the above list \n"
     << "that you will be traveling to or select 9 to quit \n"
	 << "program. Enter a number, and press enter: ";
 cin >> planet; //Store choice for switch
cout << "\n";

// Check for number within range of list and prompt to rerun program
	if(planet > 9 || planet < 0)
		{
		cout << "That is not a valid entry. Please rerun program \n"
		     << "and enter a number between 1 and 9.";
		cout << endl;
		return 0;
        }
        
// Define destination variable with switch, call functions
// to calculate weight on destination planet, and to
// calculate travel time	    
switch(planet)
	{
	case 1:
		planetName = "Mercury";
		     newWeight = weightCalc(weight, .27) ; 
		     travelTime = (57000000 / speed);
		 	break;
	case 2:
		planetName = "Venus";
		newWeight = weightCalc(weight, .086);
		travelTime = (26000000 / speed);
		 	break;
	case 3:
		planetName = "Earth";
	    newWeight = weightCalc(weight, 1);
		travelTime = (0 / speed); 	
			 break;
        case 4:
		planetName = "Mars";
	    newWeight = weightCalc(weight, .37);
		travelTime = (48000000 / speed);
		 	break;
	case 5:
		planetName = "Jupiter";
	    newWeight = weightCalc(weight, 2.64);
		travelTime = (390000000 / speed);
		 	break;
	case 6:
		planetName = "Saturn";
		newWeight = weightCalc(weight, 1.17);
		travelTime = (793000000 / speed);
		 	break;
        case 7:
	    planetName = "Uranus";
	    newWeight = weightCalc(weight, .092);
		travelTime = (1689000000 / speed); 	
			 break;
	case 8:
		planetName = "Neptune";
		newWeight = weightCalc(weight, 1.44);
		travelTime = (2700000000UL / speed); // unsigned long distance	
			 break;
	case 9:
		cout << "You have chosen to quit program! Goodbye! \n";
		return 0;
	
	// Make program terminate if switch fails
	default:
		cout << "There was an error. Please rerun program.";
}		        

// Display calculations on the screen	       
cout << setprecision(2) << fixed;
cout << "Name: " << name  << "\n"   
     << "Weight on Earth: " << weight << " lbs.\n" 
     << "Destination: " << planetName << "\n"
     << "Weight on " << planetName << ": "
     << newWeight << " lbs.\n"
     << "Travel time: ";
          
// Format travel time to make easier to view by user     
// Store time units to be sent to file
if ((travelTime / 24) < 1){
		cout << travelTime << " hours\n";	
		    tUnit =  "hours";}
else if ((travelTime / 8760) < 1){
		(travelTime /= 24);
		cout << travelTime << " days\n";
        	tUnit =  "days";}
else if((travelTime / 8760) > 1){
		(travelTime /= 8760);
		cout << travelTime << " years\n";	
		    tUnit =  "years";}
		    
// Create/open output file named planetprogram
ofstream outputFile("planetProgram.txt");

// Begin writing to output file all data exactly as 
// it was displayed on screen
outputFile << setprecision(2) << fixed
     <<"\t Interplanetary Travel Calculations\n\n" 
     << "Name: " << name  << "\n"    
     << "Destination: " << planetName << "\n"
     << "Weight on Earth: " << weight << " lbs.\n"
     << "Weight on " << planetName << ": "
     << newWeight << " lbs.\n"
     << "Travel time: " << travelTime << " "
     << tUnit;
outputFile.close(); // Close new file

return 0;
}

//Function definitions
double weightCalc(double weight, double gravity)
{
	return (weight*gravity);	
}

Glad it worked out!
Topic archived. No new replies allowed.