Program to Find Cube of a Number using Function

Posted in

Program to Find Cube of a Number using Function
vinaykhatri

Vinay Khatri
Last updated on December 14, 2024

    Function in programming languages used to perform specific tasks. The functions increase the reusability of code and make the overall code more modular and readable. In this programming tutorial, we will learn how to find a cube of a number using functions.

    C Program to Find Cube of a Number using Function

    #include 
    
    //function that will find the cube of a number
    int cube(int num)
    {
    	return num* num*num;
    }
    int main() 
    {
       int num;
       printf("Enter a Number: ");
       scanf("%d", &num);
       
       printf("The cube of Number %d is %d", num, cube(num));
       	
    }

    Output

    Enter a Number: 27
    The cube of Number 27 is 19683

    C++ Program to Find Cube of a Number using Function

    #include 
    using namespace std;
     
    //function that will find the cube of a number
    int cube(int num)
    {
    	return num* num*num;
    }
    
    int main() 
    {
       int num;
       cout<<"Enter a Number: "; cin>>num;
       
       cout<<"The cube of Number "<< num <<" is "<< cube(num);
    	
    }

    Output

    Enter a Number: 5
    The cube of Number 5 is 125

    Python Program to Find Cube of a Number using Function

    def cube(num):
        return num*num*num
    
    num = int(input("Enter a Number: "))
    
    print(f"The cube of Number {num} is {cube(num)}")

    Output

    Enter a Number: 10
    The cube of Number 10 is 1000

    Complexity Analysis

    • Time Complexity: O(1), constant time complexity.
    • Space Complexity: O(1).

    Conclusion

    In this Programing tutorial, we learned how to find a cube of a number using user-defined functions. We implement the program in three different programming languages C++, C, and Python. If you like this article or have any suggestions, please let us know by commenting down below.

    People are also reading:

    Leave a Comment on this Post

    0 Comments