You are given an input array a of type int and length n. You are also given that
ID: 3911027 • Letter: Y
Question
You are given an input array a of type int and length n.
You are also given that the array has no duplicates, i.e. ai 6= aj if i 6= j.
Write a function to sum the m largest elements in an array of length n.
the functions name is bool sum_top(int a[], int n, int m, int & sum);
The function return type is bool.
Safeguard: if n ? 0 or m ? 0 or m > n then set sum = 0 and return false.
If the calculation is sucessful, then return true.
The value of the sum is contained in the output variable sum.
There are many ways to implement sum top. You may sort function and then find the largest element, this will work too.Can not call a ‘black box’ library.
Explanation / Answer
I assume you're saying that the sum of the first m elements in a[] and sum passed as a parameter must be same for the function to return true. The code I've written is in C. You can write the same code in any programming language with the basic structure being the same.
#include <stdio.h>
bool sum_top(int a[], int n, int m, int sum) {
if(n==0 || m==0 || m>n)
return false;
else
{
//BUBBLESORT
int swap,sum1=0;
for (int i= 0 ; i < n - 1; i++)
{
for (int j = 0 ; j < n - i - 1; j++)
{
if (a[j] < a[j+1])
{
swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
}
}
}
for(int i=0;i<m;i++)
{
sum1+=a[i];
}
if(sum==sum1)
return true;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.