C Program to Calculate Square Root of a Positive Number

By | June 29, 2019

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.

C Program to find square root of positive number

C Program to find square root of positive 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

 

/*Input a positive number. 
Find square root of this number
*/
#include<stdio.h>
#include<math.h>
int main()
{
    double num;
    printf("Enter a positive number to find Square Root:");
    scanf("%lf",&num);
    if(num>0)
        printf("Square root of %.2lf is = %.2lf",num, sqrt(num));
    return 0;
}
Explanation of Logic of this Program
In summary, the program prompts the user to enter a positive number, calculates its square root using the sqrt function from the math.h library, and displays the result if the input is valid.
  1. The program includes the necessary header files: stdio.h for input/output operations and math.h for mathematical functions.
  2. The main function is defined as the entry point of the program.
  3. Inside the main function, a variable num of type double is declared to store the input number.
  4. The printf function is used to display a prompt message asking the user to enter a positive number to find its square root.
  5. The scanf function is used to read a double-precision floating-point number from the user and store it in the num variable.
  1. An if condition is used to check if the entered number num is greater than 0, ensuring it is positive.
  2. If the condition is true, the printf function is used to display the square root of the number. The %lf format specifier is used to print the value of num and sqrt(num) with two decimal places.
  3. The sqrt function from the math.h library is used to calculate the square root of num.
  4. If the entered number is not positive, the program will skip the printf statement, and no output will be displayed.
  1. The return 0; is the last statement that indicates the successful termination of the main function and the program.

Loading

Leave a Reply

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