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

3 comments:

Mythili rathinam said...

This code is not working.

Maradona Jons said...

Along with it also has a live casino 24 hours a day. สมัคร ufa Bet online gambling website is available to play with all casinos, baccarat, slots, roulette, dice and many other card games. We have gathered it here. With many promotions Apply for UEFA Bet now, we are happy to serve you all. With a professional team ready to solve problems And serve all of you There is a team to support the service. And answer your questions 24 hours a day.

ALLSTARinfo said...

The anime is worth watching. Come watch it.

ประวัติ การ์ตูน ญี่ปุ่น
ประวัติ การ์ตูน ญี่ปุ่น

Popular Posts