C++ Program to Calculate the Volume of a Cube

Calculating the volume of a cube is a basic problem often encountered in geometry. A cube is a three-dimensional shape with six equal square faces. The formula to calculate the volume of a cube is:

 V = a^3 

where V is the volume and ais the length of a side of the cube.

In this article, we will write a C++ program that takes the side length of a cube as input and calculates its volume using the formula provided.

Prerequisites

Before we begin, ensure you are familiar with:

  • Basic input and output operations in C++
  • Arithmetic operations in C++
  • Compiling and running a C++ program

C++ Program to Calculate the Volume of a Cube

C++
#include <iostream>
using namespace std;

int main() {
    // Variable to store the side length of the cube
    double side;
    
    // Prompt the user to enter the side length of the cube
    cout << "Enter the side length of the cube: ";
    cin >> side;
    
    // Calculate the volume of the cube
    double volume = side * side * side;
    
    // Display the volume of the cube
    cout << "The volume of the cube is: " << volume << " cubic units" << endl;
    
    return 0;
}

Output

Example 1

C++
Enter the side length of the cube: 3
The volume of the cube is: 27 cubic units

Example 2

C++
Enter the side length of the cube: 5
The volume of the cube is: 125 cubic units

Explanation:

  1. Variable Declaration:
    • side is declared to store the input side length of the cube.
    • volume is declared to store the calculated volume of the cube.
  2. Input Handling:
    • The program prompts the user to enter the side length of the cube.
    • The input is read and stored in the side variable.
  3. Volume Calculation:
    • The formula to calculate the volume of a cube is applied: V=a3V = a^3V=a3.
    • This is implemented as volume = side * side * side.
    • The result is stored in the volume variable.
  4. Output:
    • The program displays the volume of the cube.

Conclusion

Calculating the volume of a cube is a simple and fundamental problem in geometry. This C++ program demonstrates how to perform the calculation using basic arithmetic operations and handle user input/output.