I'm trying to reverse my 2D array, I have this code with two functions, first one creates a random matrix of a rows and a columns, the second one must reverse it, but I don't quite understand what I did wrong there, because in the end it prints me just a row of numbers. Example: last number in the matrix is, let's say, 12, so it prints me: " 0 12 0 "
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int ar[100][100];
void create_mat(int a)
{
srand(time(NULL));
for (int i=0; i<a; i++)
{
printf("\n");
for (int j=0; j<a; j++)
{
ar[a][a]=rand()%15+1;
printf("%d\t", ar[a][a]);
}
}
}
void reverse_mat(int a)
{
printf("\nReversed: ");
for (int i=0; i<a/2; i++)
{
printf("\n");
for (int j=0; j<a; j++)
{
int temp = ar[a][a];
ar[a][a]=ar[a-i-1][a];
ar[a-i-1][a]=temp;
printf("%d\t", ar[a][a]);
}
}
}
int main()
{
int (*funcptr)(int);
int (*rev)(int);
funcptr = &create_mat;
rev = &reverse_mat;
int a;
printf("Introduce the number of rows and columns: ");
scanf("%d", &a);
funcptr(a);
rev(a);
return 0;
}
Thank you to everyone for your help! Due to my pause in coding for a month, I've commited some errors that led to my problems, such as ar[a][a], rand()%15+1, etc. With your help and hints I fixed the program, and now it is doing what I was wanting it to do.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int ar[100][100];
void create_mat(int a)
{
srand(time(NULL));
for (int i=0; i<a; i++)
{
printf("\n");
for (int j=0; j<a; j++)
{
ar[i][j]=rand()%16;
printf("%d\t", ar[i][j]);
}
}
}
void reverse_mat(int a)
{
for (int i=0; i<a/2; i++)
{
printf("\n");
for (int j=0; j<a; j++)
{
int temp = ar[i][j];
ar[i][j]=ar[a-i-1][j];
ar[a-i-1][j]=temp;
}
}
}
void print_reversed(int a)
{
printf("\nMatricea in forma inversa: ");
for (int i=0; i<a; i++)
{
printf("\n");
for (int j=0; j<a; j++)
{
printf("%d\t", ar[i][j]);
}
}
}
int main()
{
int (*funcptr)(int);
int (*rev)(int);
int (*ptr_rev)(int);
funcptr = &create_mat;
rev = &reverse_mat;
ptr_rev = &print_reversed;
int a;
printf("Introduceti nr de linii si coloane: ");
scanf("%d", &a);
funcptr(a);
rev(a);
ptr_rev(a);
return 0;
}