Analyze the following program and write down the output.
# include <iostream>
using namespace std;
void modifyArray( int [ ], int );
void modifyElement ( int );
int main( )
{
const int arraySize = 8;
int a[arraySize] = { 2, -2, 10, -3, -1 ,0, 10, -5 };
modifyArray ( a, arraySize);
for ( int i =0; i < arraySize; i++)
cout << a[i] << ‘ ’;
modifyElement ( a[4] );
for ( int i =0; i < arraySize; i++)
cout << a[i] << ‘ ’;
cout << endl;
return 0;
}
void modifyArray ( int b[ ], int sizeOfArray )
{
for ( int k = 0; k < sizeOfAarray; k++)
b[k] *=2;
}
void modifyElement ( int e )
{
e *= 2;
}
4 -4 20 -6 -2 0 20 -10 4 -4 20 -6 -2 0 20 -10
Explanation:
void modifyArray ( int b[ ], int sizeOfArray )
{
for ( int k = 0; k < sizeOfAarray; k++)
b[k] *=2;
}
modifyArray method recieves an array b and and integer sizeofArray . In this method we iterate fro 0th index to sizeofArray and multiply each element by 2. So when modifyArray ( a, arraySize); is called in main, array a gets modified such that each element of array is now twice of itself.
void modifyElement ( int e )
{
e *= 2;
}
modifyElement recieves an integer e and multipplies it by 2 and assigns it to e. But when modifyElement ( a[4] ); is called, a[4] doesnt get modified. Here is why
modifyArray ( a, arraySize): Here a is passed, which means base address(address of first element). is passed. After that each element is accessed by computing address( base + offset ) This is nothing but Pass by reference. In Pass by reference, if value gets changed in the called function, it will reflect in caller function also.So when array elements are modified in modifyArray , it gets eflected in main.
modifyElement ( a[4] ); Here a[4] is passed, which means a copy of the a[4] is passed to modifyElement. This is Pass by value. In Pass by value, if value gets changed in the called function, it will not reflect in caller function also.So when a[4] is mdified in modifyElement it will not reflect in main.
Get Answers For Free
Most questions answered within 1 hours.