Examples
Now, let’s understand this with the help of examples.
Example 1
Input: 5
Output: 125
Suppose we have the number 5, and we have to find the cube. To find the cube of 5, we have to multiply it three times, i.e., 5*5*5, equal to 125.
Example 2
Input: 10
Output: 1000
Now, Suppose we have the number 10, and we have to find the cube. To find the cube of 10, we have to multiply it three times, i.e., 10*10*10, which equals 1000.
Now let’s see the C++ implementation of this approach.
Implementation in C++
C++ Program
#include <iostream>
#include <cmath>
using namespace std;
int cube(int a)
{
return(a*a*a);
}
int main()
{
int number;
cout << "ENTER THE NUMBER:";
cin >> number;
int res=cube(number);
cout << "cube obtained:" << res; //calling function
return 0;
}

You can also try this code with Online C++ Compiler
Run CodeWe have created a cubic function in this program, which takes a number as an argument and returns an integer. We are asking for a number as input from the user, and we are calling our function bypassing the user’s input, and then the function returns the cube of the number, and then we are just printing the result.
Time Complexity: O(1)
Space Complexity: O(1)
Try and compile by yourself with the help of online C++ Compiler for better understanding.
Frequently Asked Questions
What is Time Complexity?
The amount of time taken by an algorithm for its complete execution is called the time complexity of the algorithm. It shows the efficiency of an algorithm. To know more about the time complexity, click here.
Can you find the cube of a number using the pow() function?
Yes, we can also find the cube of a number using the pow() function defined in the cmath header file.
How is the space complexity O(1) in this program?
The above function takes the same amount of space regardless of the input size.
Conclusion
In this article, we have discussed the C++ program to find the cube of a number using a function. We also discussed the time complexity and space complexity of the program.
Recommended Readings: