C program for area of rectangle

Example of C program for area of rectangle –  This program will demonstrate two examples to calculate are of rectangle. First program is very simple one and second program uses a function to get the area of rectangle. Both program will use same formula for area of rectangle.

Formula for area of rectangle: Area = width*height.

C program for area of rectangle – Simple

This is simple C code to calculate area of rectangle. It will multiply width and height of the rectangle and print the area on console screen.


/*------------------------------------------------
* C program for area of rectangle
*/

#include <stdio.h>

int main()
{    

      float width = 2.5;
      float height = 3.5;
      float area =0;

      //apply rectangle area formula
      area = width * height;


      //%.3f format specifier will print up to 3 decimal digits
      printf("Area of Rectangle is:%.3f ",area);


      return 0;

}

Output:
Area of Rectangle is:8.750

C program for area of rectangle using function

In this program example to calculate area of a rectangle, a user defined function “float area(float width, float height)” has been created that receives two floats arguments i.e. width and height of the rectangle. The function calculate the area and return to the calling program.

This example will prompt user to enter width and height of the rectangle and calculate the area of rectangle using area formula.


/*------------------------------------
* C program to calculate area of rectangle
*/

/* function that receives width and height of
* a rectangle, calculate area and 
* return the result
*/ 
float area(float width, float height){

	return width*height;
}

//Test program
int main()
{
	float width =0;
	float height = 0;
	float result =0;


	printf("Enter Rectangle Width:");
	scanf("%f",&width);

	printf("Enter Rectangle Height:");
	scanf("%f",&height);

	//call area function anf recieve the 
	//area
	result = area(width,height);

	printf("Area of Rectangle = %f ", result);

	return 0;

}

Output:

Enter Rectangle Width:2.5
Enter Rectangle Height:3.5
Area of Rectangle = 8.750000

Related Posts