Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

PROGRAMMING FUNDAMENTALS

(CSCP 1013)

Affefah Qureshi

Department of Computer Science,


University of Central Punjab, Rawalpindi Campus
2D ARRAY AND FUNCTIONS
PASSING ARGUMENTS TO FUNCTIONS
C

• Three ways to pass arguments to function:


1. Pass-by-value
2. Pass-by-reference with reference arguments
3. Pass-by-reference with pointer arguments
1. PASS BY VALUE – EXAMPLE
c

void AddGraceMarks(int marks) {


cout <<“\ nAc tua l marks: "<<marks<<end l;
marks = marks + 10;
cout<<“\nMarks Updated to:"<<marks<<endl;
}

i n t main() {
i n t marks = 75;
AddGraceMarks(marks) ;
cout<<“You marks i n PF ar e : ”<<mar ks<<end l;
return 0 ;
}
USING REFERENCE VARIABLES WITH FUNCTIONS
c

• To create a second name (Alias) for a variable


in a program
• A variable that acts as an alias for another
variable is called a reference variable, or simply
a reference

• Arguments passed to function using


reference arguments:
– Modify original values of arguments
1. PASS BY REFERENCE– EXAMPLE
c

void AddGraceMarks(int &marks) {


cout <<“\ nAc tua l marks: "<<marks<<end l;
marks = marks + 10;
cout<<“\nMarks Updated to:"<<marks<<endl;
}

i n t main() {
i n t marks = 75;
AddGraceMarks(marks) ;
cout<<“You marks i n PF ar e : ”<<mar ks<<end l;
return 0 ;
}
PASSING AN ARRAY TO A FUNCTION
c
• We need to tell the compiler what the type of the
array, and give it a variable name (a reference)
float a[ ]
• We don’t want to specify the size so function can
work with different sized arrays
• Size may be provided as second parameter
• Arrays are automatically passed by reference.
• Do not use & symbol
PASSING AN ARRAY TO A FUNCTION
c
An int array
i n t Displ ay(i n t dat a [ ] , in t N) { The size of the array

cout<<“Array cont a i ns”<<endl;


f o r ( i n t k=0; k<N; k++)
cout <<dat a[k]<<“ “;
cout<<endl;
}
i n t main( )
{
in t a[4 ] = {11, 33 , 55, 77} ;
Display(a, 4 ) ;
return 0 ; } The array argument,
no [ ] or & symbol
PASSING 2D ARRAYS TO FUNCTIONS
• One important difference only:
• Include empty brackets for the leftmost index,
• Use specific dimensions for all other indices (along with
the type)
i n t Max(int[][10], i n t ) ;
• Function definition:
i n t Max(int A r r [ ] [ 1 0 ] , i n t sz)
{ . . . }
• Function call:
Display(TDArr, S i z e ) ;
i n t FindSum(int A r r [ ] [ 4 ] , i n t rows, i n t cols) {

i n t sum=0;
cout << “\ n Calcul ating sum…" << endl ;
f o r ( i n t i = 0 ; i < rows; i+ + ) {
f o r ( i n t j = 0 ; j < cols; j + + )
sum+= A r r [ i ] [ j ] ;
return sum;
}
i n t main() {

/ / i n i t i a l i z e 2d array
i n t TDArr[3][4] = { { 3 , 4 , 1 , 3 } , { 9 , 5 , 2 , 1 } , { 7 , 0 , 2 , 1 } } ;

/ / c a l l the function, pass a 2d array as an argument


cout<<“\n Sum is:”<<FindSum(TDArr,3,4);

return 0 ; }

You might also like