Passing Arrays to functions Dr Khizar Hayat Associate

  • Slides: 5
Download presentation
Passing Arrays to functions Dr. Khizar Hayat Associate Prof. of Computer Science 1

Passing Arrays to functions Dr. Khizar Hayat Associate Prof. of Computer Science 1

 • • • • • • #include<iostream> using namespace std; void fun 2(int);

• • • • • • #include<iostream> using namespace std; void fun 2(int); int c=3; int main() { int a=1; int c=4; c=c/2; cout<<"The value of c is"<<c<<endl; fun 2(c); fun 2(: : c); if(a<10) { int c=7; cout<<"The value of c is"<<c<<endl; } c++; cout<<"The value of c is"<<c<<endl; : : c=: : c+3; cout<<"The value of c is"<<: : c<<endl; return(0); } void fun 2(int x) { int c; c=x*x; cout<<"The value of c is"<<c<<endl; : : c++; cout<<"The value of c is"<<: : c<<endl; } 2

Array as a parameter to a function • The identifier of an array refers

Array as a parameter to a function • The identifier of an array refers to its address. • Arrays can only be passed to functions, by reference and not by value • In a function declaration, array parameters are specified by data type followed by empty [ ] – the name of array identifier is optional, e. g. void display(int[]); OR void display(int b[]); – The function display() takes an array parameter b of type int. • In a function call, you would pass just the identifier of the array as argument. 3

Passing Array to Function: Example #include <iostream> using namespace std; void print(int[], int); int

Passing Array to Function: Example #include <iostream> using namespace std; void print(int[], int); int main () { int a[20], n, i; cout<<“Enter the no. of elements of the array“<<endl; cin>>n; for (i=0; i<n; i++) { cout<<“Enter the value of ith element”<<endl; cin>>a[i]; } print(a, n); //see next slide for definition return 0; } 4

Passing Array to Function: Example contd… void print(int b[], int m) { int i;

Passing Array to Function: Example contd… void print(int b[], int m) { int i; for (i=0; i<m; i++) { cout<<“The value of b[“<<i<<“] is ”<<b[i]<<endl; } } 5