Q: Write a C Program to Calculate Square Root of a Positive Number
How To Calculate Square Root of a number in C Programming
We use built-in function sqrt() to calculate square root of a number.
Include Header File math.h for sqrt() function
We must include math.h header file with the help of pre processor directive in the program. sqrt() function is defined in math.h header file.
Source Code for C Program to Find Square root of a number
sqrt function from the
math.h library, and displays the result if the input is valid.
- The program includes the necessary header files:
stdio.hfor input/output operations and
math.hfor mathematical functions.
mainfunction is defined as the entry point of the program.
- Inside the
mainfunction, a variable
doubleis declared to store the input number.
printffunction is used to display a prompt message asking the user to enter a positive number to find its square root.
scanffunction is used to read a double-precision floating-point number from the user and store it in the
ifcondition is used to check if the entered number
numis greater than 0, ensuring it is positive.
- If the condition is true, the
printffunction is used to display the square root of the number. The
%lfformat specifier is used to print the value of
sqrt(num)with two decimal places.
sqrtfunction from the
math.hlibrary is used to calculate the square root of
- If the entered number is not positive, the program will skip the
printfstatement, and no output will be displayed.
return 0;is the last statement that indicates the successful termination of the
mainfunction and the program.