Help with basic recursive function? [C++]

closed account (oN3h0pDG)
Hello, I have a quick question, I just learned about recursive functions today and wrote this small program that gets the user to input a distance in meters then it loops through the function which divides the distance by half (2) until it comes to a number that is less than 1, but while it is greater than 1 it keeps calling the function to divide it by half. I thought I wrote it correctly but my compiler seems to disagree. Can someone help me figure out where I went wrong? It's probably a stupid mistake but I'm new to programming so go easy on me. Thanks for your help! :)

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
#include <iostream>
using namespace std;

void spaceTime(int distance) {
	int minutes = 0;
	float traveled = distance / 2;


	if (traveled < 1) { // base case

		cout << " Rocket traveled: " << distance << " meters in " << minutes << " minutes." << endl;

	} else if (traveled > 1) {

		minutes++;
		spaceTime(distance);

	}

}

int main() {

int distance; // meters

cout << "Enter distance: " << endl;
cin >> distance;

spaceTime(distance);

	return 0;
}
You are close, but there are a few problems with this. First, and most important, on line 16, distance should be traveled, otherwise, you pass the same value in every time and the program gets stuck in an infinite loop if the value of distance is not < 1. Second, I would recommend changing distance from an int to a float. If you don't, traveled will never get to less than one and again you get stuck in an infinite loop. To see what I mean add cout << traveled << endl; to line seven after changing line 16.
Hope this helps. If not ask another question.
closed account (oN3h0pDG)
Thank you so much! Fixed my problems! Thank you! Your are awesome!
You are welcome. By the way, I'm not sure exactly what you're trying to do with minutes, but the way you have it, it's always going to be reported as 0; If you want it to change, you'll have to pass it in by reference.
Topic archived. No new replies allowed.