Learn
Loops
The For Loop
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:
- The initialization step sets an initial value for the loop variable. It typically declares a counter variable and assigns it an initial value.
- The condition is evaluated before each iteration. If the condition is true, the loop continues to execute. If it's false, the loop terminates.
- The iteration step updates the loop variable's value after each iteration. It usually increments or decrements the counter variable.
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:
Output:
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 i
becomes 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.
Instructions
Modify the for
loop so that it prints the numbers from 0 to 10 (inclusive).
Invoke the console.log()
function inside the loop to display the value of the variable i
.
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 i
.
Sign up to start coding
Already have an account?
Sign In