Rohan Kapur
Rohan Kapur

Reputation: 5

Simple Objective-C Program Not Working

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    int n, number, triangularNumber;
    NSLog(@"What Triangular Number Do You Want?");
    scanf(@"%i", &number);
    triangularNumber = 0;

    for (n = 1; n <= number; ++n)  
        triangularNumber += n;
        NSLog(@"Triangular Number %i is %i", number, triangularNumber);

    [pool drain];
    return 0;
}

The output when I write an integer is this:

Triangular Number 0 is 0

Upvotes: 0

Views: 247

Answers (2)

Maggie
Maggie

Reputation: 8101

Your input number is 0, and your condition in the for loop starts at 1. Therefore, the loop is never executed.

Upvotes: 2

MByD
MByD

Reputation: 137402

It should be :

for (n = 1; n <= number; ++n)  {
        triangularNumber += n;
        NSLog(@"Triangular Number %i is %i", number, triangularNumber);
}

In the way you wrote it, it is parsed as:

for (n = 1; n <= number; ++n)  {
    triangularNumber += n;
}
NSLog(@"Triangular Number %i is %i", number, triangularNumber);

And since the input (number) is 0 (as indicated by the print) the loop doesn't happen, yet the line is printed.

Upvotes: 0

Related Questions