Home >Backend Development >C++ >In C language, sum the numbers in an array after dividing them by the previous number

In C language, sum the numbers in an array after dividing them by the previous number

WBOY
WBOYforward
2023-09-12 09:53:071444browse

In C language, sum the numbers in an array after dividing them by the previous number

An array is a sequence of elements of the same data type. In this question, we will consider using an array of integers to solve the problem. In this problem, we will find the sum of an element by dividing it by its preceding element.

Let us give a few examples to understand this issue better -

Example 1 -

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

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

We divide each element element-wise by its previous element and consider only the integer part of the division to find the sum.

Example 2 -

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

We divide each element by its previous element and only consider divisions to sum the integer part.

Example 2 −

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

Explanation − 2 2 1 1 3 1 3 = 13

Algorithm

This algorithm traverses the array of each element. and divide it by the element before it. Then, add the quotient value to the 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 a simple four step algorithm to find the sum of an array after dividing a number by the previous number. We initialized the sum with the first element of the array because logically the first element does not have any elements, which means it cannot be divided by any element. So, considering that the loop will generate an error because we will access the element at -1 index, this is wrong.

Example

Real-time demonstration

#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 </p><p>", sum);
   return 0;
}

Output

The sum of array after dividing number from previous number is 13.

The above is the detailed content of In C language, sum the numbers in an array after dividing them by the previous number. 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