Home  >  Article  >  Backend Development  >  What is the sum of the arrays after dividing the previous numbers?

What is the sum of the arrays after dividing the previous numbers?

王林
王林forward
2023-09-15 08:21:021199browse

What is the sum of the arrays after dividing the previous numbers?

Here, we will see an interesting question. We will take an array and find the sum by dividing each element by the previous element. 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's look at the algorithm for getting concepts.

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

Chinese translation is:

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

The above is the detailed content of What is the sum of the arrays after dividing the previous numbers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete