w3resource logo


C Programming Exercises

C Exercises: Calculates the volume of a sphere

Secondary Nav

C Input Output statement and Expressions: Exercise-2 with Solution

Write a C program that calculates the volume of a sphere.

C Programming : Volume of a sphere

A sphere is a perfectly round geometrical object in three-dimensional space that is the surface of a completely round ball.

In three dimensions, the volume inside a sphere is derived to be V = 4/3*π*r3 where r is the radius of the sphere

Python: Volume of a sphere

C Code:

#include <stdio.h>

float myradius;          /* radius of the sphere */
float myvolume;          /* volume of the sphere (to be computed) */
char line_text[50];      /* a line from the keyboard */

/* the value of pi to 50 places, from wikipedia */
const float PI = 3.14159265358979323846264338327950288419716939937510;

int main() {
	printf("Input the radius of the sphere : ");
	fgets(line_text, sizeof(line_text), stdin);
	sscanf(line_text, "%f", &myradius);

	myvolume = (4.0 / 3.0) * PI * (myradius * myradius * myradius);  /* volumn=(4/3) * pi * r^3*/
	printf("The volume of sphere is %f.\n", myvolume);

	return(0);
}

Test Data :
Radius of the sphere : 2.56

Expected Output :
The volume of sphere is 70.276237.

Solution

#include <stdio.h>

float myradius;       /* radius of the sphere */
float myvolume;       /* volume of the sphere (to be computed) */
char line_text[50];      /* a line from the keyboard */

/* the value of pi to 50 places, from wikipedia */
const float PI = 3.14159265358979323846264338327950288419716939937510;

int main() {
	printf("Input the radius of the sphere : ");
	fgets(line_text, sizeof(line_text), stdin);
	sscanf(line_text, "%f", &myradius);

	myvolume = (4.0 / 3.0) * PI * (myradius * myradius * myradius);  /* volumn=(4/3) * pi * r^3*/
	printf("The volume of sphere is %f.\n", myvolume);

	return(0);
}

Improve this sample solution and post your code through Disqus.



Join our Question Answer community to learn and share your programming knowledge.