Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Array sum after dividing numbers from previous?
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.
Syntax
float divSum(int arr[], int n);
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
The following C program calculates the sum after dividing each element by its previous element −
#include <stdio.h>
float divSum(int arr[], int n) {
float sum = arr[0];
for (int i = 1; i < n; i++) {
sum += (float)arr[i] / arr[i - 1];
}
return sum;
}
int main() {
int arr[6] = {5, 6, 7, 2, 1, 4};
int n = 6;
printf("Sum: %.4f<br>", divSum(arr, n));
return 0;
}
Sum: 12.1524
How It Works
- The first element (5) is added directly to the sum
- Each subsequent element is divided by the previous element: 6/5 = 1.2, 7/6 = 1.1667, etc.
- All results are accumulated to get the final sum
Conclusion
This algorithm efficiently calculates the sum after dividing each array element by its predecessor. The time complexity is O(n) and space complexity is O(1).
Advertisements
