Search code examples
cfor-loopmultidimensional-arrayneighbours

Code of neighbor finding program in C


The instructions are to Write a program that uses a two - dimensional array to find the elements that are larger than all their neighbors.

For example if my input is:

1   2   11
13  5   6
7   6   9

The output would be: 11, 13, 9

For some reason though it displays no numbers at all. Could someone help correct the code.

Here is the code:

#include <stdio.h>                                          
#include "genlib.h"
#include "simpio.h"

#define N 3                                                 

bool neighbourCheck(int array[N+2][N+2], int i, int j);     
void getArray(int array[N+2][N+2]);

main()                                                  
{
      int array[N+2][N+2], i, j;

      printf("This program will ask you to enter nine integers of an aray.\n");
      getArray(array);
      for (i=1; i<N+1; i++)
      {
                for(j=1; j<N+1; j++)
                {
                         if(neighbourCheck(array, i, j)==TRUE)
                         {
                                        printf("%d\t", array[i][j]);            
                         }        
                }
      }
      getchar();
}

void getArray(int array[N+2][N+2])
{
      int i, j;

      for(j=0;j<=N+1;j++)
      {
                i=0;
                array[i][j]=-1;
                i=4;
                array[i][j]=-1;                   
      }
      for(i=1;i<N+1;i++)
      {
                j=0;
                array[i][j]=-1;
                j=4;
                array[i][j]=-1;                 
      }
      for(i=1;i<N+1;i++)
      {
                for(j=1;j<4;j++)
                {
                                printf("\nEnter a positive integer: ");
                                array[i][j]=GetInteger();                
                }
      }   
}

bool neighbourCheck(int array[N+2][N+2], int i, int j)                      
{
     int l, m;

     for(l=i-1; l<i+1; l++)
     {
                for(m=j-1; m<j-1; m++)
                {
                         if(array[l][m]>=array[i][j])
                         {
                                        return(FALSE);                            
                         }
                         return(TRUE);
                }
     }
}  

Thank you :D


Solution

  • You have to change the part

    for(l=i-1; l<i+1; l++)
    {
            for(m=j-1; m<j-1; m++)
    

    into:

    for(l=i-1;l<=i+1;l++)
    {
            for(m=j-1;m<=j-1;m++)
    

    Cheers!