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
Array sum after dividing numbers from previous in C?
In C programming, we can calculate the sum of an array where each element (except the first) is divided by its preceding element. This problem involves integer division, where we only consider the quotient part of the division.
Syntax
sum = arr[0]; for(i = 1; iAlgorithm
The algorithm traverses each element of the array and divides it by the element preceding it. Then, it adds 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-1]) Step 4: print the sumExample 1
Array: 3, 5, 98, 345 Sum: 26Explanation − 3 + 5/3 + 98/5 + 345/98 = 3 + 1 + 19 + 3 = 26
Example 2
Array: 2, 5, 8, 11, 43, 78, 234 Sum: 13Explanation − 2 + 2 + 1 + 1 + 3 + 1 + 3 = 13
Implementation
#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]; printf("Array elements: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("
"); for (int i = 1; i < n; i++) { sum += arr[i] / arr[i - 1]; } printf("The sum of array after dividing numbers from previous numbers is %d
", sum); return 0; }Array elements: 2 5 8 11 43 78 234 The sum of array after dividing numbers from previous numbers is 13How It Works
We initialize the sum with the first element
arr[0]since it has no preceding element to divide by. The loop starts from index 1 and performs integer division of each element by its previous element, adding the quotient to the running sum.Key Points
- The first element is added directly to the sum as it has no preceding element
- Integer division automatically truncates the decimal part
- Division by zero should be avoided in real applications
Conclusion
This approach efficiently calculates the sum by performing integer division of consecutive array elements. The time complexity is O(n) and space complexity is O(1).
