Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,990 questions

51,935 answers

573 users

How to sum 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]);
    int sum = 0;

    for (int i = 0; i < len; i++) {
        if (is_perfect_square(array[i])) {
            std::cout << array[i] << " : Yes" << "\n";
            sum += array[i];
        }
        else {
            std::cout << array[i] << " : No" << "\n";
        }
    }

    std::cout << "sum = " << sum;

    return 0;
}




/*
run:

7 : No
8 : No
9 : Yes
0 : Yes
36 : Yes
sum = 45

*/
 
 
 

 



answered Sep 23, 2021 by avibootz

Related questions

1 answer 130 views
1 answer 143 views
1 answer 100 views
1 answer 119 views
1 answer 136 views
1 answer 91 views
1 answer 100 views
...