In this article, we are going to discuss how to calculate the perimeter of the square. So let’s start.
How to find the Perimeter of a square in C
For example-
Input –
So first step is we are going to take input from the user in the form of the side that is 2
Logic –
To calculate the perimeter of a square we have to know about the formula first, So the formula is :
Perimeter = 4 * side
Output-
according to our input, we get the output as follows:
Enter the side of square:4
the perimeter of a square is 16.000000
We are going to see two examples to calculate the perimeter of a square one by using a simple formula and another one by using a user-defined function.
Example 1:
//C program to find the perimeter of the square
#include<stdio.h>
int main(){
float = side, perimeter;
printf(“Enter the side of square :”);
scanf(“%f”, &side);
perimeter = 4 * side;
printf(“The perimeter of a square is %f” , perimeter);
return
}
Output
Enter the side of square:4
The perimeter of a square is 16.000000
Step 1: First we take two float-type variables first one is to take the side of the square from the user and the second one is to print the value in the perimeter.
Step 2: After that, we simply use scanf() to store the value of a variable.
Step 3: then we simply use the formula to calculate the perimeter. We can see that we simply use the perimeter variable to calculate the perimeter.
Step 4: after all these steps we simply use printf() to get our final answer.
Example 2 :
// C program to calculate the perimeter of a square by using a user-defined function.
#include<stdio.h>
float perimeter(float side){
return 4 *side;
}
int main(){
float side, p;
printf(“Enter the side of square :”);
scanf(“%f”, &side);
p = perimeter(side);
printf(“The perimeter of a square is %f”, p);
return 0;
}
Output
Enter the side of square:16
The perimeter of a square is 64.000000
Step 1: First we create a user-defined function. From the above example, we can see that we create a user-defined function that gives a name as the perimeter and use the float type parameter in it and gives a name as the side.
Step 2: then we go to the main function. In that we take two float-type variables first one is to take the side of the square from the user and the second one is to print the value that is p.
Step 2: After that, we simply use scanf() to store the value of a variable.
Step 3: Then we pass the value in variable p . from the above program, we can simply see that we pass the value in p.
Step 4: after all these steps we simply use printf() to get our final answer.
In this way, we simply understand how to calculate the perimeter of the square. I hope you simply understand this program. So for now keep learning and keep exploring.