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?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source