Thread: Calling functions via a for loop

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    144

    [SOLVED]Calling functions via a for loop

    When I trace this program line by line, I get different outputs(which is what I want). However, when I compile and run, output values are all the same. Why is this the case?

    I initialised the seed outside the function roll_dice (I put it in the main) and the output is fine.

    Code:
    /*
     * Craps game
     */
    
    #include <stdio.h>
    #include <stdlib.h>	//for srand and rand
    #include <time.h>
    
    int roll_dice(void);
    int play_game(void);	//returns true or false
    
    int main()
    {
    	int x;
         
        //srand((unsigned) time(NULL)); //produces correct result
    	for (x = 0; x < 100; x++)
    		play_game();
    
    	getchar();
    	return 0;
    }
    
    int roll_dice(void)
    {
    	int first_roll, second_roll, sum;
    
    	srand((unsigned) time(NULL)); //initialised in main-> output rite
    
    	first_roll = rand() % 7;
    	second_roll = rand() % 7;
    
    	sum = first_roll + second_roll;
    
    	return sum;
    }
    
    int play_game(void)		//return bool
    {
    	printf("%d\n", roll_dice());
    
    	return 0;
    }
    Is this right?
    1. For x = 0, play_game function is called
    2. in play_game function, roll_dice() function is called
    3. in roll_dice function, seed is initialised and the sum is returned to play_game function
    4. sum is printed

    In step 3, the srand function should be initialised with a new seed. Seems like the same seed keeps getting initialised
    5. repeat step 1, x++

    Solved: srand initialises new seed every second. At the moment, srand is called 100 times within 1 second, hence the same seed is used for the rand() function.

    used this for anyone who sees this in the future
    c - Problems when calling srand(time(NULL)) inside rollDice function - Stack Overflow
    c - srand() -- why call only once? - Stack Overflow
    Last edited by bos1234; 09-18-2013 at 08:36 PM. Reason: solved!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Calling functions
    By cda67 in forum C Programming
    Replies: 2
    Last Post: 10-14-2011, 11:56 PM
  2. calling functions
    By njasmine1 in forum C Programming
    Replies: 2
    Last Post: 12-29-2010, 10:28 AM
  3. Calling functions
    By Jackson_D in forum C Programming
    Replies: 2
    Last Post: 03-07-2008, 09:44 PM
  4. Help calling and using a functions
    By method in forum Windows Programming
    Replies: 0
    Last Post: 07-08-2006, 04:08 PM
  5. Calling App Functions from DLL
    By johnnie2 in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2003, 01:08 AM