Introduction
In this lab, you will learn how to determine if a given number is a perfect square or not in the C++ programming language. To accomplish this, we will use the sqrt()
method of C++ to calculate the square root of the entered number.
In this lab, you will learn how to determine if a given number is a perfect square or not in the C++ programming language. To accomplish this, we will use the sqrt()
method of C++ to calculate the square root of the entered number.
In this step, you need to include the necessary libraries. The iostream
library is used for input and output. The math.h
library is used for calculating the square root.
#include <iostream>
#include <math.h>
using namespace std;
In this step, the isPerfectSquare()
method is defined, which accepts an integer and returns true if the given number is a perfect square. In this method, we first calculate the square root of the entered number using the sqrt()
method of C++. If the square root of the entered number is an integer, then the entered number is a perfect square.
bool isPerfectSquare(int n)
{
int sr = sqrt(n);
if (sr * sr == n)
return true;
else
return false;
}
In this step, we use the main()
method to read user input and call the isPerfectSquare()
method to check for perfect square. First, we prompt the user to enter a positive integer. Then we call the isPerfectSquare()
method to check if the entered number is a perfect square. If the entered number is a perfect square, we display the square root of the entered number to the user. If the entered number is not a perfect square, we display a message indicating the same.
int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to determine if the entered number is perfect square or not ===== \n\n";
int n;
bool perfect = false;
cout << " Enter a positive integer: ";
cin >> n;
perfect = isPerfectSquare(n);
if (perfect)
{
cout << "\n\nThe entered number " << n << " is a perfect square of the number " << sqrt(n);
}
else
{
cout << "\n\nThe entered number " << n << " is not a perfect square";
}
cout << "\n\n\n";
return 0;
}
To compile and run the code, run the following commands in the terminal of Ubuntu:
$ cd ~/project
$ g++ main.cpp -o main && ./main
Enter a positive integer and press enter. The program will output whether the entered number is a perfect square or not.
In this lab, you learned how to determine if a given number is a perfect square or not in the C++ programming language. You also learned how to use the sqrt()
method of C++ to calculate the square root of the entered number. By following the above steps, you can now create your own program to determine whether a number is a perfect square or not.