Question:

How do you create a pyramid using javascript ?

by  |  earlier

0 LIKES UnLike

using asterisks ... or whatever you want .

 Tags:

   Report

1 ANSWERS


  1. Try something like this:

    <html>

    <head>

    <title>Pyramid Tester</title>

    <script language="javascript" type="text/javascript">

    function buildPyramid()

    {

    var num = document.getElementById("number");

    var sNum = num[num.selectedIndex].value;

    if(sNum != "")

    {

    var pyramid = document.getElementById("pyramid");

    var number = parseInt(sNum);

    var sOutput = calculatePyramid(number);

    pyramid.innerHTML = sOutput;

    }

    }

    function calculatePyramid(numb)

    {

    var sOutput = "";

    var sNumber = numb;

    var length = (2 * sNumber) - 1;

    var middle = parseInt(length/2);

    var startVal = 1;



    for(middle;middle>=0;middle--)

    {

    var x = middle;

    for(x;x>=0;x--)

    {

    sOutput = sOutput + " ";

    }

    for(var y = 1; y <= startVal; y++)

    {

    sOutput = sOutput + "* ";

    }

    sOutput = sOutput + "
    ";

    startVal++;

    }



    return sOutput;

    }

    </script>

    </head>

    <body>

    Choose number of levels for pyramid: 

    <select name="number" id="number" onchange="buildPyramid();">

    <option value="">Please Choose...</option>

    <option value="1">1</option>

    <option value="2">2</option>

    <option value="3">3</option>

    <option value="4">4</option>

    <option value="5">5</option>

    <option value="6">6</option>

    <option value="7">7</option>

    <option value="8">8</option>

    <option value="9">9</option>

    <option value="10">10</option>

    </select>

    <div id="pyramid">

     

    </div>

    </body>

    </html>

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.