Sunday, 2 June 2019

Passing a 2D array to a function in C

#include <stdio.h>
void read(int r,int c, int a[][c])
{
int i,j;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
}
void print(int r,int c, int a[][c])
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("%d ",a[i][j]);
printf("\n");
}
}
main()
{
int r,c;
printf("Enter the number of rows and columns\n");
scanf("%d%d",&r,&c);
int a[r][c],b[r][c],i,j;
printf("enter the array elements\n");
read(r,c,a);
printf("the array elements are\n");
print(r,c,a);
}
============================================================
#include <stdio.h>
void read(int *a,int r,int c)
{
int i,j;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[c*i+j]);
}
void print(int *a,int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("%d ",a[c*i+j]);
printf("\n");
}
}
main()
{
int r,c;
printf("Enter the number of rows and columns\n");
scanf("%d%d",&r,&c);
int a[r][c],b[r][c],i,j;
printf("enter the array elements\n");
read(&a[0][0],r,c);
printf("the array elements are\n");
print(&a[0][0],r,c);
}

Output:

No comments:

Post a Comment