Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

admo

macrumors member
Original poster
Aug 24, 2009
94
0
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.
 
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.
 
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 :)
 
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 :)

Wait until you get out of his beginner book and into his regular books ;)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.