I just wanted to solve an exercise that asks me to write a routine to generate a set of even random numbers between 2 to 10.
The problem is when printing, because I want the last number not to be followed by a comma.
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i, a, b, c;
i = a = b = c = 0;
srand(time(NULL));
for (i = 2; i <= 10; i++)
{
a = rand() % 8 + 2;
if ((i <= 10) && (a % 2) != 0)
{
continue;
}
printf((i < 10) ? "%d, " : "%d\n", a);
}
return 0;
}
And these are two execution examples:
4, 4, 2, 8,
2, 8, 6, 4, 2
In one the comma does not appear at the end but in another it does. When debugging I see that the error happens when the last number is odd, because the continue statement causes it to go to the next iteration.
As Retired Ninja has said, there are many unnecessary conditionals that can be avoided. I have revised your code so that a
will always generate an even number between 2
and 10
, thereby removing the need for the logic you implemented. This is what I have assigned this new a
value as:
a = ((rand() % 4) * 2 + 2);
This generates a random value between [0,4]
, multiplies it by 2, and adds 2, for an integer between 2 and 10, noninclusive. Since your new a
is always even, I removed your logic to check whether the number is even.
Revised code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i, a, b, c;
i = a = b = c = 0;
srand(time(NULL));
for (i = 2; i <= 10; i++)
{
a = ((rand() % 4) * 2 + 2);
printf((i < 10) ? "%d, " : "%d\n", a);
}
return 0;
}
Note that this code will always produce 9 numbers, as you have not specified how many values to print each time, just that you need to "write a routine to generate a set of even random numbers between 2 to 10". You can always change the amount of numbers printed by changing the value of i
in the for
loop. The comma issue, however, is not a problem anymore.
If my solution has helped you, please mark my answer as the correct answer :)