w3resource

JavaScript: Construct a pattern, using a nested for loop

JavaScript Conditional Statement and loops: Exercise-10 with Solution

Pyramid Pattern with Nested Loop

Write a JavaScript program to construct the following pattern, using a nested for loop.

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

Visual Presentation:

JavaScript: Construct a pattern, using a nested for loop

Sample Solution:

JavaScript Code:

// Variables to control loop counters and character output
var x, y, chr;

// Outer loop for rows
for (x = 1; x <= 6; x++) {
    // Inner loop for characters in each row
    for (y = 1; y < x; y++) {
        // Accumulate asterisks in the 'chr' variable
        chr = chr + ("*");
    }

    // Print the accumulated characters for the current row
    console.log(chr);

    // Reset 'chr' for the next row
    chr = '';
} 

Flowchart:

Flowchart: JavaScript:- Construct a pattern, using a nested for loop

Live Demo:

See the Pen javascript-conditional-statements-and-loops-exercise-10 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that prints a pyramid pattern of stars with 5 levels using nested loops and string repetition.
  • Write a JavaScript function that constructs a centered pyramid pattern with increasing numbers instead of stars.
  • Write a JavaScript function that generates a pyramid pattern of stars using string padding to center-align each row.
  • Write a JavaScript function that builds a pyramid pattern recursively instead of using nested loops.

Improve this sample solution and post your code through Disqus.

Previous:Write a JavaScript program to find the armstrong numbers of 3 digits.
Next:Write a JavaScript program to compute the greatest common divisor (GCD) of two positive integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.