Pages

This blog is under construction

Wednesday, January 23, 2019

Passing 2-D Array to a Function in C with example

Just like a 1-D array, when a 2-D array is passed to a function, the changes made by function effect the original array.

when a 2-D is passed to a function it is optional to specify the size of the left most dimensions.
So if we have an array of 2 rows and 3 columns then it can be passed to a function in the following ways:

int two_d[2][3] = {{99,44,11},{4,66,9}};

1st way:

void function(int a[][3])
{
// statements;
}

2nd way:

void function(int a[2][3])
{
// statements;
}

3rd way:

void function(int (*a)[3])
{
// statements;
}

Essentially in all the three cases discussed the type of the variable a is a pointer to an array of 3 integers, they differ only in the way they are represented.


Example:
C program to find sum of even nos of a 2 X 3 matrix.


#include <stdio.h>

void print_fun(int [][3]);
int sum_even( int [2][3]);
int sum_odd( int (*)[3]);
int main()
 { 
    int mat[2][3],i,j,sumeven, sumodd;
   printf("\nEnter elements of matrix:\n");
   for( i=0;i<2;i++)
     { for(j=0;j<3;j++)
        { printf("Enter element mat[%d][%d]: ",i,j);
           scanf("%d",&mat[i][j]);
       }
     }

        print_fun(mat);
        sumeven=sum_even(mat);
        sumodd=sum_odd(mat);
        printf("\n Sum of even numbers:%d",sumeven);
        printf("\n Sum of odd numbers:%d",sumodd);
  }

void print_fun(int mat[][3]) 

     { int i,j;
       printf("Matrix:\n");
       for( i=0;i<2;i++)
         { for(j=0;j<3;j++)
             { printf("%d\t",mat[i][j]);
             }
            printf("\n");
        }
    }

int sum_even( int mat[2][3])   
    {
      int i,j,sum=0;
        for( i=0;i<2;i++)
          { for(j=0;j<3;j++)
              { if(mat[i][j]%2==0)
                   sum=sum+mat[i][j];
              }
           }
      return sum;
   }

int sum_odd( int (*mat)[3])
  {
    int i,j,sum=0;
    for( i=0;i<2;i++)
      { for(j=0;j<3;j++)
         { if(mat[i][j]%2!=0)
                sum=sum+mat[i][j];
         }
       }
      return sum;
  }

No comments:

Post a Comment