C Program To Find Square of a Number

In this post, we will learn how to find square of a number using the C Programming language.

C Program To Find Square of a Number

When a number or integer is multiplied by itself, the resultant is called a ‘Square of a Number’. For example: The Square of 7 is (7 x 7) which is 49.

We will be finding the square of a number using two different methods. First by using the standard method and second by using a user defined function.

So, without further ado, let’s begin this tutorial.

C Program To Find Square of a Number

// C Program To Find Square of a Number
#include <stdio.h>
int main(){
    float num, square;
    
    // Asking for Input
    printf("Please enter any integer value: ");
    scanf("%f", &num);
    
    square = num * num;
    printf("The Square of the given number %.2f is %.2f", num, square);
    return 0;
}

Output

Please enter any integer value: 7
The Square of the given number 7.00 is 49.00

How Does This Program Work ?

    float num, square;

In this program, we have declared two float data type variables named num and square.

    // Asking for Input
    printf("Please enter any integer value: ");
    scanf("%f", &num);

Then, the user is asked to enter the value of an integer. The value of this integer will get stored in num named variable.

    square = num * num;

We calculate the square by multiplying the number by itself.

    printf("The Square of the given number %.2f is %.2f", num, square);

Finally, the square of the number is printed using printf() function. Here, we have used %.2f format specifier because we want the result to be shown only till 2 decimal places.

C Program To Find Square of a Number Using a Function

// C Program To Find Square of a Number Using Functions
#include <stdio.h>
float calculateSquare(float n){
    return (n * n);
}

int main(){
    float num, square;
    
    // Asking for Input
    printf("Enter an integer value: ");
    scanf("%f", &num);
    
    square = calculateSquare(num);
    printf("The Square of %.2f is %.2f", num, square);
    return 0;
}

Output

Enter an integer value: 2.7
The Square of 2.70 is 7.29
float calculateSquare(float n){
    return (n * n);
}

In this program, we have declared a function named as calculateSquare which will return the square of the number. 

Then, we call this function in the main function to obtain the square of the number entered by the user.

Conclusion

I hope after going through this post, you understand how to find the square of a number using C Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *