Reversed Sum of Pairs
Print the sum of every two consecutive elements in an array starting from the end
Understand the Problem
Problem Statement
You are given an array of N integers. Your task is to compute and print the sum of every two consecutive elements in the array, starting from the last element and moving backwards.
Process the array in pairs from the end, moving towards the beginning. If the array has an odd number of elements, the first element (index 0) will be printed as-is since it has no pair.
Constraints
- 1 ≤ N ≤ 1000
- Each array element is an integer
- Array elements can be positive, negative, or zero
- No additional constraints on individual element values
Examples
4
10 50 30 6090 60Starting from the end: 30+60=90, then 10+50=60. The pairs are processed backwards: (30,60) and (10,50).
5
1 2 3 4 59 7 1Starting from the end: 4+5=9, then 2+3=7, and finally 1 remains unpaired (odd array length), so we print 1.
3
100 -50 25-25 100Starting from the end: -50+25=-25, and 100 remains unpaired (odd array length), so we print 100.
Solution
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
scanf("%d", &n);
int arr[n];
for(int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int i;
for(i = n - 2; i >= 0; i -= 2) {
printf("%d ", arr[i] + arr[i + 1]);
}
if(i == -1) {
printf("%d", arr[0]);
}
return 0;
}Step-by-step explanation:
- Read input: First read n, then read n integers into the array
- Pair processing: Start from index n-2, going backwards by 2 each time
- Sum calculation: For each position i, add arr[i] + arr[i+1] and print with space
- Odd length handling: After loop, if i == -1, it means we have odd number of elements, so print arr[0]
- Return 0: Standard program termination
The key insight is that starting from n-2 and going backwards by 2 ensures we process consecutive pairs from the end.