w3resource logo
C Programming Exercises

C Exercises: Calculate the perimeter of a rectangle

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.

Sample Solution:

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);
}

Sample Output:

Input the height of the Rectangle : 5                                                                         
Input the width of the Rectangle : 7                                                                          
Perimeter of the Rectangle is : 24.000000   

C Programming Code Editor:

#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.