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

larswik

macrumors 68000
Original poster
Sep 8, 2006
1,552
11
Running through Objective-C tutorial. I came across a FOR loop which I have used before in Pascal and C. It is a simple counter loop that prints a numerical value and then increments it 1 number and prints again until it reaches it's control value. For some reason if I enter the value 5 it should count up to 25 and stop, but it is just printing 1 number to the screen and it is 1 number higher then I enter, in this case 6.
Code:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

	int i, userNum;
	
	NSLog(@"Please enter a number:");
	scanf("%i", &userNum);
	
	for(i = 1; i <= userNum; i++);
		NSLog(@"%i", i);
	
    [pool drain];
    return 0;
}

Code:
Program loaded.
run
[Switching to process 1313]
Running…
2011-05-22 14:56:17.707 scanf_project[1313:a0f] Please enter a number:
5
2011-05-22 14:56:19.815 scanf_project[1313:a0f] 6

Debugger stopped.
Program exited with status value:0.

This seems so simple I must be missing something obvious?

-Lars
 
You have a trailing semicolon at the end of your for.

The code as posted is equivalent to this.
Code:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    int i, userNum;
	
    NSLog(@"Please enter a number:");
    scanf("%i", &userNum);
	
    for(i = 1; i <= userNum; i++) [color=blue]{
        /* Do nothing */
    }[/color]
    NSLog(@"%i", i);
	
    [pool drain];
    return 0;
}
 
Thanks jiminaus, I knew it was something simple I was over looking. Those pesky semicolons.

-Lars
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.