This blog is under construction

Friday 12 July 2013

C program to check whether the given number is perfect square or not

Write a C program to check whether the given number is perfect square or not.


  #include <stdio.h>
  #include <math.h>
  int main() {
        int i, ch, value, flag = 0;

        /* choose the method to check for perfect square */
        printf("Method to manipulate:\n");
        printf("1. With Math Function(sqrt)\n");
        printf("2. Without Match Function(sqrt)\n");
        printf("Enter your choice:");
        scanf("%d", &ch);

        /* get the input value */
        if (ch == 1 || ch == 2) {
                printf("Enter your input value:");
                scanf("%d", &value);
        }

        switch (ch) {
                case 1:
                        /*
                         * checking for perfect square
                         * without using built in function
                         */
                        for (i = 1; i <= value; i++) {
                                if (i * i == value) {
                                        flag = 1;
                                        break;
                                }
                        }
                        break;

                case 2:
                        /* check for perfect square using built in func */
                        if (sqrt(value) * sqrt(value) == value)
                                flag = 1;
                        break;

                default:
                        printf("Wrong option!!\n");
                        goto end;
        }

        /* print the results */
        if (flag == 0)
                printf("%d is not a perfect square\n", value);
        else
                printf("%d is a perfect square\n", value);

  end:
        return 0;
  }


Note:
gcc perfectSqr.c -lm => linked math library since we have used math function sqrt().

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Method to manipulate:
  1. With Math Function(sqrt)
  2. Without Match Function(sqrt)
  Enter your choice:2
  Enter your input value:100
  100 is a perfect square



1 comment: