Changing multiple values of integer array passed to a function
A program to pass integer array to a function and change many values in it based on a condition. Then reading such values in the calling function.
Learning Objectives
- Changing multiple values of an array passed to a function.
- Learning how multiple value can actually be affected in a functions, although it can return just one value.
Source Code
|
Run Output
Code Understanding
int even2odd(int [],int); int disp_arr(int [],int);
Two functions prototypes with integer array passed as reference with another variable passed as value of length of array.
int arr[]={19,20,34,55,99,102,12}; //Array initialised
int len=sizeof(arr)/sizeof(arr[0]); //Array length found
cout<<“– Array members before change — “<<endl;
disp_arr(arr,len);
Array display function called which simply displays the function.
even2odd(arr,len);
This function traversed the whole array up to len and converts any value which is even to its higher odd number.
cout<<“– Array members after change — “<<endl;
disp_arr(arr,len);
Array display after change. Since the original array itself is changed, same array is passed to the function.
int even2odd(int array[],int len) {
A function header where array is passed by reference and length is passed by value.
for(int i=0;i<len;i++){ //Array is traversed till the last point as it is passed as len
if(array[i]%2==0) array[i]+=1;
change passed array members if found even to higher odd number by adding 1 to it. Even number testing is done by divisibility by 2 test using array[i]%2==0
}return 0;} //If function is successful 0 is returned.
int disp_arr(int array[],int len)
A function header for display purposes where array is passed by reference and length is passed by value.
{
for(int i=0;i<len;i++) { cout<<array[i]<<” “;} //The array display loop
cout<<endl; //Extra line when array is displayed
return 0; //Returned 0 when function is successful
}
Notes
- While initial development of a function one may feel that ability to return just value by a function is its serious limitation, but now one has seen the demo of affecting multiple values within a function. Actually value return is often used for success condition of the function and affected values can be actually be done through referencing.
Suggested Filename(s): fn-arr-change.cpp, fnarrchg.cpp
sunmitra| Created: 17-Jan-2018 | Updated: 17-Jan-2018|