C Program to Find Surface Area and Volume of a Cube

C Program to Find Surface Area and Volume of a Cube

C Program to Find Surface Area and Volume of a Cube


Introduction

A cube is a three-dimensional shape with six equal square faces. It is one of the most fundamental geometric shapes, and understanding its properties is crucial for various applications in mathematics, physics, and computer graphics. In this tutorial, we will explore how to calculate the surface area and volume of a cube using a simple C program. We will also explain the logic behind the calculations and demonstrate the output of the program step by step.


Formulas for Surface Area and Volume

The calculation of the surface area and volume of a cube depends on its side length, which we will denote as side.

  • Surface Area: The surface area of a cube is the total area covered by its six faces. Since all faces are squares of equal size, the formula is:
    Surface Area = 6 × (side × side)
  • Volume: The volume of a cube represents the total space enclosed by it. The formula is:
    Volume = side × side × side

Both these formulas are straightforward and easy to implement in a C program. We will now write a program to compute these values based on user input for the side length.


C Program Code

Below is the complete code for calculating the surface area and volume of a cube:

#include <stdio.h>

int main() {
    float side, surface_area, volume;

    // Prompt the user to enter the side length of the cube
    printf("Enter the side length of the cube: ");
    scanf("%f", &side);

    // Calculate surface area and volume
    surface_area = 6 * (side * side);
    volume = side * side * side;

    // Display the results
    printf("Surface Area of the cube: %.2f\n", surface_area);
    printf("Volume of the cube: %.2f\n", volume);

    return 0;
}
    

Output

Here is an example of the output when you run the above program:

Enter the side length of the cube: 5
Surface Area of the cube: 150.00
Volume of the cube: 125.00
    

The program first asks for the side length of the cube. Once the user provides the input, it calculates and displays the surface area and volume of the cube.


Explanation of the Program

Let us break down the program to understand its components:

  • Input: The program uses the scanf function to take user input for the side length of the cube. The input is stored in a variable named side.
  • Calculations:
    • The surface area is computed using the formula 6 × (side × side), and the result is stored in the variable surface_area.
    • The volume is computed using the formula side × side × side, and the result is stored in the variable volume.
  • Output: The program uses printf statements to display the calculated surface area and volume. The %.2f format specifier ensures the results are displayed with two decimal points.
  • Return Value: The return 0; statement indicates that the program has executed successfully.