Array sum after dividing numbers from previous in C?

CServer Side ProgrammingProgramming

Array is a sequence of elements of same data type. in this problem we are going to consider integer array for solving the problem. in this problem we are going to find sum of Elements found by dividing the element from the element proceeding it.

Let’s take a few examples to understand this Problem better −

Example 1 −

Array : 3 , 5 ,98, 345
Sum : 26

Explanation − 3 + 5/3 + 98/5 + 345/98 = 3 + 1 + 19 + 3 = 26

We have divided each element with its preceding element and considered only integer parts of the divisions to find the sum.

Example 2 −

Array : 2, 5 , 8, 11, 43 , 78 , 234
Sum : 13

Explanation − 2 + 2 + 1 + 1 + 3 + 1 + 3 = 13

Algorithm

this Algorithm traverse each element of the array. and divide it by the element preceding it. Then, adds the quotient value to sum variable.

Input : Array - int arr[]
Output : int sum

Step 1: Initialize sum = arr[0]
Step 2: for(i = 1 to size of arr ) follow step 3
Step 3 : sum = sum + (arr[i]/arr[i-0] )
Step 4: print the sum

This is an easy four step algorithm to find the sum of array after dividing numbers from previous numbers. We have initialised the sum by the first element of the array because according to the logic the first element does not have any elements which means it cannot be divided by any element. so taking under consideration for loop create an error because we will be accessing the element at -1 index which is wrong.

Example

Live Demo

#include<stdio.h>
int main() {
int arr[] = { 2, 5 , 8, 11, 43 , 78 , 234 };
int n = sizeof(arr)/sizeof(arr[0]);
int sum = arr[0];
for (int i = 1; i < n; i++) {
sum += arr[i] / arr[i - 1];
}
printf("The sum of array after dividing number from previous numbers is %d \n", sum);
return 0;
}

Output

The sum of array after dividing number from previous number is 13.
Published on 04-Oct-2019 10:40:31