Product of all pairwise consecutive elements in an Arrays in C++


Given an array arr[n] of n number of integers, the task is to find the product of all pairwise consecutive elements.

Consecutive elements in an array arr[] are, if we are at ith element, i.e. arr[i] then its consecutive element will be either arr[i+1] or arr[i-1], so the product will be arr[i] * arr[i+1] or arr[i] * arr[i-1].

Input 

arr[] = {1, 2, 3, 4}

Output 

2, 6, 12

Explanation 

Splitting into pairs {1,2}, {2, 3}, {3, 4}
Their results will be 1*2 = 2, 2*3 = 6, 3*4 = 12

Input 

arr[] = {9, 5, 1, 2, 6, 10}

Output 

45, 5, 2, 12, 60

Explanation 

Splitting into pairs {9, 5}, {5, 1}, {1, 2}, {2, 6}, {6, 10}
Their results will be 9*5 = 45, 5*1 = 5, 1*2 = 2, 2*6=12, 6*10=60

Approach used below is as follows to solve the problem −

  • Start the loop from 0th element of an array till it is less than n-1.

  • For every i check its i+1, product every i and i+1 print the result.

Algorithm

Start
Step 1→ Declare function to calculate product of consecutive elements
   void product(int arr[], int size)
      Declare int product = 1
      Loop For int i = 0 and i < size – 1 and i++
         Set product = arr[i] * arr[i + 1]
         Print product
      End
Step 2 → In main()
   Declare int arr[] = {2, 4, 6, 8, 10, 12, 14 }
   Declare int size = sizeof(arr) / sizeof(arr[0])
   Call product(arr, size)
Stop

Example

 Live Demo

#include <iostream>
using namespace std;
//functio to find the product of consecutive pairs
void product(int arr[], int size){
   int product = 1;
   for (int i = 0; i < size - 1; i++){
      product = arr[i] * arr[i + 1];
      printf("%d ", product);
   }
}
int main(){
   int arr[] = {2, 4, 6, 8, 10, 12, 14 };
   int size = sizeof(arr) / sizeof(arr[0]);
   printf("product is : ");
   product(arr, size);
   return 0;
}

Output

If run the above code it will generate the following output −

product is : 8 24 48 80 120 168

Updated on: 13-Aug-2020

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements