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)

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 :)


#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;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s