Program for multiplication of array elements

link 0

We are given an array and we have to calculate the product of an array using both iterative and recursive method.

Examples:

Input : array[] = {1, 2, 3, 4, 5, 6}
Output : 720
Here, product of elements = 1*2*3*4*5*6 = 720

Input : array[] = {1, 3, 5, 7, 9}
Output : 945

Iterative Method : 
We initialize result as 1. We traverse array from left to right and multiply elements with result.

// Iterative C++ program to multiply array elements
#include<iostream>
using namespace std;
// Function to calculate the product of the array
int multiply(int array[], int n)
{
    int pro = 1;
    for (int i=0;i<n;i++)   
        pro = pro * array[i];
    return pro;
}
// Driver function
int main()
{
    int array[] = {1, 2, 3, 4, 5, 6};
    int n = sizeof(array)/sizeof(array[0]);
    //Function call to calculate product
    cout<<multiply(array, n);
    return 0;
}

Output:

720

 

Recursive Method :

// Recursive C++ program to multiply array elements
#include<iostream>
using namespace std;
// Function to calculate the product of
// array using recursion
int multiply(int a[], int n)
{
    // Termination condition
    if (n==0)
        return(a[n]);
    else
        return (a[n] * multiply(a,n-1));
}
// Driver function
int main()
{
    int array[] = {1, 2, 3, 4, 5, 6};
    int n = sizeof(array)/sizeof(array[0]);
    //Function call to calculate the product
    cout << multiply(array, n-1) << endl;
    return 0;
}
 720


Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits: http://www.geeksforgeeks.org
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar