Write Program to find sum of positive square elements in the array

28 September 2022

Write Program to find sum of positive square elements in the array


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

Given an integer array of size N. Write Program to find sum of positive square elements in the array.

Sample input 1:

4

1 2 3 4

Sample output 1:

30

Explanation :

(1 + 4 + 9 + 16) = 30

Sample input 2:

4

-1 -2 -3 -4

Sample output 2:

30

Explanation :

(1 + 4 + 9 + 16) = 30

 

C Program

#include <stdio.h>

long long int SumOfSquare(int *arr,int n)

{

      long long int sum = 0;

      for(int i = 0 ; i<n ; i++)

      {

            sum = sum + arr[i]*arr[i];

      }

      return sum;

}

 

int main()

{

      int n;          scanf("%d",&n);

      int arr[n];

      for(int i = 0 ; i<n ; i++)

      {

            scanf("%d",&arr[i]);

      }

      printf("%lld",SumOfSquare(arr,n));

      return 0;

}

C++ Program

#include <bits/stdc++.h>

using namespace std;

 

long long int SumOfSquare(int arr[],int n)

{

      long long int sum = 0;

      for(int i = 0 ; i<n ; i++)

      {

            sum = sum + arr[i]*arr[i];

      }

      return sum;

}

 

int main()

{

      int n;          cin>>n;

      int arr[n];

      for(int i = 0 ; i<n ; i++)

      {

            cin>>arr[i];

      }

      cout<<SumOfSquare(arr,n);

      return 0;

}

JAVA Program

import java.util.*;

import java.lang.*;

import java.io.*;

class Main

{

      static long SumOfSquare(int arr[],int n)

    {

      long sum = 0;

      for(int i = 0 ; i<n ; i++)

      {

            sum = sum + arr[i]*arr[i];

      }

      return sum;

    }

      public static void main(String[] args) throws java.lang.Exception

      {

            Scanner sc = new Scanner(System.in);

            int n = sc.nextInt();

            int arr[] = new int[n];

            for(int i = 0 ; i<n ; i++)

            {

                        arr[i] = sc.nextInt();

            }

            System.out.print(SumOfSquare(arr,n));

      }

}

PYTHON Program

def SumOfSquare(arr,n):

    sum = 0

    for i in range(0,n):

        sum = sum + arr[i]*arr[i]

    return sum

 

n = int(input())

arr = list(map(int,input().split(' ')))

print(SumOfSquare(arr,n))


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023
Related Articles

Ask Us Anything !