-4

One of my tasks in this assignment is to add 5 to the maximum value within my array. The professor said to use a void function and to pass a value, which I did. The program adds 5 to the max, 67, to get 72. But, when I printed the array it says 67 is in the array when it should say 72. Is there a way to make it say 72 in the main function, without just adding 5 to the element holding 67 in the main function, but by using void incre(int y)?

Here is the funtion I used to increment the maximum by 5.

void incre(int y){
y+=5;
cout << "The new max after 5 is added is " << y << endl;

}

And here is the code I used to print out the array, which outputs

0 21

1 23

2 67

When it should output

0 21

1 23

2 72

cout << "Elements ------ Values\n";
for (int r = 0; r < array_size; r++){
cout << r << " ------------- " << A[r]<< endl;
}

Also, how do you pass an array to a function using passing by reference? I'm not so sure if I did passing by value or passing by reference in my code here

void fill_array(int x[], int size){
cout << "Enter in the values 23, then 21 and then 67\n";
for (int z=0;z<size; z++) {
    cin >> x[z];
} }

In the main function I put

fill_array(A, array_size);
M. Roshid
  • 3
  • 1

1 Answers1

1

Here is the funtion I used to increment the maximum by 5.

The argument is passed by value to the function. Any changes made to it affect only the local copy of the argument, not the variable in the calling function. If you want to see the change reflected in the calling function, change the argument to be a reference argument.

//            |
//            v
void incre(int& y){
  y+=5;
  cout << "The new max after 5 is added is " << y << endl;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270