C program to add all perfect square elements in an array.

CServer Side ProgrammingProgramming

Problem

Write a program to find the sum of perfect square elements in an array.

Given a number of elements in array as input and the sum of all the perfect square of those elements present in the array is output.

Solution

For example,

Input= 1, 2, 3, 4, 5, 9,10,11,16
The perfect squares are 1, 4, 9, 16.
Sum = 1 + 4 + 9 +16 = 30
Output: 30

Algorithm

Refer an algorithm given below to add the perfect square elements in an array.

Step 1 − Read number of elements in array at runtime.

Step 2 − Input the elements.

Step 3 − Declare and initialize the sum=0

Step 4 − Check, whether the array element is a perfect square or not.

Step 5 − If it is a perfect square, then, compute sum=sum+number.

Step 6 − Return sum.

Example

Following is the C program to find the sum of perfect square elements in an array −

#include<stdio.h>
#include<math.h>
int isPerfectSquare(int number){
   int iVar;
   float fVar;
   fVar=sqrt((double)number);
   iVar=fVar;
   if(iVar==fVar)
      return number;
   else
   return 0;
}
int main(){
   int n;
   printf("enter no: of elements:");
   scanf("%d",&n);
   int arr[n];
   int i;
   printf("enter the elements in an array:\n");
   for(i = 0; i < n; i++){
      scanf("%d",&arr[i]);
   }
   int sum = 0;
   for(i = 0; i < n; i++){
      sum = sum + isPerfectSquare(arr[i]);
   }
   printf("sum=%d",sum);
   return 0;
}

Output

When the above program is executed, it produces the following output −

Run 1:
enter no: of elements:5
enter the elements in an array:
1
3
5
9
10
sum=10
Run 2:
enter no: of elements:5
enter the elements in an array:
1
4
9
16
25
sum=55
raja
Published on 26-Mar-2021 12:11:35
Advertisements