C program to find perimeter of a rectangle

Previous Program Next Program

Write a C program to input length and width of a rectangle and calculate perimeter of the rectangle. How to find perimeter of a rectangle in C programming. Logic to find the perimeter of a rectangle if length and width are given in C programming.



Input length: 5
Input width: 10


Perimeter of rectangle = 30 units

Required knowledge

Fundamentals of C, Data types, Taking user input in C

Perimeter of rectangle

Perimeter of rectangle is given by the below formula

Perimeter of rectangle

Where l is the length and w is the width of rectangle.

Logic to find perimeter of a rectangle

Below is the step by step descriptive logic to find perimeter of a rectangle

  1. Read length and width of the rectangle using scanf() function. Store these in two variables say length and width.
  2. Apply the formula for perimeter of rectangle perimeter = 2 * (length + width).
  3. Print the value of perimeter.

Program to find perimeter of rectangle

 * C program to find perimeter of rectangle

#include <stdio.h>

int main()
    float length, width, perimeter;

     * Reads length and width of rectangle from user
    printf("Enter length of the rectangle: ");
    scanf("%f", &length);
    printf("Enter width of the rectangle: ");
    scanf("%f", &width);

    /* Calculates perimeter of rectangle */
    perimeter = 2 * (length + width);

    /* Prints perimeter of rectangle */
    printf("Perimeter of rectangle = %f units ", perimeter);

    return 0;

NOTE: Never forget to prioritize the order of operations using a pair of braces ( ). As both the statements perimeter = 2 * length + width and perimeter = 2 * (length + width) generates different results. Also never ever write the statements like 2 * (length + width) as 2(length + width). It will generate a compiler error.

Enter length of the rectangle: 5
Enter width of the rectangle: 10
Perimeter of rectangle = 30.000000

Happy coding ;)

Recommended posts

Previous Program Next Program
Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment