I want to be 30 numbers not 29! I knew that if we do rand() %30 +1 will count the last number too.... "For" Loop i try <= and < doesnt work? can someone give a hind?
1 2 3 4 5 6
for (int i=0 ; i <= 30; i++)
{
first[i] = rand() % 30 + 1; // The will create up to 30.
}
So 7%3 == 1 because 7/3 gives you a remainder of 1.
So any number % X is going to be [0,X). (note it's inclusive of 0, but exclusive of X).
This is commonly used with rand to produce numbers of a specific range. IE, if you want a range of 30 different possible numbers, you would do rand() % 30 because any number % 30 is going to be between [0,30).
note: [0,30) is the same as [0,29] for integers.
The widely used format for this, then, is (rand() % range) + start;
Where:
- 'range' is the number of different possible results you want
- 'start' is the lowest possible value you want
So... if you want [1,30] ... that is a range of 30 different values that start at 1.
So range=30, start=1 rand() % 30 + 1;
Or... if you want [0,30] ... that is range=31, start=0 rand() % 31;