C Program to find sum of perfect square elements in an array using pointers.

CServer Side ProgrammingProgramming

Problem

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

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 find the sum of perfect square elements in an array by using pointers. 

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 − Declare a pointer variable. 

Step 5 − Check, whether the array element is a perfect square or not by using a pointer variable 

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

Step 7 − Return sum.

Example

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

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int sumPositive(int n,int *a){
   int i,sum=0,m;
   for(i=0;i<n;i++){
      m=sqrt(*(a+i));
      if(pow(m,2)==*(a+i)){
         sum+=*(a+i);
      }
   }
   return sum;
}
int main(){
   int i,*a,n;
   printf("Enter the size of array:\n");
   scanf("%d",&n);
   a=(int*)malloc(n*sizeof(int));
   printf("Enter the elements of array:\n");
   for(i=0;i<n;i++){
      scanf("%d",a+i);
   }
   printf("Sum of positive square elements is %d",sumPositive(n,a));
   return 0;
}

Output

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

Enter the size of array:
10
Enter the elements of array:
1
2
3
4
5
6
7
8
9
10
Sum of positive square elements is 14
raja
Published on 26-Mar-2021 07:44:19
Advertisements