usr-local-bin
usr-local-bin

Reputation: 43

What is my 'for' loop doing?

Total beginner programmer here. I'm typing different conditions and trying to deduce how 'for' loops work manually, but I don't quite understand. I have figured out that 'n <= 20' will determine how many times the loop will run, but I'm not sure on much else. Further explanation would be greatly appreciated:

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

    int n;
    int x;
    NSLog(@"Enter your number");
    scanf("%i", &n);

    for ( x = x, n = x + 1; n <= 20 ; ++n ) {
        x += n;
        NSLog(@"The value of n is %i", n);
        NSLog(@"The value of x is %i", x);
    }     

      }

    return 0;

}

Upvotes: 1

Views: 60

Answers (2)

Joe
Joe

Reputation: 11

A for loop is normally composed of four parts: initialization, conditional expression, increment expression, and the loop body. In pseudocode,

for (initialization; conditional; increment) { body }

The initialization step is usually used to set up the variables used in the conditional and increment expression. The conditional expression evaluates to a boolean value (true/false). A value of true will result in the loop body being executed. After the last line of code in the loop body is executed the increment expression is evaluated and then the conditional expression is evaluated again...and so forth.

Upvotes: 1

Meteorhead
Meteorhead

Reputation: 516

There are 3 statements inside the parenthesis of the for clause.

for( initialize values when entering for loop ;
  evaluate statement to determine whether to continue the loop ;
  do after one iteration has passed )
{
  do stuff here;
}

In your case, when entering the for loop, you assign the value of x to x (pretty much meaningless), and to n. You execute the loop once (increment x by n and do logging), after that you increment n by 1, and check if n is less than or equal to 20. If yes, the body of the for loop is executed again, and n is incremented by 1... up until n is larger than 20. When it becomes larger, the loop will not execute any longer and exit.

Upvotes: 1

Related Questions