Given an array of integers of N elements. The task is to print the product of all of the pairwise consecutive elements.
Pairwise consecutive pairs of an array of size N are (a[i], a[i+1]) for all ranging from 0 to N-2
Input : arr[] = {8, 5, 4, 3, 15, 20}
Output : 40, 20, 12, 45, 300
Input : arr[] = {5, 10, 15, 20}
Output : 50, 150, 300
The solution is to traverse the array and calculate and print the product of every pair (arr[i], arr[i+1]).
Below is the implementation of this approach:
C++
#include <iostream>
using namespace std;
void pairwiseProduct( int arr[], int n)
{
int prod = 1;
for ( int i = 0; i < n - 1; i++) {
prod = arr[i] * arr[i + 1];
printf ( " %d " , prod);
}
}
int main()
{
int arr[] = { 4, 10, 15, 5, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
pairwiseProduct(arr, n);
return 0;
}
|
C
#include <stdio.h>
void pairwiseProduct( int arr[], int n)
{
int prod = 1;
for ( int i = 0; i < n - 1; i++) {
prod = arr[i] * arr[i + 1];
printf ( " %d " , prod);
}
}
int main()
{
int arr[] = { 4, 10, 15, 5, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
pairwiseProduct(arr, n);
return 0;
}
|
Java
import java .io.*;
class GFG
{
static void pairwiseProduct( int [] arr,
int n)
{
int prod = 1 ;
for ( int i = 0 ; i < n - 1 ; i++)
{
prod = arr[i] * arr[i + 1 ];
System.out.print(prod + " " );
}
}
public static void main(String[] args)
{
int [] arr = { 4 , 10 , 15 , 5 , 6 };
int n = arr.length;
pairwiseProduct(arr, n);
}
}
|
Python 3
def pairwiseProduct( arr, n):
prod = 1
for i in range (n - 1 ) :
prod = arr[i] * arr[i + 1 ]
print (prod, end = " " )
if __name__ = = "__main__" :
arr = [ 4 , 10 , 15 , 5 , 6 ]
n = len (arr)
pairwiseProduct(arr, n)
|
C#
using System;
class GFG
{
static void pairwiseProduct( int [] arr,
int n)
{
int prod = 1;
for ( int i = 0; i < n - 1; i++)
{
prod = arr[i] * arr[i + 1];
Console.Write(prod + " " );
}
}
public static void Main()
{
int [] arr = { 4, 10, 15, 5, 6 };
int n = arr.Length;
pairwiseProduct(arr, n);
}
}
|
PHP
<?php
function pairwiseProduct(& $arr , $n )
{
$prod = 1;
for ( $i = 0; $i < $n - 1; $i ++)
{
$prod = $arr [ $i ] * $arr [ $i + 1];
echo ( $prod );
echo ( " " );
}
}
$arr = array (4, 10, 15, 5, 6 );
$n = sizeof( $arr );
pairwiseProduct( $arr , $n );
?>
|
Javascript
<script>
function pairwiseProduct( arr, n)
{
let prod = 1;
for (let i = 0; i < n - 1; i++) {
prod = arr[i] * arr[i + 1];
document.write(prod + " " );;
}
}
let arr = [ 4, 10, 15, 5, 6 ];
let n = arr.length;
pairwiseProduct(arr, n);
</script>
|
Time Complexity: O(n), where n is the length of the given array
Auxiliary Space: O(1), As constant extra space is used.