Link to home
Start Free TrialLog in
Avatar of fadi_fadi
fadi_fadi

asked on

out pyramid using Javascript

Dear Expert,

I'm trying to fix this code :

function println(str) {

}

function set_indent(i) {
   var indent = i;
}

function mystr(str) {
   pre = "";
   for (var i=0; i<indent;i++) {
       pre+=" ";
   }
   return pre + str;
}

function printtable(size) {
   set_indent(0);
   println("This is a pyramid");
   for (var i=0; i<size; i++) {
       set_indent(size*2-i);
       s="";
       for (var j=0; j<i*2+1;j++) {
           s += "*";
       }
       println(mystr(s));
   }
}

indent=0;
printtable(5);

to make the output look like this:


This is a pyramid

        *

       ***

      *****

     *******

    *********

But it's doesn't work... Can you help to find the bug in the code?
and help me to finishing the function println.


Thanks
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

function printLn(str) {
  document.write(str);
]

or just replace println with document.write

Be aware that you need to do this inline and have a non=proportional font or write inside <pre></pre> tags

Also this does nothing

function set_indent(i) {
   var indent = i;
}
ASKER CERTIFIED SOLUTION
Avatar of jrm213jrm213
jrm213jrm213
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
this
function set_indent(i) {
   var indent = i;
}

should likely be

var indent=0;
function set_indent(i) {
   indent = i;
}


PS JRM you want the second <pre> to be </pre>
notes:

1. use document.write to write out your str in your println function.
2. declare variable indent at the page/script level instead of inside your function set_indent
3. Actually add the <pre> and </pre> tags to the items you are writing out
line 19 of the script i posted should be

   return pre + str + "<\pre>";
grr...
   return pre + str + "</pre>";
Avatar of fadi_fadi
fadi_fadi

ASKER

there is no other way to rewrite the

function printtable(size) {
   println("This is a pyramid");
   for (var i=0; i<size; i++) {
       set_indent(size*2-i);
       s="";
       for (var j=0; j<i*2+1;j++) {
           s += "*";
       }
message ID:36345703

I am not sure what you are asking. You want to write that function differently?

Of course. Million of ways

This one does not QUITE make it, but I am off to bed

document.write("<pre>")
var stars = "***********";
var indents = "            ";
for (var indent = 10;indent>0;indent--) {
  document.write("\n"+indents.substring(0,indent/2)+stars.substring(indent,stars.length));
}
document.write("</pre>")
give one way of the millon?
I just did - did you not see the code?

Here is a demo http://jsfiddle.net/mplungjan/Cyyy5/
a little crooked but I suck at math
Of course i did,
But I mean the function printtable.
Thanks
Thanks Experts
A split would have been nice