Below is the program to find the square of a given number in C programming with step-by-step explanation.
#include<stdio.h>
int main()
{
float number, square;
printf(“Please Enter any integer Value : “);
scanf(“%f”, &number);
square = number * number;
printf(“square of a given number %.2f is = %.2f”, number, square);
return 0;
}
Output:
Please Enter any integer Value : 4
square of a given number 4.00 is = 16.00
let’s break down the C program step by step:
- #include <stdio.h>: This line includes the standard input-output library, which provides functions like printf and scanf for input and output operations.
- int main(): This line marks the beginning of the main function, which is the entry point of a C program. It returns an integer (int) value to the operating system when the program finishes running. In this case, it takes no arguments, indicated by the empty parentheses ().
- {: The curly brace marks the beginning of the main function’s body, where the actual code of the program resides.
- float number, square;: Here, you declare two floating-point variables: number and square. number will be used to store the input integer value, and square will store the square of that value.
- printf(“Please Enter any integer Value: “);: This line uses the printf function to display the message “Please Enter any integer Value: ” on the console, prompting the user to input an integer.
- scanf(“%f”, &number);: This line uses the scanf function to read input from the user. It expects a floating-point value (%f) and stores it in the number variable. The & operator is used to provide the memory address of the number variable so that scanf can write the input value to it.
- square = number * number;: Here, you calculate the square of the input number by multiplying the number by itself and store the result in the square variable.
- printf(“square of a given number %.2f is = %.2f”, number, square);: This line uses printf to display the result. It prints the input number, rounded to two decimal places (%.2f), along with the calculated square, also rounded to two decimal places.
- return 0;: This line indicates the end of the main function and returns an exit status of 0 to the operating system, which typically signifies successful execution of the program.
- }: The closing curly brace marks the end of the main function’s body and, thus, the end of the program.
When you run this program:
It prompts you to enter an integer value.
You input an integer (in this case, “4”) and press Enter.
The program calculates the square of the input value (4 * 4 = 16.00, since we’re using floating-point variables).
It then displays the input value and its square as “square of a given number 4.00 is = 16.00,” with both numbers rounded to two decimal places.
So, in your provided example, when you entered “4,” the program displayed the result as shown.