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.


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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-conditional-statements-and-loops-exercise-10.php