How to find the perfect square elements in an array with C++

1 Answer

0 votes
#include <iostream>
#include <cmath>
 
bool is_perfect_square(double n) {
   double sq = sqrt(n);
 
   return ((sq - floor(sq)) == 0);
}
 
int main()
{
    int array[] = {7, 8, 9, 0, 36};
    int len = sizeof(array)/sizeof(array[0]);

    for (int i = 0; i < len; i++) {
        if (is_perfect_square(array[i])) {
            std::cout << array[i] << " : Yes" << "\n";
        }
        else {
            std::cout << array[i] << " : No" << "\n";
        }
    }
 
    return 0;
}
 
 
 
 
/*
run:
 
7 : No
8 : No
9 : Yes
0 : Yes
36 : Yes
 
*/

 



answered Sep 23, 2021 by avibootz
edited Sep 23, 2021 by avibootz

Related questions

1 answer 192 views
1 answer 115 views
1 answer 127 views
1 answer 173 views
1 answer 163 views
1 answer 149 views
1 answer 196 views
...