How to Generate a Random Number in C

Generating random numbers in C is needed in several applications. For instance, generating a default password for a new user on a network uses random generation of numbers and letters. Random numbers are generated in gaming applications for character battles and fighting. Whatever the reason, generating the numbers is possible through an internal C function.

Instructions

    • 1

      Create an integer to contain the random number. Variables cannot be used in C unless they are explicitly defined. The following code declares a variable in C:
      int myNumber;

    • 2

      Generate a random number using C's internal function. The function takes a whole number and it determines the ranges the function will return. For instance, if you pass the number 100 to the random function, it will return a randomly generated integer from zero to 99. Use the integer defined in Step 1 to contain the random number:
      myNumber = random(100);
      This C code returns a randomly generated number from zero to 99 and assigns it to the myNumber variable.

    • 3

      Print the number to the console. Print the number to the screen using C's "printf()" function to see what number is generated:
      printf("The number generated is %d, \n", myNumber);

Related Searches:

References

Resources

Comments

You May Also Like

Related Ads

Featured