## Monday, November 4, 2013

### C program how to find the cube of a number using recursion!!

One of my cousin asked this question. So thought of sharing this.  The tricky thing here is, if we use recursion, we dont get power of 3, we will get power of 2,4,6 ... etc. To get the cube, we need to call the recursive function two times, so that we will get the number to the power of 4, then devide that result by given number, so that you will get the given number cube.

Given number cube = number to the power of 4 / number

Below is the C program for finding the cube using recursion.

```#include<stdio.h>

int iterator = 2;
int givenValue=0;
int cubeOfNumber(int number)
{
if(!iterator)
{
printf("cube of %d is %d\n",givenValue,number/givenValue);
return;
}
else
{
iterator--;
cubeOfNumber(number*number);
}
}

int main()
{
int n=0;
printf("enter the number to find the cube\n");
scanf("%d",&givenValue);
cubeOfNumber(givenValue);
}

```
OutPut:

./a.out
enter the number to find the cube
3
cube of 3 is 27
\$ ./a.out
enter the number to find the cube
25
cube of 25 is 15625

Mythili rathinam said...

This code is not working.