
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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. 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
Advertisements