Sunday, May 25, 2025

Indexed-for loops

In this article, we’ll cover the indexed-for loop. Its syntax may seem a little more daunting than the do-while or while loops, but it’s always possible to convert a while to a for or vice versa.

For-loops look like this:

for(start state; end condition; variable change rule){
       do this stuff in here;
}

In real Java, you might see something like:

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

How does this loop flow?
  • Before we enter the loop, we create res and give it the value 0
  • Now we are concerned about the loop. Inside it, there’s a counter called i, which is initially 0.
  • We’ll check against the condition i<=10
  • If that check succeeds, we’ll do whatever is in the braces
  • Then we’ll change i according to i++
  • Then we’ll see if we should keep going according to i<=10
  • Then if we should, we’ll do whatever is in the braces, and so on, and if not we exit
  • Once we exit the loop, we print res

Take a second to go back to the while-loop article and compare the while-loop implementation of the sum of the first 10 numbers to the for-loop implementation. Notice anything similar? Different?

No comments:

Post a Comment

Switch

 Other than if/if-else/if-else if-else and the ternary operator, there is yet another common and important conditional expression in Java th...