数组中所有成对连续元素的乘积
给定一个包含 N 个元素的整数数组。任务是打印所有成对连续元素的乘积。
大小为 N 的数组的成对连续对是(a[i], a[i+1]) 范围从0 到 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
解决方法是遍历数组,计算并打印每一对的乘积(arr[i],arr[i+1])。
下面是这种方法的实现:
C++
// C++ program to print the
// product of the consecutive elements.
#include
using namespace std;
// Function to print pairwise
// consecutive product
void pairwiseProduct(int arr[], int n)
{
int prod = 1;
for (int i = 0; i < n - 1; i++) {
// multiply the alternate numbers
prod = arr[i] * arr[i + 1];
printf(" %d ", prod);
}
}
// Driver Code
int main()
{
int arr[] = { 4, 10, 15, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
pairwiseProduct(arr, n);
return 0;
}
Java
// Java program to print the product
// of the consecutive elements.
import java .io.*;
class GFG
{
// Function to print pairwise
// consecutive product
static void pairwiseProduct(int[] arr,
int n)
{
int prod = 1;
for (int i = 0; i < n - 1; i++)
{
// multiply the alternate numbers
prod = arr[i] * arr[i + 1];
System.out.print(prod + " ");
}
}
// Driver Code
public static void main(String[] args)
{
int[] arr = { 4, 10, 15, 5, 6 };
int n = arr.length;
pairwiseProduct(arr, n);
}
}
// This code is contributed
// by anuj_67..
Python 3
# Python 3 program to print the
# product of the consecutive elements.
# Function to print pairwise
# consecutive product
def pairwiseProduct( arr, n):
prod = 1
for i in range(n - 1) :
# multiply the alternate numbers
prod = arr[i] * arr[i + 1]
print(prod, end = " ")
# Driver Code
if __name__=="__main__":
arr = [ 4, 10, 15, 5, 6 ]
n = len(arr)
pairwiseProduct(arr, n)
# This code is contributed
# by ChitraNayal
C#
// C# program to print the product
// of the consecutive elements.
using System;
class GFG
{
// Function to print pairwise
// consecutive product
static void pairwiseProduct(int[] arr,
int n)
{
int prod = 1;
for (int i = 0; i < n - 1; i++)
{
// multiply the alternate numbers
prod = arr[i] * arr[i + 1];
Console.Write(prod + " ");
}
}
// Driver Code
public static void Main()
{
int[] arr = { 4, 10, 15, 5, 6 };
int n = arr.Length;
pairwiseProduct(arr, n);
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
PHP
Javascript
输出:
40 150 75 30
时间复杂度: O(n)