- 1). Create a new C program. Start "Visual studio." From the pull-down menu, click "File," "New Project." In the dialog box, click "Win32" under "Visual C++" on the tree view. Choose the Console application icon. Name the project "Randomizer." Click "OK." A text editor window will appear.
- 2). Add the following headers at the top of the program:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
Also add the following preprocessor definition immediately after the include statements:
#define N 25
When the list of random numbers are created, N is the highest number generated. Change this definition to vary the quantity of random numbers desired. - 3). Define the following memory variables inside the main function:
int _tmain(int argc, _TCHAR* argv[])
{ int nums[N];
int i, r;
The array nums will hold the random numbers and is sized based on the preprocessor definition. Note that different C programming versions may need slight variations of the function declaration. - 4). Clear the nums array and seed the random number generator.
srand ( time(NULL) );
for (i=0; i<N; i++)
{ nums[i]=0;
}
The srand function seeds the random number based on the current time. This ensures that a different list of random numbers occur each time the program runs. - 5). Generate the list of random numbers.
for (i=0;i<N; i++)
{ r = rand() % N;
while (nums[r] > 0)
{ r++;
if (r>=N) r=0;
}
nums[r]=i+1;
}
This loop first generates a random number from 0 to N-1 (in this case 24) then checks to see if the array at that element is empty. If it is, the random number (plus 1 to make the sequence run from 1 to 25) is placed in this location. If not, the inner while loop looks for the next available empty item in the nums array. This process is repeated until the array is full. - 6). Print the array.
for (i=0; i<N; i++)
{ printf ("%d ", nums[i]);
}
printf("\n"); - 7). End the function.
return 0;
} - 8). Click "F5" to run the program. A list of 25 random numbers will be listed in the console window.
previous post