Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to find square root of a number

C Code Example — Basic Programs

ADVERTISEMENT

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

  1. Include the standard math library: #include <math.h>.
  2. Declare float variables n and sq.
  3. Read the number from the user.
  4. Use the built-in sqrt(n) function to calculate the square root.
  5. 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.h header 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 -lm to your compile command (e.g., gcc program.c -lm).

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT