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

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,037 questions

40,783 answers

573 users

How to sum the perfect square elements in an array with Java

1 Answer

0 votes
public class MyClass {
    public static boolean is_perfect_square(double n) {   
       double sq = Math.sqrt(n); 
        
       return ((sq - Math.floor(sq)) == 0); 
    } 
     
    public static void main(String args[]) {
        int arr[] = { 7, 8, 9, 0, 36 };
        int sum = 0;
        
        for (int i = 0; i < arr.length; i++) {
            if (is_perfect_square(arr[i])) {
                System.out.println(arr[i] + " : Yes"); 
                sum += arr[i];
            }
            else {
                System.out.println(arr[i] + " : No"); 
            }
        }
        System.out.println("Sum = " + sum); 
    }
}
 
 
 
 
/*
run:
 
7 : No
8 : No
9 : Yes
0 : Yes
36 : Yes
Sum = 45
 
*/

 





answered Sep 23, 2021 by avibootz

Related questions

1 answer 44 views
1 answer 46 views
1 answer 61 views
1 answer 61 views
1 answer 71 views
...