Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to print a triangle formed of '#' using JavaScript?
In this tutorial, we will learn to print a triangle formed of '#' using JavaScript.
You need to use nested loops to print a triangle formed of '#' in JavaScript. The outer loop controls the number of rows, while the inner loop controls how many '#' symbols to print in each row.
Nested loops are loops that contain another loop inside them. We'll explore two approaches using different types of loops in JavaScript:
- for loop
- while loop
Using for Loop to Print a Triangle
The for loop is ideal for this task because we know exactly how many iterations we need. The outer loop runs for each row, and the inner loop prints the '#' symbols for that row.
Syntax
for (i = 0; i < rows; i++) {
for (j = 0; j <= i; j++) {
// Print '#' symbol
}
// Move to next line
}
Algorithm
- STEP 1 ? Initialize outer for loop to control rows
- STEP 2 ? Initialize inner for loop to print '#' symbols
- STEP 3 ? Print '#' from inner loop and create line breaks
Example
Here's a complete example that prints a triangle of '#' symbols in the browser:
<html>
<body>
<h2>Triangle Pattern Using <i>for loop</i></h2>
<div id="triangle1"></div>
<script>
var triangle = "";
for (var i = 0; i < 7; i++) {
for (var j = 0; j <= i; j++) {
triangle += " #";
}
triangle += "<br>";
}
document.getElementById("triangle1").innerHTML = triangle;
</script>
</body>
</html>
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
Using while Loop to Print a Triangle
The while loop provides more control over the iteration process. We need to manually manage the loop variables and their increments.
Syntax
var i = 0;
while (i < rows) {
var j = 0;
while (j <= i) {
// Print '#' symbol
j++;
}
// Move to next line
i++;
}
Algorithm
- STEP 1 ? Initialize variables and outer while loop
- STEP 2 ? Initialize inner while loop for each row
- STEP 3 ? Print '#' and increment inner counter
- STEP 4 ? Reset inner counter and increment outer counter
Example
Here's how to create the same triangle pattern using while loops:
<html>
<body>
<h2>Triangle Pattern Using <i>while loop</i></h2>
<div id="triangle2"></div>
<script>
var triangle = "";
var i = 0;
while (i < 7) {
var j = 0;
while (j <= i) {
triangle += " #";
j++;
}
triangle += "<br>";
i++;
}
document.getElementById("triangle2").innerHTML = triangle;
</script>
</body>
</html>
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
Comparison
| Method | Code Complexity | Best Use Case |
|---|---|---|
| for loop | Simpler | Known number of iterations |
| while loop | More verbose | Dynamic conditions |
Conclusion
Both for and while loops can create triangle patterns effectively. The for loop is generally preferred for this task due to its cleaner syntax and built-in counter management.
