Function to create diamond shape given a value in JavaScript?


You can create your own function to create diamond shapes for a given value. Following is the code −

Example

function createDimondShape(size){
   for(var i=1;i<=size;i++){
      for(var s=size-1;s>=i;s--){
         process.stdout.write(" ");
      }
      for(var j=1;j<=i;j++){
         process.stdout.write("* ")
      }
      console.log();
   }
   if(i==size+1){
      for(var i=1;i<=size-1;i++){
         for(var s=1;s<=i;s++){
            process.stdout.write(" ");
         }
         for(j=i;j<=size-1;j++){
            process.stdout.write("* ");
         }
         console.log();
      }
   }
}
createDimondShape(9);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo58.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo58.js
           *
          * *
         * * *
        * * * *
       * * * * *
      * * * * * *
     * * * * * * *
    * * * * * * * *
   * * * * * * * * *
    * * * * * * * *
     * * * * * * *
      * * * * * *
       * * * * *
        * * * *
         * * *
          * *
           *

Updated on: 03-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements