hello programmers . I have a question not a syntax one but I need it for speed in contests
we have a 3x3 array and when we call a number it add to itself and around him +1 but in many casses like [0][1] when we want to add around it there is a place like [-1][1] that you know that it doesent exist ! so is there a command like if that array number exists then add?
heres of an example of the adding:
[0][0] = [0][0] , [1][0] , [0][1]
[1][1] = [1][0] , [0][1] , [1][1] , [2][1] , [1][2]!
thanks for your minding

As far as I know you can't have a negative index to an array. Also when an array is declared all elements exist. I think all you can do is check if an element equals zero or null.

#include <iostream>

using namespace std;

// 3x3 Matrix
const int MATRIX_SIZE = 3;

void SetElement (const int row, const int column, const int value, int matrix[][MATRIX_SIZE])
{
    // Only set the element if the supplied indexes are valid.
    if (row >= 0 && column >= 0 && row < MATRIX_SIZE && column < MATRIX_SIZE)
    {
        matrix[row][column] = value;
    }
}

void SetArea (const int row, const int column, const int value, int matrix[][MATRIX_SIZE])
{
    // Sets the element at [row][index] and all surrounding nodes except diagonal ones.
    SetElement(row    , column    , value, matrix);
    SetElement(row - 1, column    , value, matrix);
    SetElement(row + 1, column    , value, matrix);
    SetElement(row    , column - 1, value, matrix);
    SetElement(row    , column + 1, value, matrix);
}

int main()
{
    int matrix[MATRIX_SIZE][MATRIX_SIZE] = {{0,0,0},
                                            {0,0,0},
                                            {0,0,0}};

    // Example usage. First sets the 1,1 to 1 (and the corresponding area)
    // Then sets the 1,0 and 1,2 to 2.
    SetArea(1, 1, 1, matrix);
    SetArea(1, 0, 2, matrix);
    SetArea(1, 2, 2, matrix);

    // Print the matrix.
    for (int i = 0; i < MATRIX_SIZE; i++)
    {
        for (int j = 0; j < MATRIX_SIZE; j++)
        {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

You could have some 'padding' around your array. So, use a 5-by-5 array instead of 3-by-3. Then, just ignore the values of the elements in the first and last rows and columns.

Alternatively, you can have an array of pointers to updator functions that is the same size as you target array. Then just call the function in the same element as the array that you want to update.

This article has been dead for over six months. Start a new discussion instead.