Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to calculate the volume of a sphere using C programming language?
The volume of a sphere is the amount of space enclosed within the sphere. In C programming, we can calculate this using the mathematical formula for sphere volume.
Syntax
volume = (4.0/3.0) * ? * radius³
Where ? (pi) ? 3.14159 and radius is the distance from the center to any point on the sphere's surface.
Algorithm
Step 1: Enter radius of sphere at runtime
Step 2: Apply the formula to variable
Volume = (4/3) * ? * radius³
Step 3: Print the volume
Step 4: Stop
Example 1: Basic Volume Calculation
This example calculates the volume of a sphere with a fixed radius −
#include <stdio.h>
int main() {
float vol;
int rad;
rad = 20;
vol = ((4.0f/3.0f) * (3.1415) * rad * rad * rad);
printf("The volume of a sphere is %.2f<br>", vol);
return 0;
}
The volume of a sphere is 33509.34
Example 2: Volume and Surface Area Calculator
This example calculates both volume and surface area with user input −
#include <stdio.h>
#define PI 3.14159
int main() {
float rad;
float area, vol;
printf("Enter radius of the sphere: ");
scanf("%f", &rad);
area = 4 * PI * rad * rad;
vol = (4.0/3.0) * PI * rad * rad * rad;
printf("Surface area of sphere is: %.3f<br>", area);
printf("Volume of sphere is: %.3f<br>", vol);
return 0;
}
Enter radius of the sphere: 4 Surface area of sphere is: 201.062 Volume of sphere is: 268.083
Key Points
- Use float or double data types for accurate decimal calculations.
- Define PI as a constant for better precision:
#define PI 3.14159 - The formula is: V = (4/3) × ? × r³
- Always use
(4.0/3.0)instead of(4/3)to avoid integer division.
Conclusion
Calculating sphere volume in C involves applying the mathematical formula with proper data types. Using the constant PI and floating-point arithmetic ensures accurate results for geometric calculations.
Advertisements
