Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Purpose: A simple sample of recursion. QUESTION: Building on their success of la

ID: 3682425 • Letter: P

Question

Purpose: A simple sample of recursion.
QUESTION: Building on their success of landing spacecraft on planets and comets, rocket scientists have developed a new kind of space ship which will enable interstellar travel across the large distances of space very quickly. The technology is very complicated, but the visible behaviour of the ship is quite simple:
If the distance to the destination is greater than 1 meter, the ship will "fold space" and "jump" half that distance in one minute.
Any distance of 1 meter or less will take exactly one minute, using normal rockets.
For example, if the ship has to travel 10 meters, it will jump 5 meters in the first minute, 2.5 meters the second minute, 1.25 meters the 3rd minute, and 0.625 meters the fourth minute. Finally, the remaining 0.625 meters takes one more minute. Thus the total time to travel 10 meters is 5 minutes. (That seems very slow, and it is for small distances; the true value of this method only reveals itself for large distances.)
Write a recursive function called spaceTime() that calculates the time needed to travel a given distance. Your main function should ask the user for a distance in meters, and then calls your function to calculate the time required to travel the given distance.
Test your function out on all of the following examples:
Maximum distance between the earth and the moon: 405,410 km
Average distance between the earth and the sun: 149,597,870 km
Approximate distance between the sun and the closest star: 4.24 light years (a light year is roughly 1015 meters).
Size of the observable universe: 93 billion light years
Remember that the ship measures distances in meters, not km or light years.

Explanation / Answer

I have executed it under CodeBlocks IDE and checked all the given test cases:

#include <iostream>

using namespace std;

float spaceTime(int);
long int i=0,x=0,minutes=0;
int main()
{
long int meters=0;
//do{
cout << "Enter the distance in meters :" ;
cin >> meters;
if(meters <= 1) //if distance is less than or equals to 1
cout << meters<<" Minutes Required to travel the " <<meters<<" meters"<<endl;
else
minutes=spaceTime(meters);

cout << minutes << " Minutes Required to travel the " <<meters<<" meters"<<endl;
//}while(true);
return 0;
}
float spaceTime(int meters)
{

if(meters < 1)
return 1;
else{
x=meters/2+spaceTime(meters/2); // x is a dummy variable
i++; // calculates the minutes
}
return i+1;// one is for covering the last part of the distance
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote