Given an array of integers. Now you need to implement four functions. a) add(int
ID: 3795618 • Letter: G
Question
Given an array of integers. Now you need to implement four functions.
a) add(int arr[]) - should add integer 2 to each element of the array.
b) subtract(int arr[]) - should subtract 1 from each element of the array
c) multiply(int arr[]) - each element of the array should be multiplied by 3
d) divide(int arr[])- each element of the array should be divided by 2
Each of the four functions, take an integer array as its parameter. The return type of the function is also an array.First pass the input array, say x[] to the add function. Get the result of the add function. Pass this result to the subtract function. Get the result from the subtract function. Pass this result to the multiply function and so on. Eg:- arr = add(arr) arr = subtract(arr) arr = multiply(arr) arr = divide(arr) Finally print the array, using a loop.
Explanation / Answer
In C or C++ you can't return arrays, but pointer to arrays. So the program will look like this
#include <iostream>
using namespace std;
int* add(int arr[6]) {
for(int i=0;i<6;i++) {
arr[i]+=2;
}
return arr;
}
int* subtract(int arr[6]) {
for(int i=0;i<6;i++) {
arr[i]-=1;
}
return arr;
}
int* multiply(int arr[6]) {
for(int i=0;i<6;i++) {
arr[i]*=3;
}
return arr;
}
int* divide (int arr[6]) {
for(int i=0;i<6;i++) {
arr[i]/=2;
}
return arr;
}
int main() {
int arr[6]={3,5,7,9,11};
int *a;
a = add(arr);
for(int i=0;i<6;i++) {
arr[i]=*a;
a++;
}
a = subtract(arr);
for(int i=0;i<6;i++) {
arr[i]=*a;
a++;
}
a = multiply(arr);
for(int i=0;i<6;i++) {
arr[i]=*a;
a++;
}
a = divide(arr);
for(int i=0;i<6;i++) {
arr[i]=*a;
a++;
}
for(int i=0;i<6;i++) {
cout<<arr[i]<<" ";
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.