C Code to Find the Sum of Positive Perfect Square Elements in an Array

To Learn sum of perfect square elements in an array

Today we will discuss on program in which we have to find the sum of perfect square elements in an array. An array is given as user input and the sum of all the perfect square elements present in the array is generated as output of the code.
For Example:-Input={2,4,6,9,15},in this input only 4 and 9 is the perfect square of the number.
Output:-{13},the sum of 4 and 9 is 13.
To deal with this problem in C Programming Language.

C Program to find sum of positive perfect square elements in an array

Working:-

  1. Enter the size of array.
  2. Enter the elements of the array .
  3. Initialize sum = 0.
  4. Check if the array element is a perfect square.
  5. If it is a perfect square, sum + = number.
  6. Return sum.

C Program:-

//C Code to print the sum of perfect square elements in an array
#include<stdio.h>
#include<math.h>
    int PerfectSquareEle(int num)
    {
        int i;
        float f;
        f=sqrt((double)num);
        i=f;
        if(i==f)
        return num;
        else
        return 0;
    }
        int main()
        {
            int n;
            printf("Enter the size of array : ");
            scanf("%d",&n);
            int arr[n];
            int j;
            printf("Enter the elements of an array : ");
            for(j = 0; j < n; j++)
            {
                scanf("%d",&arr[j]);
            }
            int sum = 0;
            for(j = 0; j < n; j++)
            {
               sum = sum + PerfectSquareEle(arr[j]);
            }
            printf("Sum of elements which is perfect square number : ");
            printf("%d",sum);
            return 0;
        }
Output
Enter the size of array : 6
Enter the elements of an array : 4
1
3
9
64
5
Sum of elements which is perfect square number : 78