I have solved it and the code works fine, but it's too long and I'm curious to know if there's any more compact way of writing it. And by "it" i'm referring to the second loop.

PS: I'm printing instead of calculating sum to display the process and see if there's anything wrong

#include <stdio.h> int main() { int a[100][100], i, j, n; scanf("%d", &n); printf("\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++){ scanf("%d",&a[i][j]); } } printf("\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++){ if(i==0 && j ==0) printf("%d %d %d", a[i][j],a[i+1][j],a[i][j+1]); else if (i==0 && j==n-1)printf("%d %d %d", a[i][j],a[i][j-1],a[i+1][j]); else if(j==0 && i ==n-1)printf("%d %d %d", a[i][j],a[i-1][j],a[i][j+1]); else if(i==0) printf("%d %d %d %d", a[i][j],a[i][j-1],a[i+1][j],a[i][j+1]); else if(j==0) printf("%d %d %d %d", a[i][j],a[i-1][j],a[i+1][j],a[i][j+1]); else if(i==n-1 && j ==n-1) printf("%d %d %d", a[i][j],a[i-1][j],a[i][j-1]); else if(i==n-1) printf("%d %d %d %d", a[i][j],a[i-1][j],a[i][j-1],a[i][j+1]); else if(j==n-1) printf("%d %d %d %d", a[i][j],a[i-1][j],a[i][j-1],a[i+1][j]); else printf("%d %d %d %d %d", a[i][j],a[i-1][j],a[i][j-1],a[i+1][j],a[i][j+1]); printf("\n"); } } }