DEV Community

JckSmith
JckSmith

Posted on

For loops for beginners!

So you are coding your new project, and lo and behold! You are stuck writing line after line of repetitive code. Oh how you wish this was not as tedious and for it just to be over. Luckily for you, there are loops!

Loops allow programmers to write what could be dozens of lines in just a few. They preform code and repeat it as many times as necessary.

For example, say we are trying to make a lot of cookies for a bake sale, but you can only make around a dozen each batch. We can use loops to repeat the steps for us so we do not need to write the many lines of repetitive code!

Syntax

for (initialization condition; testing condition; increment/decrement)
{
    statement(s)
}
Enter fullscreen mode Exit fullscreen mode
  • For loops execute step by step -

  • Initialization condition: You initialize a variable to use for the for loop, which is local for the loop only.

  • Testing condition: Used to exit the loop. Returns a Boolean value, and it is checked before executing the loop.

  • Statement execution: If the Boolean returns as true, it executes the statements in the body of the loop.

  • Increment/Decrement: used to update the variable for next iteration

  • Loop termination: When condition becomes false, the loop terminates, ending it.

Code Example

for (let i = 0; i < 5; i++) {
  nums[i] = i;
  console.log(nums[i]);
}
Enter fullscreen mode Exit fullscreen mode

Code Output

0
1
2
3
4
Enter fullscreen mode Exit fullscreen mode

We can also put for loops into more for loops! This is called nesting, and every time the nested for loop completes, and terminates, the outside for loop increments or decrements once.

Code Example 2

for (let i = 0; i < 2; i++) {
  for(let j = 0; j <2; j++){
  nums[j] = j;
  console.log(nums[j])
  }
}
Enter fullscreen mode Exit fullscreen mode

Code Output 2

0
1
0
1
Enter fullscreen mode Exit fullscreen mode

In conclusion, for loops can be a very useful tool for every programmer that is trying to save as much time, and to be as efficient as possible!

Credit to Ankit Lathiya - Java For Loop: Iteration In Java – Complete Guide

Latest comments (0)