JavaScript for Loop

Introduction

In JavaScript, a for loop is a construct that facilitates the management of your code flow, enabling the repeated execution of code based on a specified condition. The structure of a for loop in JavaScript is divided into three segments: initialization, condition, and increment/decrement.

Syntax of the for loop

The structure of a for loop in JavaScript can be outlined as follows:

Example

for(initialization; condition; increment/decrement){

//code to be executed

}

Initialization: This refers to an expression or a variable declaration that is assessed a single time prior to the commencement of the loops. It is commonly employed to set a counter variable.

Condition: This refers to an expression that is assessed prior to each iteration of the loop. When this expression results in true, the specified statement will be executed. Conversely, if it evaluates to false, the for loop will cease to run.

Increment/Decrement: This refers to the process of increasing or decreasing the value of the counter, which occurs each time following the execution of the code block.

Flowchart

In JavaScript, the following flowchart illustrates how the for loop operates within the language. It provides a visual representation of the control flow associated with the for loop.

Example 1

A straightforward JavaScript program that displays the numbers from 1 to 5 utilizing a for loop is as follows:

Example

for (let i = 1; i <= 5; i++) {
    console.log(i);
}

In this example:

  • The for loop initializes a variable, i, starting at 1.
  • The condition i <= 5 ensures that the loop will continue executing as long as i is less than or equal to 5.
  • The increment statement i++ increases the value of i by 1 after each iteration.
  • The console.log(i) statement outputs the current value of i to the console during each cycle of the loop.

When executed, this program will print:

Example

1
2
3
4
5

Example

Example

for(let i= 1; i<=5; i++){

    console.log(i);

}

Output:

Output

1

2

3

4

5

Explanation

In this instance, we begin by setting i = 1. The conditional segment evaluates whether i is less than or equal to 5 (i <= 5). The console.log(i); statement outputs the current value to the console. The increment section then raises the value of i to 2, and this process is repeated until i is no longer less than or equal to 5.

Example 2

JavaScript Program to Display a Multiplication Table Using a For Loop

In this tutorial, we will create a JavaScript program that generates and prints a multiplication table using a for loop. This is a fundamental exercise that not only enhances your understanding of loops but also reinforces your ability to work with numbers in JavaScript.

Example Code

Here is a sample implementation of the program:

Example

// Function to print the multiplication table
function printMultiplicationTable(number) {
    console.log(`Multiplication Table for ${number}:`);
    for (let i = 1; i <= 10; i++) {
        console.log(`${number} x ${i} = ${number * i}`);
    }
}

// Calling the function with a specific number
printMultiplicationTable(5);

Explanation

  • Function Definition: We define a function named printMultiplicationTable, which takes one argument, number. This will be the base number for which we are creating the multiplication table.
  • Console Output: Inside the function, we first log a message to indicate which multiplication table is being printed.
  • For Loop: We then utilize a for loop that iterates from 1 to 10. For each iteration, the loop variable i represents the current multiplier.
  • Multiplication and Logging: Within the loop, we calculate the product of number and i, and print the result in the format number x i = result.
  • Function Invocation

To execute the table generation, we call the printMultiplicationTable function with a specific number—in this example, we use 5. This will output the multiplication table for 5 in the console.

Output

When you run the program, the output will be:

Example

Multiplication Table for 5:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

This code snippet provides a clear and effective way to utilize loops in JavaScript to perform repetitive tasks. You can easily modify the input number to generate multiplication tables for any integer.

Example

Example

let p = 3;

for (let q = 1; q <= 10; q++) {

  console.log(p * q); 

}

Output:

Output

3

6

9

12

15

18

21

24

27

30

Explanation

In this snippet, we begin by setting the variable p to 3. Subsequently, a loop is executed 10 times, during which the variable q is initialized at 1 and incremented up to 10. For each iteration corresponding to the value of q, the code computes the product of 3 and q, subsequently displaying the outcome.

Example 3

Here is a JavaScript program that demonstrates how to output the word "Example" five times utilizing a for loop:

Example

for (let i = 0; i < 5; i++) {
    console.log("Example");
}

In this code snippet:

  • The for loop is initialized with a variable i set to 0.
  • The loop will continue to execute as long as i is less than 5.
  • After each iteration, the value of i is incremented by 1.
  • Within the loop, the console.log function is utilized to print "Example" to the console.

When executed, this program will produce the following output:

Example

Example
Example
Example
Example
Example

Example

Example

for(let i= 1; i<=5; i++){

    console.log("Example");

}

Output:

Output

Example

Example

Example

Example

Example

Explanation

In this illustration, we set a variable I to 1, which verifies whether it is less than or equal to 5. After each loop iteration, I is incremented by 1, resulting in the string "Example" being printed to the console a total of 5 times.

JavaScript Nested for Loop

In JavaScript, the nested for loop plays a crucial role in allowing iteration through multi-dimensional data structures or executing intricate operations. This technique involves embedding one loop within another, where the outer loop runs for every iteration of the inner loop.

In JavaScript, this enables various operations, allowing you to construct multi-dimensional arrays and patterns that can be both crucial and effective for data manipulation and navigation.

Syntax

