Reputation: 41
So my homework assignment is to create a looping function to print only even numbers from 0 – 200. I need to create 100 random and even numbers(only 10 numbers can print per line). I'm having trouble randomizing the numbers. This is what I have so far:
// Loop from 0 to 200
for (i = 2, j = 1; i <= 200; i++, j++)
{
// Print even numbers(divisible by 2)
if (i % 2 == 0)
{
cout << i;
}
// Create new line after printing 10 numbers
if (j == 20)
{
j = 0;
ofs << '\n';
}
}
Upvotes: 2
Views: 122
Reputation: 2565
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h>
int main()
{
srand (time(NULL));
int even = rand() % 200;
if (even % 2 == 0)
{
cout<<even;
}
}
Upvotes: 2
Reputation: 72
Apart from that, your code is a little off the way. Here are some things that may be confusing to other coders (.. anyways if you feel comfortable with your style that's really ok)
"for (i = 2, j = 1; i <= 200; i++, j++)" 2 Variables are a little bit wierd, try to use only one variable. .. Just make it something like this:
int j = 1;
for (i = 2; i <= 200; i++) {
j++;
//Code
if (j == 20) {
j = 0; //etc.
}
}
Beside that "J" looks familliar to "I" so that could confuse others.. try to call it "count", that's pretty standard.
Upvotes: 0
Reputation: 2672
Here is some quick code that prints 100 even numbers [0..200] in a random order without repeating them:
#define PRIME 7879 /* Some big prime number (>> 100) */
#define NUMS 100 /* Number of values to process */
#define PRINT_GROUP 10 /* Number of values printed on a line */
int main()
{
int number = rand() % NUMS;
int i;
for (i = 0; i < NUMS; i++) {
printf("%d%c", 2*number, (i + 1) % PRINT_GROUP == 0 ? '\n' : ' ');
number = (number + PRIME) % NUMS;
}
return 0;
}
Upvotes: 1