for loop?

Hi everyone!

I need help with a loop...I believe the one I need to use is a for loop but I might be wrong.

Basically the program needs to count every minute and say how much fuel is required for a ship to escape at a certain altitude and how much fuel is available until the amount of fuel available is larger than the fuel required at a certain altitude.

This is the output.

TIME ALTITUDE FUEL AVAILABLE FUEL REQUIRED
---------------------------------------------------------------
1 min 9900 KM 85 KG 95.1 KG
2 min 9500 KM 95 KG 95.2 KG
3 min 8600 KM 105 KG 95.7 KG

This is another example of output.

TIME ALTITUDE FUEL AVAILABLE FUEL REQUIRED
---------------------------------------------------------------
1 min 9900 KM 35 KG 95.1 KG
2 min 9500 KM 45 KG 95.2 KG
3 min 8600 KM 55 KG 95.7 KG
4 min 7000 KM 65 KG 96.5 KG
5 min 4500 KM 75 KG 97.8 KG
6 min 900 KM 85 KG 99.6 KG
7 min 0 KM 95 KG 100.0 KG

1. Initialize the time to zero
2. Now, while the amount of fuel is less than the amount of fuel required and the current altitude
is greater than zero,
a) Add one to the time
b) Compute the new current altitude using the formula:
altitude = altitude - beam_strength * time * time
c) Calculate the amount of fuel required to escape using this new altitude. Use the formula for
the required fuel that was given above.
d) Compute the new amount of fuel in the engines by adding 10 Kg. to the previous
amount. Scotty can shovel 10 Kg. of fuel per minute.
e) Print out the time, the current altitude, the fuel available, and the fuel required for escape.
Sounds like a for loop. I can't give you the solution, but it sure does sound like a for loop.

Although a while loop works just as well.
Last edited on
sounds like a while loop to me.


while the amount of fuel is less than the amount of fuel required and the current altitude is greater than zero



1
2
3
4
5
while( amount_of_fuel < amount_of_fuel_required && current_altitude > 0 )
{
    ++time;
    //do the rest of calculations
}
A for loop is exactly the same as that, it just does ++time for you:
1
2
3
4
int time = 0;
for (; fuelAmount < fuelRequired && altitude > 0; ++time) {
    // do the calculations
}
I agree with giblit, a for loop is good when the number of iterations are known (or can be computed from constant values), otherwise use a while loop.

All the loop constructs can be re-written in one of the other forms, but the above rule works well.
Topic archived. No new replies allowed.