how to generate a random integer number between 0 and 9

This is a discussion on how to generate a random integer number between 0 and 9 within the C Programming forums, part of the General Programming Boards category; Hi everyone could anyone tell me how to generate a random integer number between 0 and 9.How to use s_rand() ...

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    4

    how to generate a random integer number between 0 and 9

    Hi everyone
    could anyone tell me how to generate a random integer number between 0 and 9.How to use s_rand() and rand() ?I think these functions are suitable but i dont know how to use them.Thanks for reading

  2. #2
    {Jaxom,Imriel,Liam}'s Dad Kennedy's Avatar
    Join Date
    Aug 2006
    Location
    Alabama
    Posts
    1,065
    This question is asked very often. Search the forums.

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    There's an FAQ on it: http://faq.cprogramming.com/cgi-bin/...&id=1043284385

    The short answer is: seed the random number with srand() (and probably time()); and get a random number with rand(), restricting its value to 10 with %.
    Code:
    #include <time.h>  /* for time() */
    #include <stdlib.h>  /* for rand() and srand() */
    
    int n;
    srand(time(NULL));
    n = rand() % 10;  /* generate a number from 0 - 9 */
    BTW, only call srand() once.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21