## Calculate Sum Off All 8 Neighbors Of Each Element In An Integer Array (Tính tổng các giá trị lân cận trong mảng 2 chiều)

http://i.imgur.com/Rr67DFK.gif

http://i.imgur.com/WUzKnmp.gif

You can use If-else statements to do this, very simple, but i use another way to calculate this, help you improving about FOR-LOOP 🙂

[code language=”cpp”]

#include <iostream>

using namespace std;

int main() {

int IntArray[5][5] = {

{1, 1, 1, 1, 1},

{2, 2, 2, 2, 2},

{3, 3, 3, 3, 3},

{4, 4, 4, 4, 4},

{5, 5, 5, 5, 5}

};

for(int i=0; i<5; i++){

for(int j=0; j<5; j++){

cout << IntArray[i][j] << " ";

}

cout << endl;

}

cout << endl;

int TempArray[7][7] = {0};

for(int i=1; i<6; i++){

for(int j=1; j<6; j++){

TempArray[i][j] = IntArray[i-1][j-1];

}

}

cout << "After add a \"zero-shape\"" << endl;

cout << endl;

for(int i=0; i<7; i++){

for(int j=0; j<7; j++){

cout << TempArray[i][j] << " ";

}

cout << endl;

}

int ResultArray[5][5] = {0};

for(int i=1; i<7; i++){

for(int j=1; j<7; j++){

ResultArray[i-1][j-1] =

TempArray[i-1][j-1] + TempArray[i-1][j] +

TempArray[i-1][j+1] + TempArray[i][j-1] +

TempArray[i][j+1] + TempArray[i+1][j-1] +

TempArray[i+1][j] + TempArray[i+1][j+1];

}

}

cout << "\nHere is result\n" << endl;

for(int i=0; i<5; i++){

for(int j=0; j<5; j++){

cout << ResultArray[i][j] << " ";

}

cout << endl;

}

return 0;

}

[/code]