Studytonight is now part of the GUVI universe. Explore GUVI →
🤩 New Cool Developer Tools for you. Explore →
FREE JavaScript Video Series Start Learning →
Signup/Sign In
Tests
MCQs to test your knowledge.
Compilers
Compilers to execute code in browser.
Index
LAST UPDATED: OCTOBER 12, 2020

C++ Determine Perfect Square Program

Hello Everyone!

In this tutorial, we will demonstrate the logic of determine if the given number is a Perfect Square or not, in the C++ programming language.

Logic:

The sqrt(x) method returns the square root the x.

For a better understanding of its implementation, refer to the well-commented CPP code given below.

Code:

#include <iostream>
#include <math.h>
using namespace std;
// Returns true if the given number is a perfect square
bool isPerfectSquare(int n)
{
 // sqrt() method is defined in the math.h library 
 // to return the square root of a given number
 int sr = sqrt(n); 
 if (sr * sr == n)
 return true;
 else
 return false;
}
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";
 // variable declaration
 int n;
 bool perfect = false;
 // taking input from the command line (user)
 cout << " Enter a positive integer : ";
 cin >> n;
 // Calling a method that returns true if the 
 // number is a perfect square
 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;
}

Output:

C++ perfect square program output

Let's see another number with number 81.

C++ perfect square 2

We hope that this post helped you develop a better understanding of the concept to check for perfect square, in C++. For any query, feel free to reach out to us via the comments section down below.

Keep Learning : )



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.

Learn to Code
Learn and practice coding side-by-side.
NEW
C language Course
115+ coding exercises
Javascript Course
85+ coding exercises

AltStyle によって変換されたページ (->オリジナル) /