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 star pattern in JavaScript in a very simple manner?
Here is a simple star pattern that we are required to print inside the JavaScript console. Note that it has to be printed inside the console and not in the output or HTML window:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Here's the code for doing so in JavaScript:
Example
const star = "* "; // where length is no of stars in longest streak const length = 6; for(let i = 1; iOutput
The console output will be:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *How It Works
The pattern has two parts: an increasing triangle (1 to 6 stars) and a decreasing triangle (5 to 1 stars). The loop runs from 1 to 11 (length*2-1), and the variable
kdetermines how many stars to print:
- For i ? 6: k = i (increasing part)
- For i > 6: k = 12-i (decreasing part)
The String.repeat() function creates n copies of the string, where n is the argument it receives.
Alternative Approach Using Two Loops
const length = 6;
// Increasing part
for(let i = 1; i = 1; i--){
console.log("* ".repeat(i));
}
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Conclusion
This diamond star pattern can be created using a single loop with conditional logic or two separate loops. The time complexity is O(n²) and space complexity is O(1), where n is the pattern length.