Example

for(initialization; condition; increment/decrement){

    for(initialization; condition; increment/decrement){

       //code to be executed

    }

}

Example 1

//Basic program to display the multiplication table utilizing a for loop.

Example

Example

for (let p = 1; p <= 10; p++) {

    let row = "";

    for (let q = 1; q <= 10; q++) {

        row += (p * q) + "\t";

    }

    console.log(row);

}

Output:

Output

1	2	3	4	5	6	7	8	9	10	

2	4	6	8	10	12	14	16	18	20	

3	6	9	12	15	18	21	24	27	30	

4	8	12	16	20	24	28	32	36	40	

5	10	15	20	25	30	35	40	45	50	

6	12	18	24	30	36	42	48	54	60	

7	14	21	28	35	42	49	56	63	70	

8	16	24	32	40	48	56	64	72	80	

9	18	27	36	45	54	63	72	81	90	

10	20	30	40	50	60	70	80	90	100

JavaScript Pyramid Programs using for Loop

Example 1:

A program to generate an upper pyramid using a for loop can be implemented in various programming languages. Below is an example in Python that demonstrates this concept.

Example

# Function to print the upper pyramid
def upper_pyramid(n):
    # Loop through each row
    for i in range(n):
        # Print spaces for alignment
        for j in range(n - i - 1):
            print(" ", end="")
        # Print stars for the pyramid
        for k in range(2 * i + 1):
            print("*", end="")
        # Move to the next line after each row
        print()

# Input for the number of rows
rows = int(input("Enter the number of rows for the upper pyramid: "))
# Calling the function to display the pyramid
upper_pyramid(rows)

In this code snippet:

  • We define a function named upper_pyramid that takes one parameter, n, representing the number of rows in the pyramid.
  • The first for loop iterates over each row from 0 to n - 1.
  • Inside this loop, a nested for loop is used to print the necessary spaces. The number of spaces decreases with each row, calculated as n - i - 1.
  • A second nested for loop prints the asterisks () for each row. The count of asterisks follows the formula 2 i + 1, creating the pyramid shape.
  • After completing the row, the print function is called to shift to the next line.
  • The program prompts the user to input the number of rows for the upper pyramid and then invokes the upper_pyramid function to display the result.

Feel free to modify the input value to see different sizes of the upper pyramid.

Example

Example

function createPyramid(rows) {

  for (let i = 1; i <= rows; i++) {

    console.log(' '.repeat(rows - i) + '*'.repeat(2 * i - 1));

  }

}



createPyramid(5);

Output:

Output

*

   ***

  *****

 *******

*********

Explanation

The JavaScript snippet outputs a pyramid star pattern to the console utilizing the createPyramid function. This function employs a loop that runs from 1 to the number of rows specified. Within the loop, it generates a string composed of two segments: ' '.repeat(rows - i), which produces a string of spaces whose length corresponds to rows - i.

''.repeat(2 i - 1) generates a string composed of asterisks () that has a length of 2 i - 1. The formula 2 * i - 1 is used to ascertain the quantity of asterisks to be utilized in each level, thereby creating the pyramid structures.

Example 2

Algorithm to display an inverted pyramid using a for loop:

  1. Initiate the number of rows for the pyramid. For example, let's assume the total number of rows is defined as n.
  2. Employ a for loop to iterate through rows in a descending order starting from n down to 1.
  3. Within the outer loop, utilize another for loop to print leading spaces. The number of spaces should be equal to the current row number subtracted from n.
  4. Subsequently, utilize a final for loop to print the asterisks (*). The quantity of asterisks printed should equal double the current row number minus one.
  5. After printing the asterisks for each row, insert a newline character to move to the next line.

Here's a sample implementation in Python:

Example

def inverted_pyramid(n):
    for i in range(n, 0, -1):  # Loop from n to 1
        for j in range(n - i):  # Print leading spaces
            print(" ", end="")  # Stay on the same line
        for k in range(2 * i - 1):  # Print asterisks
            print("*", end="")  # Stay on the same line
        print()  # Move to the next line

# Example usage:
rows = 5
inverted_pyramid(rows)

In this example, if the variable rows is set to 5, the output will resemble the following:

Example

*********
 *******
  *****
   ***
    *

This structure effectively demonstrates how to create an inverted pyramid using nested loops in Python.

Example

Example

function createPyramid(n) {

  for (let i = n; i >= 1; i--) {

    console.log(' '.repeat(n - i) + '*'.repeat(i * 2 - 1));

  }

}

createPyramid(5);

Output:

Output

*********

 *******

  *****

   ***

    *

Explanation

In this illustration, the function accepts an integer n as its argument, denoting the height of the pyramid. The for loop counts down from n to 1. Within each iteration of the loop, two actions are executed: console.log(' '.repeat(n - i) + ''.repeat(i 2 - 1));

n - i generates a sequence of spaces, with the quantity of spaces diminishing as the pyramid ascends.

I * 2 - 1 generates a sequence of asterisks, with the total count of asterisks expanding as the pyramid rises in height.

Subsequently, the two strings are joined together and displayed on the console.

Input Required

This code uses input(). Please provide values below: