2d array finding neighbors c++
#include <stdio.h>
#define ROWS 8
#define COLS 8
typedef int matrix_t[ROWS][COLS];
static int sum(matrix_t &matrix, int row, int col)
{
int sum = 0;
for (int i = -1; i < 2; i++)
{
for (int j = -1; j < 2; j++)
{
// skip center cell
if (i == j) continue;
// skip rows out of range.
if ( (i + row) < 0 || (i + row >= ROWS) continue;
// skip columns out of range.
if ( (j + col) < 0 || (j + col >= COLS) continue;
// add to sum.
sum += matrix[i + row][j + col];
}
}
return sum;
}
static int make(matrix_t &result, const matrix_t &source)
{
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLS; j++)
result[i][j] = sum(source, i, j);
}
// print a matrix to stdout.
static int print(const matrix_t &source)
{
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
printf("\t%d", source[i][j]);
printf("\n");
}
}
// unit test
int main(int argc, char *argv[])
{
matrix_t result = {0};
const matrix_t source =
{
{1, 2, 3, 4, 5, 6, 7, 8},
{1, 2, 3, 4, 5, 6, 7, 8},
{1, 2, 3, 4, 5, 6, 7, 8},
{1, 2, 3, 4, 5, 6, 7, 8},
{1, 2, 3, 4, 5, 6, 7, 8},
{1, 2, 3, 4, 5, 6, 7, 8},
{1, 2, 3, 4, 5, 6, 7, 8},
{1, 2, 3, 4, 5, 6, 7, 8}
};
make(result, source);
puts("Source:");
print(source);
puts("Result:");
print(result);
return 0;
}
</stdio.h>
Are there any code examples left?
New code examples in category C++
-
C++ 2023-04-28 17:44:25
-
C++ 2022-03-27 19:20:39 lists occurrences of characters in the string c++
-
C++ 2022-03-27 18:00:14 variabili in c++
-
C++ 2022-03-27 17:10:08 repeat character n times c++
-
C++ 2022-03-27 15:50:07 delete an array c++
-
C++ 2022-03-27 15:40:12 C++ pointer to base class
-
C++ 2022-03-27 12:15:21 find the graph is minimal spanig tree or not
-
C++ 2022-03-27 11:30:15 multi variable assignment cpp
-
C++ 2022-03-27 11:05:17 c++ pi float
-
C++ 2022-03-27 10:20:12 why exceptions can lead to memory leaks