Passing arrays to a function as argument


Passing arrays to a function as argument :-

Ø  To pass a one-dimensional array to a function, it is sufficient to list the name of the array without any subscripts and size of the array as arguments.

Example :-        get (a,n);      
o   Where a is the array name and n is the size of the array.
o   But in function header, we need to mention the array as a subscripted variable.



write a c program to Read and Print array elements using functions.
get(int [ ],int );
 put(int [ ],int );
 main()
 {
            int a[20],n;
            clrscr();

            printf("enter size of array  :");
            scanf("%d",&n);

            get(a,n);
            printf("\n the Array elements are.....\n");
            put(a,n);
 getch();
 }
 get(int a[ ],int n)
 {
            int i;
            for(i=0;i<n;i++)
            {
                        printf("ente %d element ",i);
                        scanf("%d",&a[i]);
            }
 }

 put(int a[ ],int n)
 {
            int i;
            for(i=0;i<n;i++)
             printf("\n %d",a[i]);
 }


Passing Two dimensional arrays to a function as argument :-

Ø  To pass a one-dimensional array to a function, it is sufficient to list the name of the array without any subscripts and size of the array as arguments. But we must specify the size of columns in function definition .

Example :-        get (a,m,n); 

o   Where a is the array name and n is the size of the array.
o   But in function header, we need to mention the array as a subscripted variable. M and  N are sizes of array row and column sizes.

get(int a[ ][5], int m, int n)
{     ------------
      ------------
}

Example : write a c program to Read and Print array elements using functions.



get(int [ ][ ],int ,int );
 put(int [ ][ ],int ,int );

main()
 {
            int a[20][20],m,n;
            clrscr();

            printf("enter size of array  :");
            scanf("%d%d",&m,&n);

            get(a,m,n);
            printf("\n the Array elements are.....\n");
            put(a,m,n);
 getch();
 }

 get(int a[ ][10],int m,int n)
 {
            int i;
            for(i=0;i<m;i++)
               for(j=0;j<n;j++)
{
                        printf("ente %d element ",i);
                        scanf("%d",&a[i][j]);
            }
 }

  
 put(int a[ ][10],int m,int n)
 {
            int i;
            for(i=0;i<n;i++)


for(j=0;j<n;j++)
             printf("\n %d",a[i][j]);
 }
 


In this example we can pass the a two dimensional array, in the function definition we must specify the size of that array column size other wise it will throw an error

No comments:

Post a Comment