In this example, we will write a C program to calculate area of rectangle based on user input. For example, if user enters width as 4 and height as 2 then program should print 8 as area of rectangle.
Area of rectangle = width * height
C Program to calculate area of rectangle based on user input
#include <stdio.h>
int main() {
float width, height, area;
// Prompts the user to enter width of the rectangle
printf("Enter width of the rectangle: ");
scanf("%f", &width);
// Prompts the user to enter height of the rectangle
printf("Enter height of the rectangle: ");
scanf("%f", &height);
// Calculate the area of the rectangle
area = width * height;
// Print the area of rectangle
printf("Area of the rectangle is: %.2f\n", area);
return 0;
}
Output:
Enter width of the rectangle: 5.5
Enter height of the rectangle: 3.2
Area of the rectangle is: 17.60
Explanation:
- Include header file: The
stdio.h
header file is included to use theprintf
andscanf
functions for input and output. - Declare variables: In this program, we have three variables:
width
,height
andarea
. These variables store the width, height, and area of the rectangle, respectively. - Input: It prompts the user to enter the width and height of the rectangle using
printf
. User entered values are read and stored in respective variables usingscanf
. - Calculate the area: Area of the rectangle is calculated using the formula
width * height
. - Print the result: Finally, the
area
is printed usingprintf
.
Leave a Reply