osxfloo osxfloo - 1 month ago 7
C++ Question

Odd random number in range [1..99]

I want to fill an array with odd random numbers in a range [1..99].

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;

const int N = 100;
int a[N];

void print(){
for (int i=0; i<N; i++)
cout << a[i] << " ";
}

int main(){
srand(time(NULL));
int number;
for (int i=0; i<N; i++) {
number=(rand()%100)+1;
if (number%2!=0)
a[i]=number;
}
print();
}


When I use this code I receive:

0 7 0 0 29 0 0 93 0 0 29 0 27 0 0 13 35 0 0 0 0 0 51 0 0 0 97 99 15 73 79 0 73 0 21 39 0 7 25 41 1 99 31 0 0 1 0 81 69 73 37 95 0 0 0 41 21 75 97 31 0 0 0 0 0 0 31 21 0 11 33 65 0 69 0 0 9 63 27 0 13 0 63 27 0 7 0 0 99 0 77 0 59 5 0 99 0 69 0 0

What is wrong with that? Why there are a lot of "0"?

Answer

Why shouldn't there be? You only fill in odd ones:

    if (number%2!=0)
        a[i]=number;

If the random number is even, skip adding it to the array. So... every 0 you got represents an even number.

Comments