C++ Program to Multiply all Elements (Numbers) in an Array

This article includes some programs in C++ that find and prints the multiplication result of all elements in a given array. These are the list of programs available here:

• Multiply all elements in an array of 10 elements
• Multiply all elements in an array of n elements
• Multiply only non-zero elements of an array

Multiply all Elements in an Array of 10 Elements

The question is, write a program in C++ that receives 10 elements for an array to find and print the multiplication result of all the given 10 elements. Here is its answer:

#include<iostream>

using namespace std;
int main()
{
int arr, i, mul=1;
cout<<"Enter 10 Elements for the Array: ";
for(i=0; i<10; i++)
cin>>arr[i];
for(i=0; i<10; i++)
mul = mul*arr[i];
cout<<"\nMultiplication Result of all 10 Elements = "<<mul;
cout<<endl;
return 0;
}

Here is the initial output produced by above C++ program on printing the multiplication result of all elements in a given array:

Now supply any 10 elements say 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and press ENTER to find and print the multiplication result of all these elements as shown in the snapshot given below:

Find Multiplication Result of all Elements in an Array of n Elements

This program allows user to define the size of array along with its elements. That is, program receives the size, then ask to enter all the elements for array of required size to multiply them and then print the multiplication result:

#include<iostream>

using namespace std;
int main()
{
int n, arr, i, m=1;
cout<<"Enter the size for array (max.100): ";
cin>>n;
cout<<"Enter "<<n<<" array elements: ";
for(i=0; i<n; i++)
{
cin>>arr[i];
m *= arr[i];
}
cout<<"\nMultiplication Result = "<<m;
cout<<endl;
return 0;
}

Here is its sample run with user input 5 as size or the value of n and 1, 2, 3, 4, 5 as 5 numbers or elements for the array:

Find Multiplication of only non-zero Array Elements

Since both the program given above gives 0 as result, if any of the element in an array is 0. Because multiplying any number with 0 gives 0 as result. Therefore, let's modify the above program and create a new one that only find and print the multiplication result of only non-zero elements:

#include<iostream>

using namespace std;
int main()
{
int n, arr, i, m=1, chk=0;
cout<<"Enter the size for array (max.100): ";
cin>>n;
cout<<"Enter "<<n<<" array elements: ";
for(i=0; i<n; i++)
{
cin>>arr[i];
if(arr[i]!=0)
{
m *= arr[i];
chk = 1;
}
}
if(chk==1)
cout<<"\nMultiplication Result = "<<m;
else
cout<<endl;
return 0;
}

Here is its sample run with user input 5 as size and 1, 0, 2, 0, 3 as five array elements:

C++ Online Test

« Previous Program Next Program »