By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,652 Members | 1,487 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,652 IT Pros & Developers. It's quick & easy.

C++ how to execute for loop and generate a random number??

P: 6
I have to write a C++ program that picks a random number between 0 and 49. If the number is even lets say 30, then the computer will display 30, 32, 34, 36... all the way till 100, if its odd lets say 17, then the computer will display 17, 19.. till 99. I got the computer picking a random number, I just can't figure out how to display every other number using a for loop statement. Here's my code for random number generator:

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. #include <iostream>
  4. #include <cstdlib> 
  5. #include <ctime>
  6.  
  7. using namespace std;
  8.  
  9. int main()
  10.  
  11. {
  12.  
  13.     {
  14.  
  15.     srand((unsigned)time(0));
  16.  
  17.     int random_integer;
  18.  
  19.     random_integer = (rand()%49);
  20.  
  21.     cout << random_integer << endl;
  22.  
  23.     }
  24.  
  25.  
  26.     return 0;
  27.  
  28.  
  29.  
Oct 24 '14 #1
Share this Question
Share on Google+
4 Replies


Expert 100+
P: 2,391
I believe rand()%49 yields a value between 0 and 48.
Oct 24 '14 #2

weaknessforcats
Expert Mod 5K+
P: 9,197
Just write a loop that adds 2 to your number, displays the number, and keeps going while the number is less than or equal to 100.
Oct 24 '14 #3

P: 6
I know the logic behind it but I just can't get started on how to write the loop
Oct 24 '14 #4

weaknessforcats
Expert Mod 5K+
P: 9,197
Expand|Select|Wrap|Line Numbers
  1. while(put your test here)
  2. {
  3.    ...add 2 to your number
  4.    ...display the number
  5. }
As a for loop it looks like:
Expand|Select|Wrap|Line Numbers
  1. for(; put your test here; )
  2. {
  3.    ...add 2 to your number
  4.    ...display the number
  5. }
Oct 24 '14 #5

Post your reply

Sign in to post your reply or Sign up for a free account.