How to Print Odd Random Int

what is the code I would use to print 200 random int, 20 rows and 10 columns format?


1
2
3
4
5
6
7
8
9
 23     srand(time(0));
 24     
 25     for(int c = 1; c <= 200; c++){
 26             
 27             cout << (rand() % 100) << endl;
 28             
 29             }
 30             
What your code does now, is it simply outputs a random number, once for each newline. In short, it'll be one column in width, and 200 in length. So logically think about what you want to do: you want to print out 10 numbers on one line. Then as soon as a counter ticks to 10 (hint: %10), move on to a new line with endl;.

This is assuming you're not dealing with 2d arrays.
Last edited on
Okay i got the numbers separated into 20 per column but they are all still stuck on one line. Also the bigger question is how would i program the code to only print random odd integers?

Thank you for your advice!
Last edited on

int main()
{
int n;

srand(time(NULL));

for (int i=0;i<10;i++)
{
n = rand();

cout<<(n%2?n:n+1)<<endl;
}

return 0;
}
@OP ask yourself what defines a number to be even or odd? In your regular math class, you'd say that depends on that number's divisibility by two, right? Well in programming, as you may or may not know, these types of arithmetic are divided into two basic subcategories: integer arithmetic and everything else1.

In programming if you have
ints a, b, and c, with
a = b/c, and
b = 3,
c = 2,
a would be 1.

Because you're dividing by whole numbers, and how many times can 2 go into 3? Exactly once, as reasoned by the compiler. So how people test for divisibility is NOT to see if a number is divisible by another number, because you're always going to get one of three possiblities: undefined (div by 0), 0 (0 div by a number), or >=1 (anything else).

In short, test for even or odd using modular arithmetic: if( a % 2 == 0) //etc



1Anything like floating point arithmetic will get you 1.5, like if you're using float or double data types and such. Not with ints. Never with ints.
Ive figured out how to print random ODD INT but cant get the rows and column correct. I should be 20 rows and 10 columns. What am I doing wrong?

23 srand(time(0));
24 for(int r = 1;r <= 20; r++){
25 for(int c = 1; c <= 10; c++){
26 int a;
27 a = (rand() % 100);
28 if(a % 2 != 0){
29 cout << a;
30 }
31 cout << endl;
32 }
33
34 }
35
36
Topic archived. No new replies allowed.