Determine Perfect Square in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to check whether a number is a perfect square or not using a C program. A perfect square is a number that is the product of an integer multiplied by itself. For example, 9 is a perfect square because 3 * 3 = 9. We will write a program that takes user input and checks whether the number is a perfect square or not.

Getting User Input

In this step, we will take user input for the number to check. Add the following code to the main.c file.

#include<stdio.h>

int main()
{
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

    // Write the code for next steps here

    return 0;
}

Check for Perfect Square

In this step, we will check whether the entered number is a perfect square or not. We will use a for loop to iterate over the numbers from 1 to the entered number. Then we will check if the square of the current number is equal to the entered number. Add the following code to the main.c file.

#include<stdio.h>

int main()
{
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

    for(int i = 1; i <= number; i++)
    {
        if((i*i) == number)
        {
            printf("%d is a perfect square.", number);
            return 0;
        }
    }

    printf("%d is not a perfect square.", number);

    // Write the code for next step here

    return 0;
}

Testing the Program

Now let's test the program. Compile and run the code using the following commands.

gcc main.c -o main
./main

Enter a number to check whether it is perfect square or not.

Full Code

#include<stdio.h>

int main()
{
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

    for(int i = 1; i <= number; i++)
    {
        if((i*i) == number)
        {
            printf("%d is a perfect square.", number);
            return 0;
        }
    }

    printf("%d is not a perfect square.", number);

    return 0;
}

Summary

In this lab, you learned how to check whether a number is a perfect square or not using a C program. We used a for loop to check if the square of each number is equal to the entered number or not. At the end of the program, we printed whether the entered number is a perfect square or not.

Other C Tutorials you may like