Write a program to find the sum of the array and average
Example 1:
Input:
Output: sum=26 , average = 4.333
Approach:
Java
public class SumAndAvgArray {public static void main(String[] args) {int arr[] = { 3, 1, 4, 2, 5, 11 };int sum = sumOfArray(arr);double avg = averageOfArray(arr);System.out.println("Sum " + sum);System.out.printf("Average %.2f", avg);}private static double averageOfArray(int[] arr) {int sum = sumOfArray(arr);double avg = (double) sum / arr.length;return avg;}// Method used for sum of array elementprivate static int sumOfArray(int[] arr) {int sum = 0;// Iterate till endfor (int i = 0; i < arr.length; i++) {sum += arr[i];}return sum;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the sum//of array elementsint sumOfArray(int arr[],int n){//varible to hold//the sumint sum=0;//iterate till the size of arrayfor(int i=0;i<n;i++)sum+=arr[i];//return the sumreturn sum;}//function to find the average//of the given arraydouble averageOfArray(int arr[],int n){int sum=sumOfArray(arr,n);double average=(double)sum/n ;return average;}int main(){int arr[]={3,1,4,2,5,11};int n=sizeof(arr)/sizeof(arr[0]);int sum=sumOfArray(arr,n);double average=averageOfArray(arr,n);cout<<"Sum is "<<sum<<", ";cout<<"Average is "<<average<<"\n";}
No comments:
Post a Comment