Shaun
Shaun

Reputation: 463

What is for, for?

I would like to ask you guys a question. You see, I know what a for-loop is for but can someone please maybe explain how one works, just to help me get my head around it, an example is:

for(int i = 0; i < 10; i++) {
    System.out.println("hello");
}

Now obviously that will just print Hello 10 times into the console but that's besides the point, I want to know how the for-loop works.

Sorry if i have confused anyone asking this - Shaun

Upvotes: 0

Views: 217

Answers (3)

Cg2916
Cg2916

Reputation: 1117

Well, this is how it is set up:

for (a; b; c)

"A" is something that is done at the beginning of the loop. It can actually be left out if necessary, like this:

for (; b; c)

"B" must be a true or false statement (like i<10, it either is or it isn't). Once "b" is no longer true, the loop stops.

"C" is something that is done at the end of the loop.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234807

The for loop in your example is more or less equivalent to this:

int i = 0;
while (i < 10) {
    System.out.println("hello");
    i++;
}

The only difference is that with your for loop, the variable i exists only within the scope of the loop.

Every for loop can be transformed into a while loop using this same pattern.

for (init; test; continuation) {
    // loop body
}

becomes:

init;
while (test) {
    // loop body
    continuation;
}

Again, the only difference will be with the scope of any variables declared in init.

Upvotes: 10

Mark Byers
Mark Byers

Reputation: 838276

The for Statement

The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:

for (initialization; termination; increment) {
     statement(s)
}

When using this version of the for statement, keep in mind that:

  • The initialization expression initializes the loop; it's executed once, as the loop begins.
  • When the termination expression evaluates to false, the loop terminates.
  • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

Upvotes: 3

Related Questions