WAP to find square root of a number
Objective
Write a C++ program to find the square root of a number using mathematical functions.
Algorithm / Approach
- Include the
<math.h>(or<cmath>) header file. - Declare an integer
aand a doubleb. - Read the number from the user.
- Call the square root function:
b = sqrt(a). - Print the result.
main.cpp
#include<iostream>
#include<math.h>
using namespace std;
int main() {
int a;
double b;
cout<<"Enter Number: ";
cin>>a;
b = sqrt(a);
cout<<"SQUARE ROOT = "<< b;
return 0;
}
Expected Output
Enter Number: 5 SQUARE ROOT = 2.3607
Explanation of the Program
- The
sqrt()function calculates the principal square root of a number. - Because square roots are rarely perfect integers (e.g., the square root of 5 is 2.236), the function is designed to return a floating-point value. This is why we store the result in a
double.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)