Thread: I don't really understand this loop that contains breaks and continues.

  1. #1
    Registered User
    Join Date
    Aug 2012
    Posts
    5

    I don't really understand this loop that contains breaks and continues.

    Well, I'm still learning the tutorials and I just have a question. I kind of get the other examples, but this one I'm not understanding. I like to explain everything in the code using comments so that I can know what each part does. But I just don't really understand this.

    Code:
    for (player = 1; someone_has_won == FALSE; player++)    {
            
            if (player > total_number_of_players)
            {player = 1;}
            if (is_bankrupt(player))
            {continue;}
            take_turn(player);
        }
    Like I don't understand the player = 1 part, the someone_has_won, the player++, and basically everything about it. Like my other thread, please explain it to me like I'm five.

    Thanks.

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    The purpose of the loop is to control the game. The game is over when someone wins, I hope I don't have to further explain the for loop condition. Also a game has to give everyone playing a turn or it wouldn't be fair. So whoever player 1 is goes first, and assuming he didn't go bankrupt, takes his turn. Then player++ happens and you keep going around the table.

    So based on what we know, the loop looks pretty similar:
    Code:
    for (player = 1; someone_has_won == FALSE; player++) {
       if (!is_bankrupt(player)) {
          take_turn(player);
       }
    }
    The problem with this loop is that games tend to be played by small groups of people. If 4 people are playing, then you don't want a turn to go to a nonexistent 5th person. That is the purpose of the comparison against `total_number_of_players' because you want to bring the turns back around to the first player.

    Finally, the purpose of the continue keyword is to force the loop to start a new iteration and prevent a player who's bankrupt from taking a turn. There are other way to write that as you have seen.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can someone help me understand this very simple loop?
    By matthayzon89 in forum C Programming
    Replies: 2
    Last Post: 04-17-2010, 09:12 AM
  2. C keep a loop going whilst program continues on
    By fortune2k in forum C Programming
    Replies: 6
    Last Post: 03-11-2009, 08:44 AM
  3. trying to understand the message loop
    By bling in forum Windows Programming
    Replies: 4
    Last Post: 08-08-2008, 09:27 AM
  4. Replies: 11
    Last Post: 09-09-2006, 12:15 PM
  5. for loop again. I don't understand the construction.
    By cdalten in forum C Programming
    Replies: 6
    Last Post: 03-22-2006, 09:06 AM