Reputation: 17
The problem states that the user determines the size of the array, then based on the size you initialize the array elements to ones and zeros. How to initialize it?
Upvotes: 0
Views: 95
Reputation: 5652
Using a std::vector
which is the right way to have an "array" whose size is specified at run time, you get zeros for free:
size_t size= ⋯ get the value from the user somehow ⋯
std::vector<int> A (size);
Every element of A
contains the integer 0
.
If you want 1 in every element, use a second argument:
std::vector<int> B (size, 1);
Every element of B
will contain the integer 1
.
See This page for a good reference on the standard library classes.
Upvotes: 0
Reputation: 510
You shouldn't put the 2nd for inside the 1st one. Simply use something like:
for (int i = 0; i < size; ++i)
{
A[i] = (i % 2);
std::cout << A[i];
}
Or use two cycle for fill and another one for print, like this:
for (int i = 0; i < size; i += 2)
A[i] = 0;
for (int i = 1; i < size; i += 2)
A[i] = 1;
for (int i = 0; i < size; ++i)
std::cout << A[i];
Upvotes: 0
Reputation: 726809
You can do it in a single loop: observe that you can get zero or one from a position by taking the remainder of division of an index by two, or by masking the index with 1
:
for (int i = 0 ; i != size ; i++) {
A[i] = i % 2; // A[i] = i & 1; will work as well
}
Upvotes: 1