#163 – Iterating Using the for Loop

The for statement allows executing a block of code a fixed number of times.

You could use a while loop to execute a block of code a fixed number of times:

            int i = 1;
            int sum = 0;

            // Add up numbers 1-10
            while (i <= 10)
            {
                sum += i;
                i++;
            }

You can do this a little more conveniently using a for loop.

            int sum = 0;

            // Add up numbers 1-10
            for (int i = 1; i <= 10; i++)
                sum += i;

The expression after the for keyword includes three clauses, separated by a semicolon:

  • The initialization clause specifies variables to initialize before the loop starts executing
  • The condition clause specifies the conditions under which the loop continues to execute
  • The iteration clause specifies an operation to perform after executing the body of the loop
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: