Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D array search in C

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. enter image description here 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;
}
like image 291
T.Malo Avatar asked Nov 26 '25 07:11

T.Malo


2 Answers

Change this:

y[j] = j;
x[c] = c;

for this:

y[count] = j;
x[count] = c;

The arrays x and y are your results and they have to be indexed according to the number of results.

like image 169
imreal Avatar answered Nov 28 '25 23:11

imreal


Change you code like this it will work fine :

Try this :

int flag = 0; 

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)
        {
           printf("%c is present at (%d , %d) times in array.\n", search, j, c);
           flag = 1;
        }
    }
}

if (flag == 0)
    printf("%c is not present in array.\n", search);
like image 29
Ashraful Haque Avatar answered Nov 28 '25 22:11

Ashraful Haque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!