Recursively increment variable used in many calculations

Hi! My program currently works, but I need it increment using only recursions, not loops. The program needs to output a number (x), its square root (sqrt x), and its square (x^2). I need this entire process (all three calculations) to repeat 81 times, creating the following output.


Number: 1
Number's square root: 1
Number squared: 1
---------
Number: 2
Number's square root: 1.41421
Number squared: 4
---------

(and so on and so forth)

Number: 81
Number's square root: 9
Number squared: 6561
---------


The program should not require input from the user, but output all 81 iterations upon start-up. I've used this link (http://www.cprogramming.com/tutorial/lesson16.html) to understand recursion, but I haven't been able to modify the examples to account for the three calculations in my program. The way I'm currently incrementing the variable is not accepted by my teacher, and more importantly, it's very inefficient and time consuming to type out.

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

int calc1 (int x){ //calculates "Number"
	return x;
}
double calc2 (double x){ //calculates "Number's square root"
	return sqrt(x*1.0);
}
int calc3 (int x){ //calculates "Number squared"
	return pow(x, 2.0);
}
int M1 (int x){ //outputs complete iteration of the program
	cout << "Number: " << calc1 (x) << endl;
	cout << "Number's square root: " << calc2 (x) << endl;
	cout << "Number squared: " << calc3 (x) << endl;
	cout << "_________" << endl;
	return x;
}
int main (){ //how program currently increments variable for next iteration
	int a = 1;
	a = M1 (a);
	int b = 2;
	b = M1 (b);
	int c = 3;
	c = M1 (c);
	// and so on and so forth
	int z = 81;
	z = M1 (z);
}


I'm sorry for any awkwardness in my code, and welcome advice beyond my specific question. Repeating without loops is the focus of my class right now, so advice on loop-less programming will probably help me too. Thank you for any help and advice.
Recursion? In C++? Oooooooh boy.

To define a recursive function, when defining a function, make sure the function calls itself.

Your function will need to also take an integer that will be incremented per recursion.

EDIT: Have fun.

-Albatross
Last edited on
closed account (jwC5fSEw)
Your function will need to also take an integer that will be incremented per recursion.


No it won't. He said the function isn't supposed to take any input.

Anyway, if you're having trouble figuring out the recursion, think about it like this. You can obviously write a function to print out a number, its square root and itself squared; you already have. A recursive version is just doing that for x and then calling itself for x+1. Do that until the condition is met (i.e. x = 81) then stop.
Topic archived. No new replies allowed.