Introduction
In this lab, you will learn how to determine if a given number is a perfect square in C++. A perfect square is a number that can be expressed as the product of an integer with itself. For example, 1, 4, 9, 16, and 25 are perfect squares because they can be expressed as 1×1, 2×2, 3×3, 4×4, and 5×5 respectively.
We will create a C++ program that uses the sqrt() function from the standard library to calculate the square root of a number and determine if it is a perfect square. This lab will introduce you to basic C++ programming concepts including functions, conditional statements, and mathematical operations.
Create a New C++ File and Include Necessary Libraries
In this step, we will create a new C++ file and include the necessary libraries for our program.
First, let's create a new file named main.cpp in the project directory:
- In the WebIDE, click on the Explorer icon in the left sidebar
- Right-click on the
projectfolder and select "New File" - Name the file
main.cppand press Enter
Now, let's add the necessary libraries to our program. We need two main libraries:
iostream: This library provides functionality for input and output operationscmath: This library contains mathematical functions, including thesqrt()function that we will use
Add the following code to your main.cpp file:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << "\nWelcome to the Perfect Square Checker Program\n\n";
// We will add more code here in the next steps
return 0;
}
This code:
- Includes the required libraries
- Uses the
namespace stdto avoid having to writestd::before standard library functions - Creates a basic
main()function that displays a welcome message - Returns 0 to indicate successful program execution
Save your file by pressing Ctrl+S or selecting File > Save from the menu.
Implement the Perfect Square Checking Function
Now, we will create a function that determines whether a number is a perfect square. A perfect square has an integer square root. For example, 16 is a perfect square because its square root is exactly 4.
Add the following function above the main() function in your main.cpp file:
bool isPerfectSquare(int number) {
// Calculate the square root of the number
double squareRoot = sqrt(number);
// Convert the square root to an integer
int intSquareRoot = static_cast<int>(squareRoot);
// A number is a perfect square if squaring its integer square root gives the original number
return (intSquareRoot * intSquareRoot == number);
}
Let's understand how this function works:
- The function takes an integer parameter
numberand returns a boolean value (true or false) - We use the
sqrt()function from thecmathlibrary to calculate the square root of the input number - We convert the square root to an integer using
static_cast<int>(), which removes any decimal portion - If the number is a perfect square, then multiplying the integer square root by itself will give the original number
- The function returns
trueif the number is a perfect square, andfalseotherwise
For example:
- For number 16:
- sqrt(16) = 4.0
- Converting 4.0 to an integer gives 4
- 4 × 4 = 16, which equals the original number, so 16 is a perfect square
- For number 10:
- sqrt(10) ≈ 3.16227766
- Converting 3.16227766 to an integer gives 3
- 3 × 3 = 9, which does not equal the original number, so 10 is not a perfect square
Your complete code so far should look like this:
#include <iostream>
#include <cmath>
using namespace std;
bool isPerfectSquare(int number) {
// Calculate the square root of the number
double squareRoot = sqrt(number);
// Convert the square root to an integer
int intSquareRoot = static_cast<int>(squareRoot);
// A number is a perfect square if squaring its integer square root gives the original number
return (intSquareRoot * intSquareRoot == number);
}
int main() {
cout << "\nWelcome to the Perfect Square Checker Program\n\n";
// We will add more code here in the next step
return 0;
}
Save your file before proceeding to the next step.
Complete the Main Function with User Input and Output
Now, let's enhance the main() function to:
- Prompt the user to enter a number
- Get the user's input
- Use our
isPerfectSquare()function to check if the number is a perfect square - Display an appropriate message based on the result
Update your main() function with the following code:
int main() {
cout << "\nWelcome to the Perfect Square Checker Program\n\n";
int userNumber;
// Prompt the user to enter a number
cout << "Please enter a positive integer: ";
cin >> userNumber;
// Check if the entered number is a perfect square
if (isPerfectSquare(userNumber)) {
int squareRoot = static_cast<int>(sqrt(userNumber));
cout << "\nThe number " << userNumber << " is a perfect square!" << endl;
cout << "It is equal to " << squareRoot << " × " << squareRoot << endl;
} else {
cout << "\nThe number " << userNumber << " is not a perfect square." << endl;
}
cout << "\nThank you for using the Perfect Square Checker Program!\n" << endl;
return 0;
}
Let's understand what this code does:
- We declare an integer variable
userNumberto store the user's input - We prompt the user to enter a positive integer using
cout - We read the user's input using
cinand store it inuserNumber - We call our
isPerfectSquare()function withuserNumberas the argument - If the number is a perfect square:
- We calculate its square root and store it in
squareRoot - We display a message indicating that the number is a perfect square
- We show what two identical integers multiply to give the original number
- We calculate its square root and store it in
- If the number is not a perfect square:
- We display a message indicating that the number is not a perfect square
- Finally, we display a thank-you message and return from the
main()function
Your complete program should now look like this:
#include <iostream>
#include <cmath>
using namespace std;
bool isPerfectSquare(int number) {
// Calculate the square root of the number
double squareRoot = sqrt(number);
// Convert the square root to an integer
int intSquareRoot = static_cast<int>(squareRoot);
// A number is a perfect square if squaring its integer square root gives the original number
return (intSquareRoot * intSquareRoot == number);
}
int main() {
cout << "\nWelcome to the Perfect Square Checker Program\n\n";
int userNumber;
// Prompt the user to enter a number
cout << "Please enter a positive integer: ";
cin >> userNumber;
// Check if the entered number is a perfect square
if (isPerfectSquare(userNumber)) {
int squareRoot = static_cast<int>(sqrt(userNumber));
cout << "\nThe number " << userNumber << " is a perfect square!" << endl;
cout << "It is equal to " << squareRoot << " × " << squareRoot << endl;
} else {
cout << "\nThe number " << userNumber << " is not a perfect square." << endl;
}
cout << "\nThank you for using the Perfect Square Checker Program!\n" << endl;
return 0;
}
Save your file before proceeding to the next step.
Compile and Test the Program
Now that we have completed our C++ program, it's time to compile and run it. Compiling converts our human-readable code into a machine-executable program.
Compile the Program
Open a terminal in the WebIDE by clicking on "Terminal" in the menu and selecting "New Terminal".
In the terminal, navigate to the project directory:
cd ~/project
Compile the program using the g++ compiler:
g++ main.cpp -o perfect_square_checker
This command tells the compiler to:
- Take our source file
main.cpp - Compile it into an executable named
perfect_square_checker
If the compilation is successful, you will not see any output. If there are errors, read the error messages, fix the issues in your code, and try compiling again.
Run the Program
After successfully compiling the program, run it using:
./perfect_square_checker
The program will start and prompt you to enter a positive integer.
Test with Different Inputs
Let's test our program with different inputs to verify it works correctly:
Test Case 1: A Perfect Square
Enter 16 when prompted. You should see output similar to:
Please enter a positive integer: 16
The number 16 is a perfect square!
It is equal to 4 × 4
Thank you for using the Perfect Square Checker Program!
Test Case 2: Not a Perfect Square
Run the program again and enter 10 when prompted. You should see output similar to:
Please enter a positive integer: 10
The number 10 is not a perfect square.
Thank you for using the Perfect Square Checker Program!
Test Case 3: Another Perfect Square
Run the program again and enter 25 when prompted. You should see output similar to:
Please enter a positive integer: 25
The number 25 is a perfect square!
It is equal to 5 × 5
Thank you for using the Perfect Square Checker Program!
By testing with different inputs, you can verify that your program correctly identifies perfect squares and non-perfect squares.
Congratulations! You have successfully created a C++ program that determines whether a number is a perfect square.
Summary
In this lab, you successfully created a C++ program that determines whether a number is a perfect square. Let's review what you accomplished:
You learned how to include necessary libraries in a C++ program:
iostreamfor input and output operationscmathfor mathematical functions likesqrt()
You implemented the
isPerfectSquare()function that uses a mathematical approach to determine if a number is a perfect square:- Calculate the square root of the number
- Check if squaring the integer part of the square root equals the original number
You created a user-friendly interface in the
main()function that:- Prompts the user to enter a number
- Uses the
isPerfectSquare()function to check if the number is a perfect square - Displays an appropriate message based on the result
You compiled and tested your program with different inputs to verify its functionality.
Through this lab, you gained practical experience with several important C++ programming concepts:
- Creating and calling functions
- Using conditional statements (if-else)
- Working with user input and output
- Performing type conversions
- Using mathematical functions from the standard library
- Compiling and running a C++ program
You can further enhance this program by adding features such as:
- Input validation to ensure the user enters a positive integer
- The ability to check multiple numbers without restarting the program
- Finding the closest perfect square to a non-perfect square number
By continuing to practice and build upon these fundamental concepts, you will develop stronger C++ programming skills that you can apply to more complex problems.



