Write a program that takes an array of 10 integer numbers and calcula.docx
1. Write a program that takes an array of 10 integer numbers and
calculates the average and the sum of the array using two
different functions. Declare and write a function called
calcavg. Returns a double, passes the 1D array. Calcavg adds
the 10 elements of the array and divides by 10 to return the
average. Assume there are always 10 elements. Calcavg does
not display any result. Declare and write a function called
calcsum. Returns void. Passes the 1D array and an integer
variable by reference. Sums the 10 elements of the array and
sets the summation to the variable passed by reference. Calcsum
does not display any result. Write a program that has the
appropriate headers and variable declarations. The program
should create an integer 1D array, nums of 10 elements
containing the numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. Please add
several comments throughout your program and functions. The
main program should display the elements of the array using a
for loop. The display should look exactly as shown below. Use
field width manipulators. Call the two functions and display the
average and sum of the elements of the array using statements
in the main function. The terminal window should look exactly
as shown.
Solution
#include <iostream>
using namespace std;
//declare and define calcavg function with parameter array nums
double calcavg(int nums[])
{ int sum=0;
2. for(int i=0;i<10;i++)
sum=sum+nums[i]; //sum is perform on array element
return((double)sum/10); // double is used for type casting
and returns
}
//function calcsum for calculating sum of array elements
void calcsum(int nums[],int &s)
{ int sum=0;
for(int i=0;i<10;i++)
sum=sum+nums[i];
s=sum;
}
int main()
{
int a[10]={1,2,3,4,5,6,7,8,9,10}; //array declaration
int s=0;
cout<<"The elements of nums are:"<<endl;
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
cout<<"The average of nums is "<<calcavg(a)<<endl;
calcsum(a,s);
cout<<"The sum of nums is "<<s<<endl;