Adsense 728 * 15

Search

Custom Search

Program to Check Perfect Square in C, C++

Write a C, C++ program to check whether a input number is perfect square or not. We can solve this question without using in-built function sqrt().

C, C++ programming questions for practice.

Find cube of a number

Perfect Square

A number is a perfect square if it is the square of an integer.

For example - 25 is a perfect square. You can write it as 5 * 5 which the square of an integer. But 17 is not a perfect square.


C Program to Check Perfect Square


#include <stdio.h>

int main(void) {

   int num, flag = 0;
 
   printf ("Enter a number \n");
   scanf ("%d", &num);
 
   for (int i = 1; i <= num; i++) {
  
                 
      if ( i * i == num) {
   
         flag = 1;
         break;
      }
  
      if ( i * i > num) {
   
        break;
   
      } 
   }
 
   if (flag) {
  
      printf (" %d is a perfect square", num);
  
    } else {
  
      printf (" %d is not a perfect square", num);
    }

   return 0;
}



Output :

Enter a number :  4

4 is a perfect square


Enter a number : 7

7 is not a perfect square

C++ Program to Check Perfect Square


#include <iostream>
using namespace std;

int main() {
 
   int num, flag = 0;
 
   cout << "Enter a number \n";
   cin >> num;
 
   for (int i = 1; i <= num; i++) {
  
     if ( i * i == num) {
   
         flag = 1;
         break;
     }
  
     if ( i * i > num) {
   
        break;
   
      } 
   }
 
   if (flag) {
  
     cout << num << " is a perfect square";
  
   } else {
  
     cout << num << " is not a perfect square";
 }
 
 return 0;
}

1 comment:

  1. Useful post.This perfect square program is really interesting.Continue sharing more programs.
    Regards,
    C Training in Chennai | C++ Training in Chennai | C and C++ institute

    ReplyDelete