w3resource logo


C Programming Exercises

C Exercises: Calculate the perimeter of a rectangle

Secondary Nav

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

Write a C program that prints the perimeter of a rectangle to take its height and width as input.
Test Data :
Height of the Rectangle : 5
Width of the Rectangle : 7

Expected Output :
Perimeter of the Rectangle is : 24.000000

C Code:

#include <stdio.h>

float rec_width;         /* width of the rectangle */
float rec_height;        /* height of the rectangle */
float rec_perimeter;     /* perimeter (to be computed) */
char line_text[50];      /* a line from the keyboard */

int main() {
	printf("Input the height of the Rectangle : ");
	fgets(line_text, sizeof(line_text), stdin);
	sscanf(line_text, "%f", &rec_height);

	printf("Input the width of the Rectangle : ");
	fgets(line_text, sizeof(line_text), stdin);
	sscanf(line_text, "%f", &rec_width);

	rec_perimeter = 2.0 * (rec_height + rec_width); /* perimeter = 2 * ( width + height )*/

	printf("Perimeter of the Rectangle is : %f\n", rec_perimeter);

	return(0);
}

Solution

#include <stdio.h>

float rec_width;         /* width of the rectangle */
float rec_height;        /* height of the rectangle */
float rec_perimeter;     /* perimeter (to be computed) */
char line_text[50];      /* a line from the keyboard */

int main() {
	printf("Input the height of the Rectangle : ");
	fgets(line_text, sizeof(line_text), stdin);
	sscanf(line_text, "%f", &rec_height);

	printf("Input the width of the Rectangle : ");
	fgets(line_text, sizeof(line_text), stdin);
	sscanf(line_text, "%f", &rec_width);

	rec_perimeter = 2.0 * (rec_height + rec_width); /* perimeter = 2 * ( width + height )*/

	printf("Perimeter of the Rectangle is : %f\n", rec_perimeter);

	return(0);
}

Improve this sample solution and post your code through Disqus.



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