w3resource

C++ Exercises: Calculate the volume of a cylinder


Cylinder Volume

Write a C++ program to calculate the volume of a cylinder.

Visual Presentation:

C++ Exercises: Calculate the volume of a cylinder

Sample Solution:

C++ Code :

#include <iostream> // Including the input-output stream header file

using namespace std; // Using the standard namespace

int main() // Start of the main function
{
    int rad1, hgt; // Declaring variables to store cylinder's radius and height
    float volcy; // Declaring variable to store the volume of the cylinder

    // Outputting messages to prompt the user to input the radius and height of the cylinder
    cout << "\n\n Calculate the volume of a cylinder :\n";
    cout << "-----------------------------------------\n";
    cout << " Input the radius of the cylinder : ";
    cin >> rad1; // Reading the radius input from the user
    cout << " Input the height of the cylinder : ";
    cin >> hgt; // Reading the height input from the user

    // Calculating the volume of the cylinder using the formula: volume = π * radius^2 * height
    volcy = (3.14 * rad1 * rad1 * hgt);

    // Outputting the calculated volume of the cylinder
    cout << " The volume of a cylinder is : " << volcy << endl;
    cout << endl;

    return 0; // Return statement indicating successful completion of the program
}

Sample Output:

 Calculate the volume of a cylinder :                                  
-----------------------------------------                              
 Input the radius of the cylinder : 4                                  
 Input the height of the cylinder : 8                                  
 The volume of a cylinder is : 401.92

Flowchart:

Flowchart: Calculate the volume of a cylinder

For more Practice: Solve these Related Problems:

  • Write a C++ program to calculate the volume of a cylinder using a user-defined function that takes the radius and height as parameters.
  • Write a C++ program that computes the cylinder volume and then converts the result from cubic centimeters to liters.
  • Write a C++ program to input the dimensions of a cylinder, calculate its volume, and then print both the volume and the base area.
  • Write a C++ program that calculates the volume of a cylinder and prints the result along with a visual representation of the cylinder.

Go to:


PREV : Cone Volume.
NEXT : Sum of Even and Odd Numbers.

C++ Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.