Creating a program in C to find the square root of a given number is an essential exercise for beginners and intermediate programmers. This tutorial will guide you through the process, with examples and explanations, to help you understand and build this practical program.
What is Square Root?
The square root of a number is a value which, when multiplied by itself, gives the same original number. For instance, the square root of 16
is 4
because 4
times 4
equals 16
. Finding the square root is a common task in mathematics and is often required in various programming applications.
Algorithm to Find Square Root
- Initialize Variables: Declare a variable to store the number whose square root is to be found (let's call it
num
) and a variable for the square root (let's call itresult
). - Input Value: Prompt the user to enter the number. Use the
scanf()
function to take input from the user. - Calculate Square Root: Use a standard function, like
sqrt()
from the math library, to calculate the square root of the given number. - Output Result: Display the calculated square root using the
printf()
function. Format the output to display the square root up to a certain number of decimal places.
Code Example
Here's a C program that calculates the square root of a given number:
#include <stdio.h>
#include <math.h> // Include the math library for sqrt()
int main() {
double num, result;
// Take user input for the number
printf("Enter a number: ");
scanf("%lf", &num);
// Check if the number is negative
if(num < 0) {
printf("Square root of a negative number is imaginary\n");
return 0;
}
// Calculate square root
result = sqrt(num);
// Display the result
printf("Square Root of %.2lf is: %.2lf\n", num, result);
return 0;
}
Program Output:
For example, if you input the number 16, the program calculates and displays the square root as 4.00.
Enter a number: 16
Square Root of 16.00 is: 4.00
Conclusion
Writing a C program to find the square root of a number is a simple yet essential task. By understanding the concept of square roots and following the provided algorithm, you can easily create a program for this purpose. This task also introduces you to using the math library in C, which is crucial for many advanced programming tasks.