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.



Input any number: 5


Cube of 5 = 125

Required knowledge

Basic C programming, Function

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 i.e. cube().
  2. The function should accept a number whose cube is be calculated. Hence, function definition is cube(double num).
  3. Finally, the function should return cube of argument 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;
    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);

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 we did 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).


Enter any number: 5
Cube of 5 is 125.00

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>