easy
0 views

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

Example 1
Input
4
10 50 30 60
Output
90 60
Explanation

Starting from the end: 30+60=90, then 10+50=60. The pairs are processed backwards: (30,60) and (10,50).

Example 2
Input
5
1 2 3 4 5
Output
9 7 1
Explanation

Starting from the end: 4+5=9, then 2+3=7, and finally 1 remains unpaired (odd array length), so we print 1.

Example 3
Input
3
100 -50 25
Output
-25 100
Explanation

Starting 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;
}
Time:O(n)
Space:O(n)
Approach:

Step-by-step explanation:

  1. Read input: First read n, then read n integers into the array
  2. Pair processing: Start from index n-2, going backwards by 2 each time
  3. Sum calculation: For each position i, add arr[i] + arr[i+1] and print with space
  4. Odd length handling: After loop, if i == -1, it means we have odd number of elements, so print arr[0]
  5. 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.

Visual Explanation

Loading diagram...