WAP to find the cube of a number
Objective
Write a C++ program to find the cube of a number.
Algorithm / Approach
- Declare two integers:
a(the base number) andb(the result). - Read the base number.
- Calculate the cube by multiplying the number by itself three times:
b = a * a * a. - Print the result.
main.cpp
#include<iostream>
using namespace std;
int main() {
int a;
int b;
cout<<"Enter Number: ";
cin>>a;
b = a*a*a;
cout<<"CUBE = "<< b<< endl;
return 0;
}
Expected Output
Enter Number: 5 CUBE = 125
Explanation of the Program
- The cube of a number is simply the number multiplied by itself three times (n³).
- While C++ provides a built-in
pow()function for exponents, for very small powers like a square or a cube, multiplying manually is actually faster for the computer to execute.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)