-1

I was solving this problem and I came up with the code shown below. Also, the problem requires indexing from 1.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int arr[5][5];

    for(int i = 1; i <= 5; i++)
    {
        for(int j = 1; j <= 5; j++)
        {
            scanf("%i", &arr[i][j]);
        }
    }

    int row = 0;
    int column = 0;

    for(int i = 1; i <= 5; i++)
    {
        for(int j = 1; j <= 5; j++)
        {
            if(arr[i][j] == 1)
            {
                row = i;
                column = j;
                break;
            }
        } 
    }

    int moves = abs(row - 3) + abs(column - 3);

    printf("%i\n", moves);
    return 0;
}

The program returns the correct output but exits with a seg fault. When I replaced the array declaration outside the main function i.e. globally, it works perfectly without any seg fault. I can't understand why this is happening..?

Sarthak
  • 3
  • 4

1 Answers1

0

This code can help you ,

In for loop you should start from 0 to N-1

#include <stdio.h>

int main(void)
{
    int arr[5][5];

    for(int i = 0; i < 5; i++)
    {
        for(int j = 0; j < 5; j++)
        {
            scanf("%d", &arr[i][j]);
        }
    }

   int row = 0;
   int column = 0;
   int i=0,j=0;
   while(i<5)
   {j=0;
       while(j<5)
       {
            if(arr[i][j] == 1)
            {
                row = i;
                column = j;
                break;
            }
            j++;
       }
       i++;
    }
    int moves = abs(row - 2) + abs(column - 2);
    printf("\n%d\n", moves);
    return 0;
}
MED LDN
  • 684
  • 1
  • 5
  • 10