Array sum after dividing numbers from previous?

CServer Side ProgrammingProgramming

Here we will see one interesting problem. We will take one array, then find the sum by taking each element after dividing it by the previous elements. Let us consider an array is {5, 6, 7, 2, 1, 4}. Then the result will be 5 + (6 / 5) + (7 / 6) + (2 / 7) + (1 / 2) + (4 / 1) = 12.15238. Let us see the algorithm to get the concept.

Algorithm

divSum(arr, n)

begin
   sum := arr[0]
   for i := 1 to n-1, do
      sum := sum + arr[i] / arr[i-1]
   done
   return sum
end

Example

#include <iostream>
using namespace std;
float divSum(int arr[], int n){
   float sum = arr[0];
   for(int i = 1; i<n; i++){
      sum += arr[i] / float(arr[i - 1]);
   }
   return sum;
}
int main() {
   int arr[6] = {5, 6, 7, 2, 1, 4};
   int n = 6;
   cout << "Sum : " << divSum(arr, n);
}

Output

Sum : 12.1524
raja
Published on 01-Aug-2019 11:24:29
Advertisements