C Program to find cube of a number

Category: C Program

Learn how to write a C program to find the cube of a number using a function. This article provides a complete explanation and code example, highlighting the benefits of using functions in C programming.

Calculating the cube of a number involves multiplying the number by itself twice. This simple yet fundamental operation is frequently used in various mathematical computations and programming tasks. In this article, we will explore how to write a C program that calculates the cube of a given number using a dedicated function. We will explain the concept, outline the structure of the C program, and provide a complete implementation with a function to compute the cube.

Understanding the Cube of a Number

The cube of a number n is denoted as n^3 and is calculated as:

n^3 = n x n x n

For example:

  • The cube of 2 is 2 x 2 x 2 = 8.
  • The cube of 3 is 3 x 3 x 3 = 27 .

Importance of Functions in C Programming

Functions in C are blocks of code designed to perform a specific task. They are useful for breaking down complex problems into simpler, manageable parts. Functions improve code reusability, modularity, and maintainability. By encapsulating the logic within a function, we can easily reuse the function across different parts of the program or even in different programs.

Write a C Program to find cube of a number

We will write a C program that includes a function cube to calculate the cube of a number. The function will take an integer as an argument and return its cube.

#include <stdio.h>

// Function to calculate the cube of a number
int cube(int num) {
    return num * num * num;
}

int main() {
    int number, result;

    // Input the number from the user
    printf("Enter a number to find its cube: ");
    scanf("%d", &number);

    // Call the cube function and store the result
    result = cube(number);

    // Output the result
    printf("The cube of %d is %d.", number, result);

    return 0;
}

Output

Enter a number to find its cube: 4
The cube of 4 is 64.

Explanation of the Code

  1. Function cube:
    • The function cube takes an integer num as its parameter.
    • It returns the result of multiplying num by itself twice, which is num * num * num.
    • This function encapsulates the logic for calculating the cube, making the code more organized and reusable.
  2. Main Function main:
    • The program begins by declaring two integer variables: number and result.
    • The user is prompted to enter a number, which is stored in the variable number.
    • The function cube is called with number as an argument, and the returned value is stored in result.
    • The result, which is the cube of the entered number, is printed to the console.

Recommended Posts