In: Computer Science
Write a C++ function that accepts array size and pointers to three arrays a1, a2 and a3 of type float as parameters. It then multiplies a1 and a2 and stored the result in a3. Assume that array multiplication is done by multiplying corresponding array elements, e.g. a3[i] = a1[i] * a2[i] where 0 <= i <= (array size – 1) Write a C++ main program to dynamically create three equal sized float arrays a1, a2 and a3. The size of the arrays is given by the user at run time. The values for array elements for a1 and a2 are also given by the user at run time by entering the values on keyboard when prompted by the program. The program should then call array multiply function to multiply two arrays (a1 * a2) and store the results in array a3. After the array multiplication is computed by the program print the resulting array a3 on the screen. The size of the arrays and values of array elements will be given to you by your GAs.
Code:
#include <iostream>
using namespace std;
void multiply(int n,float *a1,float *a2,float *a3){
//calculating the product for each element
for(int i = 0;i<n;++i){
a3[i] = a1[i]*a2[i];
}
}
// Driver Code
int main()
{
int n;
//user input for size of the array
cout<<"Enter the size of the array : ";
cin>>n;
//declaring arrays
float a1[n];
float a2[n];
float a3[n];
for(int i =0;i<n;++i){
cout<<"Enter value for a1["<<i<<"] and a2["<<i<<"] : ";
cin>>a1[i];
cin>>a2[i];
}
//calling the function to calculate the product
multiply(n,a1,a2,a3);
//printing the result
for(int i = 0;i<n;++i){
cout<<"a3["<<i<<"] = "<<a3[i]<<endl;
}
return 0;
}
output:
code screenshot: