Calculate and print the total sum, mean, sum of all even numbers & odd numbers in an array using c++


Program to print sum of even numbers, sum of odd numbers, total sum of all elements in an array and mean of array

        Take the array size and its elements from the user. Using loop check each element is even or odd if the array element is even_add it to the even_sum and if it is odd add that element to the odd sum. To find the total sum add the even_sum and odd_sum. Calculate the mean by dividing the total sum by the size of the array. Finally print the required data. 


Code

    #include<bits/stdc++.h>

    using namespace std;


    int main()

    {


int n;                                                 //size of array

cin>>n;                                               //Reading size

int a[n];                                                 //array declaration


for(int i=0;i<n;i++){                                   //Reading the array

            cin>>a[i];

    }


int sum=0;                                        //to store total sum

int evensum=0;                              //to store sum of even numbers

int oddsum=0;                              //to store sum of odd numbers

int mean=0;                               //to store mean


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

            if(a[i]%2==0){

                evensum=evensum+a[i];                     //if even gets added to evensum

            }

            else{

                oddsum=oddsum+a[i];                      //if odd gets added to oddsum

            }

}


        //total sum is simply calculated by adding even and odd sums

sum=evensum+oddsum; 


        //mean of the array

        mean=sum/n;


        //printing the required data

cout<<"The sum of all even numbers of given array is: "<<evensum<<endl;

cout<<"The sum of all odd numbers of given array is: "<<oddsum<<endl;

cout<<"The total sum of all elements of given array is: "<<sum<<endl;

cout<<"The mean of array is "<<mean<<endl;


return 0;

}


Input

5
1 2 3 4 5

Output

The sum of all even numbers of given array is: 6
The sum of all odd numbers of given array is: 9
The total sum of all elements of given array is: 15
The mean of array is 3

Post a Comment

0 Comments