Generating odd numbers from set

This is a discussion on Generating odd numbers from set within the C Programming forums, part of the General Programming Boards category; I'm trying to generate random odd numbers from the given set: 3, 5, 7, 9, 11. I got my program ...

  1. #1
    Registered User
    Join Date
    Sep 2010
    Posts
    5

    Generating odd numbers from set

    I'm trying to generate random odd numbers from the given set: 3, 5, 7, 9, 11.
    I got my program to generate random numbers, but they are not odd and sometimes they are larger than 11. Can anyone explain how to generate odd numbers between 3 and 11? Where did I go wrong?

    Here is my code:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main( void ) 
    {
        int x;
    
        srand(time(NULL));    
        printf( "%d\n", 3 + ( rand() % 11 ) );
            
        system("pause");
        return 0;
    }

  2. #2
    cph
    cph is offline
    Registered User cph's Avatar
    Join Date
    Sep 2008
    Location
    Indonesia
    Posts
    82
    it should be
    Code:
    printf("%d\n", ((rand() % 5) + 1) * 2 + 1);

  3. #3
    Registered User
    Join Date
    Sep 2010
    Posts
    5
    Thank you so much! It all makes sense now. I knew I needed a "+1" somewhere.... but no one explained it well or showed me where to put it. A thousand times, thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting a set of numbers.... I should remember this....
    By advancedk in forum C Programming
    Replies: 3
    Last Post: 12-17-2008, 10:28 PM
  2. Generating the Mode of a Data Set
    By firetheGlazer in forum C Programming
    Replies: 3
    Last Post: 07-15-2008, 02:48 PM
  3. drand48(): generating pseudo random numbers in a range
    By Isolda_ in forum C Programming
    Replies: 2
    Last Post: 08-31-2007, 12:21 PM
  4. generating random numbers using srand
    By skyrnnr87 in forum C Programming
    Replies: 5
    Last Post: 11-24-2006, 06:45 AM
  5. adding odd numbers only
    By CheyenneWay in forum C++ Programming
    Replies: 12
    Last Post: 05-06-2004, 01:22 AM

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