Help with challenge in A Hillegass book

Discussion in 'Mac Programming' started by admo, Feb 1, 2012.

  1. macrumors member

    Joined:
    Aug 24, 2009
    #1
    In chapter 7 of Objective-C Programming, the challenge is to create a program that counts backwards from 99 to 0 by 3. Additionally, every time a number is divisible by 5, it should also print "Found one!" So the output should look like:

    99
    96
    93
    90
    Found One!
    87
    ...
    0
    Found One!

    I successfully completed the challenge with the following code:

    Code:
    #include <stdio.h>
    
    int main (int argc, const char * argv[])
    {
        int i;
        for (i = 99; i >= 0; i -= 3) {
            printf("%d\n", i);
            if (i % 5 == 0) {
                printf("Found one!\n");
            }
        }
        
        return 0;
    }
    
    Now, the chapter dealt with loops, which I used the "for" loop. But the chapter also introduced "break" and "continue". I struggled for a while, trying to use break and/or continue in the program, but that seemed to make it more complex than needed.

    So, with the above challenge, would any of you have used the continue or break commands to achieve the same result?

    Thanks!

    I must say, I was kind of shocked that when I first built and ran it after typing the above, that it worked.
     
  2. macrumors 603

    Joined:
    Aug 9, 2009
    #2
    Some loops don't need break or continue. Just like some if statements don't need an else.

    I think your loop is fine as-is. It's time to try the next challenge or exercise.

    Programming isn't a contest to use as many things as possible. Use what's appropriate, and no more. If anything, the contest lies in figuring out what's appropriate, and maintaining a "no more than is necessary" constraint.
     
  3. thread starter macrumors member

    Joined:
    Aug 24, 2009
    #3
    Much appreciated. I guess going into the challenge I had assumed that the problem may even require a break or continue. Hence my amazement that my code worked, and just seemed so simple. I guess I should be happy that I found the challenge quite simple :)
     
  4. macrumors 604

    chrono1081

    Joined:
    Jan 26, 2008
    Location:
    Isla Nublar
    #4
    Wait until you get out of his beginner book and into his regular books ;)
     

Share This Page