# C program to find cube of a number using function

Write a C program to input any number from user and find cube of the given number using function. How to find cube of a given number using function in C programming. Write a C function to find cube of a given number.

Example

Input

`Input any number: 5`

Output

`Cube of 5 = 125`

## Required knowledge

Must know - Program to find power of two number.

## Declare function to find cube of a number

Cube of a number num is `cube = num * num * num`. This is easy, but we need to write a separate function for this simple statement.

1. First assign a meaningful name to the function, say `cube()`.
2. The function should accept a number whose cube is to be calculated. Hence, function definition is `cube(double num)`.
3. Finally, the function should return cube of num passed. Hence, return type of function should be `double`.

After observing above points function declaration looks like `double cube(double num);`

Note: Instead of taking `double` as parameter and return type. You can also use `int`, `float` or any other integer/fractional types. However, `double` fits best for the above requirement.

## Program to find cube using function

``````/**
* C program to find cube of any number using function
*/
#include <stdio.h>

/* Function declaration */
double cube(double num);

int main()
{
int num;
double c;

/* Input number to find cube from user */
printf("Enter any number: ");
scanf("%d", &num);

c = cube(num);

printf("Cube of %d is %.2f", num, c);

return 0;
}

/**
* Function to find cube of any number
*/
double cube(double num)
{
return (num * num * num);
}
``````

Learn more - Program to find power using recursion.

Important note: Inside `cube()` function you can also use a temporary variable to store cube of num. Which is

``````double cube(double num)
{
double c = num * num * num;
return c;
}``````

However, the above approach is not worth. In addition, it increases complexity to declare a useless variable c. Instead we can directly return cube of num as in first approach.

`%.2f` prints fractional numbers up to 2 decimal places. You can also use `%f`, to print fractional numbers up to 6 decimal places (default).

Output

```Enter any number: 5
Cube of 5 is 125.00```

Happy coding ðŸ˜‰

## About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols. as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Twitter | Google | or

Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>