The for loop is a powerful tool that allows us to iterate over a block of code multiple times. It consists of three components: initialisation, condition, and increment. Let's see how it works:
In this example, we initialise a variable
i to 0. The condition
i < 5 specifies the limit for the loop. As long as the condition is true, the loop will continue executing. After each iteration, the increment
i++ increases the value of
i by 1.
Inside the loop, we can perform any desired operations, such as printing values, manipulating data, or executing specific tasks. The loop will repeat the code block until the condition becomes false.
lets have another example to make thing much easier,
This code creates an array of numbers. It then initialises an empty array called multipliedNumbers. Using a for loop, it iterates over each element in the numbers array and multiplies it by 2. The multiplied numbers are then pushed into the multipliedNumbers array. Finally, the multipliedNumbers array is logged to the console.