logo

Iterating over neighbours in a multi-dimensional array in C

#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { int arr[][5] = { {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, } int offsetx[] = { 0, 1, 1, 1, 0, -1, -1, -1}; int offsety[] = {-1, -1, 0, 1, 1, 1, 0, -1}; int x, y; printf("Input x: "); scanf("%d", &x); printf("Input y: "); scanf("%d", &y); int i; int sum = arr[y][x]; for (i = 0; i < 8; i++) { int nx = x + offsetx[i]; int ny = y + offsety[i]; if (nx < 0 || nx > 4 || ny < 0 || ny > 4) { continue; } sum += arr[ny][nx]; } printf("The sum of neighbours is %d\n", sum); return 0; }

Courses with this lesson