Click here to Skip to main content
15,867,488 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
according to the following code which can generate random binary numbers, how I can decrease these 2 for loop to one for loop?

C++
std::vector<int> b;
srand(time(0));

for (i = 1; i <= 4; i++)
{
    b.push_back(i);
}

for (i = 1; i <= b.size(); i++)
{
    b[i] = rand() % 2;
    std::cout << b[i] % 2 << " ";
}


What I have tried:

how I can decrease these 2 for loop to one for loop?
Posted
Updated 27-Mar-18 5:11am
v3

1 solution

Try this:

C++
std::vector<int> b;
srand(time(0));

for (int i = 0; i <= 4; i++)
{
   b.push_back(rand() % 2);
   std::cout << b[i] << " ";
}
 
Share this answer
 
v2
Comments
MK2266 27-Mar-18 10:11am    
thank you
Leo Chapiro 27-Mar-18 11:08am    
You are welcome.
MK2266 29-Mar-18 17:17pm    
excuse me, but you changed the range of i in for loop, in my code the range is from 1 to 4, but in your code its from 0 to 4 and when I change it to 1 to 4 normally its okay but in my project it never match with other parts and the result will be wrong
KarstenK 27-Mar-18 11:17am    
You also fixed his bug in the output ;-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900