Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to find square root of a number

C++ Code Example — Basic Programs

ADVERTISEMENT

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

  1. Include the <math.h> (or <cmath>) header file.
  2. Declare an integer a and a double b.
  3. Read the number from the user.
  4. Call the square root function: b = sqrt(a).
  5. 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)
ADVERTISEMENT