ADVERTISEMENT
ADVERTISEMENT

C program to pass two dimensional array (Two-D array) to a function

Here, we have a C program, in which we are demonstrating an example of passing two dimensional arrays to a function.
Submitted by IncludeHelp, on March 22, 2018

Given a two dimensional array and we have to pass it to the function in C.

In this example, we are declaring a two dimensional array inside the main() function and passing it to the function - within the function, elements of the array are printing.

Here is the function that we are using in the program,

void arrayfun(int ptr[3][3] , int row, int col)

Here,

  • void is the return type of the function.
  • arrayfun is the name of the function.
  • int ptr[3][3] an integer type of variable (which is declared as two dimensional array), that will store the elements of the array which will be passed. We can also use int ptr[][3] there is no need to provide size for the row, but number of maximum columns must be provided.
  • int row, int col are the variables that will store the value of number of rows and columns.

Function calling statement,

arrayfun(array,3,3);

Here,

  • array is a two dimensional integer array
  • 3,3 are the number of rows and columns
ADVERTISEMENT

Program to pass two dimensional arrays in C

/*  
C program to pass 2D array to a function
*/

#include <stdio.h>

// function to print 1D array elements
void arrayfun(int ptr[3][3] , int row, int col)
{
    int i=0,j=0;
    
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            printf("\nArray [%d][%d] : %d",i,j,ptr[i][j]);  
			fflush(stdout);
        }
        printf("\n");
    }
}

// main function
int main()
{
  // Declare a 2D array and initialize the three rows
  int array[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
	
  // Passing 2D-array and number of columns and rows to Function
  arrayfun(array,3,3);
  return 0;
}

Output

Array [0][0] : 1
Array [0][1] : 2
Array [0][2] : 3

Array [1][0] : 4
Array [1][1] : 5
Array [1][2] : 6

Array [2][0] : 7
Array [2][1] : 8
Array [2][2] : 9

C User-defined Functions Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.