how can I fill a 2d array with 0 and 1. for example the first row should be filled with all 1. In the second row, every second element should be filled with 1 and other elements with 0. In the third row, every third element should be filled with 1 and others with 0.
-
3Try something (there's going to need to be some loops). If you get stuck, come back and ask for help with a specific problem. – Alan Stokes Dec 6 '15 at 11:03
-
3i am already stuck... – ynnenu Dec 6 '15 at 11:16
-
1So, to begin with, you don't even know how to write loops? – Jongware Dec 6 '15 at 11:48
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;
}