# Functions Exercises

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.

**Required knowledge**

Basic C programming, Functions, Returning value from function

**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.

- First assign a meaningful name to the function, say cube().
- The function should accept a number whose cube is to be calculated. Hence, function definition is cube(double num).
- 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); }

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