Write a function to find the sum of the m largest elements in an array of length
ID: 3911052 • Letter: W
Question
Write a function to find the sum of the m largest elements in an array of length n in C++.
Function name bool sum_top(int a[], int n, int m, int & sum); The return type is bool.
safegaurds if if n ? 0 or m ? 0 or m > n then set sum = 0 and return false.
if the calculation is succesful, return true. the value of the sum is output in the reference &sum.
There are many ways to implement sum top(...).
You may sort the array first then find sum of the largest elements in the sorted array.
main function is also needed.
Explanation / Answer
#include<iostream>
using namespace std;
//swapping method
void swap(int *p, int *y)
{
int temp = *p;
*p = *y;
*y = temp;
}
//sorting method
void bubbleSort(int array[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (array[j] > array[j+1])
swap(&array[j], &array[j+1]);
}
//method to find sum of m largest elements
bool sum_top(int a[], int n, int m, int & sum)
{
//safegaurds
if(n<=0 || m<=0 || m>n)
return false;
//sorting array using bubble sort
bubbleSort(a,n);
//after sorting
//finding sum of m largest elements
int s=0;
n--;
while(m>0)
{
s=s+a[n];
n--;
m--;
}
sum = s;//storing sum in variable
return true;//means successs
}
//test method
int main()
{
int a[] = {2,3,1,8,9,5,6,3,7,4};
int s=0;
if(sum_top(a,10,5,s))
cout<<"Sum is:"<<s<<endl;
return 0;
}
output:
Sum is:35
Process exited normally.
Press any key to continue . . .
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.