Objuective C For loop problem

Discussion in 'Mac Programming' started by larswik, May 22, 2011.

  1. macrumors 68000

    Joined:
    Sep 8, 2006
    #1
    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
     
  2. macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #2
    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;
    }
    
     
  3. thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #3
    Thanks jiminaus, I knew it was something simple I was over looking. Those pesky semicolons.

    -Lars
     

Share This Page