Technology computers-hardware

How to Create a Randomizer in C

    • 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.

Related posts "Technology : computers-hardware"

Is There a Way to Recover Data From an S RAM Card?

Hardware

How to Create a DVD With More Than One Video File Separated Into Titles

Hardware

How to Troubleshoot Your Dell Notebook With a Projector

Hardware

Printing On A Constant Progression

Hardware

Tips on Using a Digital Pen Efficiently

Hardware

How to Fix a Master Boot Record in Vista Ultimate

Hardware

Setting Up a PC as a Wireless Router

Hardware

How to Upgrade a MacBook

Hardware

How to Disable the Touch Pad on a Dell Precision M90 Laptop

Hardware

Leave a Comment