C Program to find square root of a number
Objective
Write a C program to find the square root of a number using the math library.
Algorithm / Approach
- Include the standard math library:
#include <math.h>. - Declare float variables
nandsq. - Read the number from the user.
- Use the built-in
sqrt(n)function to calculate the square root. - Print the result.
main.c
#include<stdio.h>
#include<math.h>
int main( ) {
float n, sq;
printf("Enter Value for N : ");
scanf("%f",&n);
sq = sqrt(n);
printf("SQUARE ROOT IS : %f\n",sq);
return 0;
}
Expected Output
Enter Value for N : 16 SQUARE ROOT IS : 4.0
Explanation of the Program
- C provides a vast mathematical library via the
math.hheader file. - The
sqrt()function takes a floating-point number as an argument and returns its exact square root. - If you attempt to compile this using the GCC compiler on Linux, you must link the math library by appending
-lmto your compile command (e.g.,gcc program.c -lm).
Complexity
Time Complexity
O(1)
Space Complexity
O(1)