I am still learning C and could use some help. I am trying write a program that will to do a search of a 2D array of char's. And have it tell you what points the searched for char is in relation to the 2D array in a (x y) coordinates. My problem is that the program is not outputting the right (x y) coordinates. Now I thought the program should output (1,0),(1,1), (1,2), (1,3), (1,4) for B. I also plan on adjusting the coordinates so that it would count at 1 instead of 0 i.e for B output should be (2,1),(2,2), (2,3), (2,4), (2,5). So far the only coordinate that prints out right is (1,1) and I am not sure why my code does not work. What can I do to fix this?
FULL CODE:
#define _CRT_SECURE_NO_WARNINGS
#define SIZE 5
#include <stdio.h>
int main()
{
int c, count = 0;
int x[SIZE] = { 0 };
int y[SIZE] = { 0 };
int j, i;
char array[SIZE][SIZE] = { { 0 }, { 0 } };
char array2[SIZE] = { 'A', 'B', 'C', 'D', 'S' };
char search;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
array[i][j] = array2[j];
}
}
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
printf("%c ", array[i][j]);
}
printf(" \n");
}
printf("What letter are you lookiong for? ");
scanf("%c", &search);
for (j = 0; j < 5; j++)
{
for (c = 0; c < 5; c++)
{
if (array[j][c] == search)
{
y[j] = j;
x[c] = c;
count++;
}
}
}
if (count == 0)
printf("%c is not present in array.\n", search);
else
{
for (i = 0; i < count; i++)
{
printf("%c is present at (%d , %d) times in array.\n", search, x[i], y[i]);
}
}
return 0;
}
array[row][column]
whereas your preferred answer seems to use Array(Column,Row) (or A(C,R)) notation. It is a matter of presentation, but you're likely to find it confusing if you use A(C,R) notation. At the very least, you need to be aware of this behaviour. – Jonathan Leffler