# Calculating a math formula using void function-recursion in C

• Comp Sci
anonymous33
No Effort - member warned that some effort must be shown
Homework Statement:
C
Relevant Equations:
Recursion
how can i write a function that calculate math formula using void function-recursion in C?

Staff Emeritus

We can't offer you tutorial help until you try it first yourself. Show us your work.

noname12345
Your question mixes up a bunch of different, vague requirements and generic terms; but this might help you.

Firstly you ask for "... void function ...". A void function doesn't have a return value, so you're making life difficult by specifying that. Not only do you need to find an alternative way to obtain the final result, it is in the very nature of "recursion" that each level of recursion needs access to the intermediate results from the deeper levels.

You want to "calculate math formula", but do not specify what formula?

You say you want to use "function recursion", but only a subset of formulae lend themselves to recursive solutions.

So, let's start by picking an example formula: factorial. factorial( n ) =: n* n-1 * n-2 * n-3...

This can be computed in C without recursion or void return as:
Code:
int factorialIterative( int n ) {
while( n > 1 ) {
n -= 1;
}
}

Using recursion and non-void function:
Code:
int factorialRecursive( int n ) {
if( n == 1 ) return 1;
return n * factorialRecusive( n-1 );
}
(That's pretty much the standard form for recursion in C.)

If you really insist on making life difficult by using a void function, then you need to have a way to return the computed result to the caller. One way to to that is to pass a pointer to a variable in the calling code that the function can store the result to.

Code:
void factorialRecursiveVoid( int *answer, int n ) {
if( n == 1 ) return;
}