Determine Perfect Square in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to determine whether a number is a perfect square using the C programming language. A perfect square is a number that can be expressed as the product of an integer multiplied by itself. For example, 16 is a perfect square because it equals 4 × 4, and 25 is a perfect square because it equals 5 × 5.

By the end of this lab, you will understand the concept of perfect squares and be able to write a C program that checks if a user-provided number is a perfect square or not.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("C")) -.-> c/BasicsGroup(["Basics"]) c(("C")) -.-> c/ControlFlowGroup(["Control Flow"]) c(("C")) -.-> c/FileHandlingGroup(["File Handling"]) c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c/BasicsGroup -.-> c/variables("Variables") c/ControlFlowGroup -.-> c/if_else("If...Else") c/ControlFlowGroup -.-> c/for_loop("For Loop") c/FileHandlingGroup -.-> c/create_files("Create Files") c/UserInteractionGroup -.-> c/user_input("User Input") c/UserInteractionGroup -.-> c/output("Output") subgraph Lab Skills c/variables -.-> lab-123221{{"Determine Perfect Square in C"}} c/if_else -.-> lab-123221{{"Determine Perfect Square in C"}} c/for_loop -.-> lab-123221{{"Determine Perfect Square in C"}} c/create_files -.-> lab-123221{{"Determine Perfect Square in C"}} c/user_input -.-> lab-123221{{"Determine Perfect Square in C"}} c/output -.-> lab-123221{{"Determine Perfect Square in C"}} end

Understanding Perfect Squares

Before we start coding, let us understand what a perfect square is and how we can determine if a number is a perfect square.

A perfect square is a number that is the square of an integer. In other words, it is a number that can be written as n², where n is an integer.

Examples of perfect squares:

  • 1 = 1² (1 × 1)
  • 4 = 2² (2 × 2)
  • 9 = 3² (3 × 3)
  • 16 = 4² (4 × 4)
  • 25 = 5² (5 × 5)

To determine if a number is a perfect square, we can check if there exists an integer whose square equals the given number.

Let us create a directory for our project and navigate into it:

mkdir -p ~/project/perfect-square
cd ~/project/perfect-square
Create a directory

Now, let us create a new C file for our program:

  1. In the WebIDE, navigate to the file explorer panel on the left side.
  2. Right-click on the perfect-square folder and select "New File".
  3. Name the file perfect_square.c and press Enter.

Creating the Basic Program Structure

Now let us create the basic structure of our C program. We need to include the necessary header files and set up the main function.

Open the perfect_square.c file in the WebIDE by clicking on it in the file explorer panel. Then add the following code:

#include <stdio.h>

int main() {
    int number;

    // Prompt user for input
    printf("Enter a number to check if it's a perfect square: ");
    scanf("%d", &number);

    // We will add code to check for perfect square in the next step

    return 0;
}

Let us understand the code:

  1. #include <stdio.h> - This includes the standard input-output library, which provides functions like printf and scanf.
  2. int main() - This is the main function where program execution begins.
  3. int number; - We declare an integer variable to store the user input.
  4. printf("Enter a number..."); - This displays a prompt to the user.
  5. scanf("%d", &number); - This reads an integer input from the user and stores it in the number variable. The & operator is used to get the memory address of the variable where the input will be stored.

Save the file by pressing Ctrl+S or by clicking on File > Save.

Implementing the Perfect Square Check Algorithm

Now let us implement the logic to check if the number entered by the user is a perfect square. There are several ways to check if a number is a perfect square. We will use a simple approach where we check if any integer from 1 to the number has a square equal to the number.

Update your perfect_square.c file with the following code:

#include <stdio.h>

int main() {
    int number;
    int isPerfectSquare = 0;  // Flag to indicate if number is perfect square

    // Prompt user for input
    printf("Enter a number to check if it's a perfect square: ");
    scanf("%d", &number);

    // Check if number is negative
    if (number < 0) {
        printf("%d is negative, and negative numbers cannot be perfect squares.\n", number);
        return 0;
    }

    // Check if the number is a perfect square
    for (int i = 0; i <= number; i++) {
        if (i * i == number) {
            isPerfectSquare = 1;
            printf("%d is a perfect square. It is %d squared.\n", number, i);
            break;  // Exit the loop once we find the answer
        }

        // Optimization: If i*i exceeds number, no need to check further
        if (i * i > number) {
            break;
        }
    }

    // If not a perfect square, inform the user
    if (isPerfectSquare == 0) {
        printf("%d is not a perfect square.\n", number);
    }

    return 0;
}

Let us understand the new code:

  1. We added an isPerfectSquare flag to track whether we found the number to be a perfect square.
  2. We check if the number is negative, since negative numbers cannot be perfect squares.
  3. We use a for loop to iterate from 0 to the number.
  4. Inside the loop, we check if i * i equals the number. If it does, we set our flag, print a message, and exit the loop.
  5. We added an optimization: if i * i exceeds the number, we can stop checking because all subsequent values will also exceed the number.
  6. Finally, if the flag is still 0, we inform the user that the number is not a perfect square.

Save the file (Ctrl+S or File > Save).

Compiling and Testing the Program

Now that we have completed the code for checking perfect squares, let us compile and test it. We will use the GCC compiler to compile our C program.

Navigate to the directory containing our code (if you're not already there):

cd ~/project/perfect-square

Compile the program:

gcc perfect_square.c -o perfect_square

This command compiles perfect_square.c and creates an executable file named perfect_square. If the compilation is successful, you will not see any output.

Now let us run the program:

./perfect_square
Run the program

The program will prompt you to enter a number. Let us test with different inputs:

  1. Enter a perfect square number, such as 16.
    Output should be: 16 is a perfect square. It is 4 squared.

  2. Enter a non-perfect square number, such as 10.
    Output should be: 10 is not a perfect square.

  3. Enter a negative number, such as -4.
    Output should be: -4 is negative, and negative numbers cannot be perfect squares.

You can run the program multiple times to test with different inputs.

Let us also try an edge case, the number 0:

./perfect_square

Enter 0 when prompted.
Output should be: 0 is a perfect square. It is 0 squared.

Congratulations! You have successfully created a C program that checks if a number is a perfect square.

Summary

In this lab, you learned how to create a C program that determines whether a number is a perfect square. Here are the key concepts covered:

  1. Perfect squares are numbers that can be expressed as the square of an integer.
  2. Basic C programming concepts including variables, conditional statements, and loops.
  3. Taking user input using scanf and displaying output using printf.
  4. Using a loop to check if a number is a perfect square by testing each possible value.
  5. Optimizing the solution by breaking out of the loop when necessary.
  6. Handling edge cases like negative numbers and zero.

This lab demonstrated how mathematical concepts can be implemented in programming. You can extend this program by adding more features, such as finding the next perfect square after a given number or checking if a number is a cube (n³) instead of a square.