do } { while

I’ve been coding in coding in various languages since around 1983 and this is the first time I’ve had an occasion to use a do } { while loop.

Here’s the scenario. I have four different kinds of pictures: locomotives, boxcars, tankers, and cabooses. I have eleven versions of each, one for each of eleven colors. I want to display two items on the screen at the same time and ask the child to identify the color. Now if a red boxcar and a red caboose show up on the screen at the same time, both are correct so the child can’t choose the red one. So what I want to do is check to see if the colors are the same and then pick a different object if they are.

I’ve already picked my first object from the list and this is the code I use to pick the second. I always need to pick a second item, so the do { } while construction is perfect. It runs through the code and after the first pass evaluates the conditional. In this case, it checks to see if the color of the first object (leftItem) is the same as the color of the second object (rightItem). If they are equal, it does another iteration and picks another object. I have eleven colors so the loop repeats about 9% of the time, so it doesn’t have any impact on execution. If you only had two or three colors, you’d probably want to use a different method.

Note: The code is Objective C and I changed it a bit from the original to make the loop portion clearer.


  NSInteger randomWord2;
        do {
            // Get another random number between 0 and n-1 
            //and add it to the original number plus 1
            int randomNumber2 = (arc4random() % numItems);
            // If randomNumber2 is not zero then the two words will be different
            if (randomNumber2   == 0) randomNumber2 = self.scoreKeeper.currentScreen + 1;
            randomItem2 = (randomNumber2 + self.scoreKeeper.currentScreen) % numItems;
            self.rightItem = [self.wordList getWord:randomItem2];
        // If the two objects have the same color, look for another rightItem
        } while ( [self.rightItem.color isEqual:self.leftItem.color] );

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.