[Solved] how can i fill a 2d array with 0 and 1.? [closed]


As usual there are many ways to do the task. For example you can use the following solution

#include <iostream>

int main()
{
    const size_t M = 5;
    const size_t N = 10;
    int a[M][N];

    for ( size_t i = 0; i < M; i++ )
    {
        for ( size_t j = 0; j < N; j++ ) a[i][j] = ( j + 1 ) % ( i + 1 ) == 0;
    }

    for ( const auto &row : a )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }        

    return 0;
}

The program output is

1 1 1 1 1 1 1 1 1 1 
0 1 0 1 0 1 0 1 0 1 
0 0 1 0 0 1 0 0 1 0 
0 0 0 1 0 0 0 1 0 0 
0 0 0 0 1 0 0 0 0 1 

If your compiler does not support the range-based for loop

    for ( const auto &row : a )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }        

then you can substitute it for an ordinary loop. For example

    for ( size_t i = 0; i < M; i++ )
    {
        for ( size_t j = 0; j < N; j++ ) std::cout << a[i][j] << ' ';
        std::cout << std::endl;
    }

8

solved how can i fill a 2d array with 0 and 1.? [closed]