Home  >  Article  >  Web Front-end  >  Diamond Pattern Printing using javascript

Diamond Pattern Printing using javascript

Linda Hamilton
Linda HamiltonOriginal
2024-10-21 22:41:02570browse

Diamond Pattern Printing using javascript

Follow us on instagram for daily coding videos

https://www.instagram.com/webstreet_code/

Introduction

In this video, I’ll show you how to create a colorful diamond pattern using JavaScript. This project is a great way to practice your skills and explore how to manipulate strings and whitespace for alignment in the console.

What You'll Learn

  • How to use loops to create patterns in JavaScript.
  • The importance of string manipulation for formatting output.
  • How to create visually appealing text-based art in the console.

Code Explanation

Here’s the code used to create the diamond pattern:

javascript
function printDiamond(n) {
    let pattern = '';
    const symbol = '?'; // Diamond symbol

    // Upper part of the diamond
    for (let i = 1; i <= n; i++) {
        pattern += ' '.repeat(n - i); // Add leading spaces
        for (let j = 0; j < 2 * i - 1; j++) {
            pattern += symbol + ' '; // Add diamonds with space
        }
        pattern += '\n'; // Move to next line
    }

    // Lower part of the diamond
    for (let i = n - 1; i >= 1; i--) {
        pattern += ' '.repeat(n - i); // Add leading spaces
        for (let j = 0; j < 2 * i - 1; j++) {
            pattern += symbol + ' '; // Add diamonds with space
        }
        pattern += '\n'; // Move to next line
    }

    console.log(pattern);
}

// Set the number of rows (height of the diamond)
let rows = 5; // You can change the number of rows here
printDiamond(rows);

The above is the detailed content of Diamond Pattern Printing using javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn