Write a program to find the sum of adjacent pairs in an array in C/C++.
Example,
Input 1 2 2 3 4 5 Output 3 4 5 7 9
The program is very simple. We traverse each element of the array (except for the first element) and print the sum of the current element and the previous element.
Steps
- Let the input array be arr[0..N-1]. The size of array is N.
- Set i = 1.
- Repeat the following steps while i < N
- Print arr[i] + arr[i-1]
- i = i + 1
- Terminate the program.
#include<stdio.h>
void sum_adjacent_pairs(int *arr, int n){
int i = 1;
while(i<n){
printf("%d ", arr[i] + arr[i - 1]);
++i;
}
printf("\n");
}
int main() {
int arr[100];
int i,n;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter Array: ");
for(i = 0;i<n;++i){
scanf("%d", &arr[i]);
}
printf("\nSum of Adjacent Pairs: ");
sum_adjacent_pairs(arr, n);
return 0;
}
Output
Enter number of elements: 6
Enter Array: 1 2 2 3 4 5
Sum of Adjacent Pairs: 3 4 5 7 9
We can also implement the same program using recursion. Each recursive call prints sum of one pair. After printing the sum, we move to the next element and again call the recursive function. The program is self-explanatory.
Program to find the sum of adjacent pairs using recursion
#include<stdio.h>
void sum_adjacent_pairs(int* arr, int n, int i) {
if (i >= n) return;
printf("%d ", arr[i] + arr[i - 1]);
sum_adjacent_pairs(arr, n, i + 1);
}
int main() {
int arr[100];
int i, n;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter Array: ");
for (i = 0; i < n; ++i) {
scanf("%d", &arr[i]);
}
printf("\nSum of Adjacent Pairs: ");
sum_adjacent_pairs(arr, n, 1);
return 0;
}
Output
Enter number of elements: 7
Enter Array: 1 4 3 2 5 6 1
Sum of Adjacent Pairs: 5 7 5 7 11 7
Read
- C Program to print all alphabets using pointer
- Reverse Array ( Recursion and without Recursion )
- C Program to Swap first half and second half of an array