In programming, repetition is a powerful concept that allows us to perform a task multiple times. One of the most commonly used mechanisms for repetition is the for loop. With the for loop, we can easily automate repetitive tasks and iterate over a specific range of values.
Let's explore the syntax and functionality of the for loop:
Here's how it works:
To demonstrate the for loop in action, let's say we want to print the numbers from 1 to 5 on the console. We can achieve this with the following code:
In this example, the loop starts with
i = 1. As long as
i is less than or equal to
5, the loop will execute. After each iteration, the value of
i is incremented by
1. This continues until
6, which fails the condition, ending the loop.
During each iteration of the loop, we can perform any desired actions or calculations. This could be anything from printing values to the console, updating variables, or even executing complex algorithms.
The for loop is an incredibly handy tool in programming, and mastering it will open up doors to efficient and elegant solutions to common problems.
for loop so that it prints the numbers from 0 to 10 (inclusive).
console.log() function inside the loop to display the value of the variable
Check if the value of
i is divisible by 2 using the modulus operator (
%). If it is, print the message "Even number" after printing the value of
Sign up to start coding
Already have an account?