Thursday 13 May 2021

Passing two dimensional array to functions

A two dimensional array is an array of one dimensional array. Like normal variables, a 2D array can also be passed to it as an argument to function. Here are different methods that are used to pass a 2D array to function.


 

A two dimensional array can be passed to a function in three different ways.

1. Passing individual elements

2. Passing entire row

3. Passing entire array

The above three methods are discussed below in detail with example programs.

1. Passing individual elements to array

The individual elements of a two dimensional array can be passed using their index value. We use particular index value to specify array data.

#include<stdio.h>
void fun(int x);
void main()
{
  int a[2][2]={10,20,30,40};
  fun(int(a[0][0]);
 }
 void fun(int x)
 {
   printf("%d",x);
  }

In the above example the array data '10' is passed to the function using their index value as a[0][0].

2. Passing entire row:

Since two dimensional array is a an array of one dimensional array. So, to pass entire row to a function, we are actually passing a one dimensional array from calling function to called function.

  #include<stdio.h>
void fun(int x[])
void main()
{
  int a[2][2]={10,20,30,40}
  fun(a[2]);
 }
 void fun(int x[])
 {
 
   for(int i=0;i<2;i++)
   {
     printf("%d",x[i]);
    }
   }

3. Passing entire array:

To pass two dimensional array to a function, we use array name, number of rows, number of columns as actual parameters. However the parameters in the called function must indicate that the array as two dimensional array.


#include<stdio.h>
void fun(int x[][], int row, int columns);
void main()
{
int a[2]2[2]={10,20,30,40};
fun(a,2,2);
}
void fun(int x[][], int row, int columns)
{
  for(int=0;i<2;i++)
  {
   for(j=0;j<2;j++)
   {
     printf("%d", &x[i][j]);
    }
   }
 }


0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top