I have to write a program which illustrates the usage of pointers with arrays and functions.
#include <stdio.h>
#include <conio.h>
#define ROWS 3
#define COLS 4
void print(int rows, int cols, int *matrix);
void main(void)
{
int a[ROWS*COLS],i;
for(i=0;i<ROWS*COLS;i++)
{
a[i]=i+1;
}
print(ROWS,COLS,a);
getch();
}
void print(int rows, int cols, int *matrix)
{
int i,j,*p=matrix;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf("%3d",*(p+(i*cols)+j));
}
printf("\n");
}
}
The above program prints a matrix with the rows and columns predefined. I want to modify the program such that the rows and columns are entered by the user.
#include <stdio.h>
#include <conio.h>
void print(int rows, int cols, int *matrix);
void main(void)
{
int ROWS,COLS,a[ROWS*COLS],i;
printf("Enter the number of rows: ");
scanf("%d",ROWS);
printf("\nEnter the number of columns: ");
scanf("%d",COLS);
for(i=0;i<ROWS*COLS;i++)
{
a[i]=i+1;
}
print(ROWS,COLS,a);
getch();
}
void print(int rows, int cols, int *matrix)
{
int i,j,*p=matrix;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf("%3d",*(p+(i*cols)+j));
}
printf("\n");
}
}
This programs is giving an error that the variables ROWS and COLS are being used before they are being declared. How to solve this problem.