/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] Not sure which type of Loop to use & should I use Break & Continue

My assignment, and I realize this is pretty basic stuff:

[COLOR=”#0000CD”]Write a JavaScript program embedded in a HTML document with the following requirements:
• Request the user to enter a number
• Check if the user input is not empty. Also check value entered is a number
• Write on the html document a triangle out of the numbers as follow:
E.g. output: (let’s say the user entered number 10)
Your input number is 10.
10
11 11
12 12 12
13 13 13 13
14 14 14 14 14
15 15 15 15 15 15
• The triangle should have 6 rows.
• Use Comments explaining how the program works[/COLOR]

My Code so far ( what little there is):

[CODE]<script type=”text/javascript”>

var myNumber = prompt (“Please enter a number”, 1);
var myRows = 6;
var loopCounter;

if ((isNaN(myNumber)) || (myNumber == 0 )) //Working.
{
alert(“Please enter a number.”);
window.location.reload();
}

document.write(“Your input number is ” + myNumber + “.” + “<BR>”);

for (loopCounter = 0; loopCounter <= 19; loopCounter++)
{

document.write(myNumber);
}

</script>
[/CODE]

This comes as I read the chapter on Decisions, Loops, and Functions. So I assume it involves a loop to count the number of rows and columns.

I’ve been looking as the JavaScript Loop examples in W3Schools as they are easier to follow than the text book. My thoughts are it should be a While Loop although I couldn’t get even the little bit of code I have to run using While.

In my head I should be taking myNumber and increasing it by one more than the input number and displaying it once. By using the ++ I should be able to increase the original myNumber by one and increase the number of times it’s displayed and so on based on the previous output until 6 rows are displayed. I can’t sort out how to get there.

Thank you!

to post a comment
JavaScript

13 Comments(s)

Copy linkTweet thisAlerts:
@deathshadowOct 14.2014 — Again... educators... bah.

1) if you have multiple VAR, you only need to say VAR once and then comma delimit them.

2) Don't use double quotes if your not using complex parsing...

3) As with one of your previous posts, avoid wasting bandwidth on window.location.reload -- seriously whoever is teaching you that needs a good hard slap in the face with a wet trout. Just loop the prompt until they enter a valid value.

4) You would need a loop nested in a loop with a separate counter as the maximum value.

Something like...


&lt;script type="text/javascript"&gt;

<i> </i>var
<i> </i> values,
<i> </i> rowCount = 6,
<i> </i> colCount = 0;
<i> </i> errorText;

<i> </i>do {
<i> </i> value = prompt(errorText + 'Please enter a number', 1);
<i> </i> errorText = (
<i> </i> (isNan(value) || (value == 0)) ?
<i> </i> "Please enter a non-zero numberrn" :
<i> </i> false
<i> </i> );
<i> </i>} while (errorText);

<i> </i>document.write('You entered ' + myNumber + '&lt;BR&gt;');

<i> </i>for (var i = 0; i &lt; rowCount; i++) {
<i> </i> for (var j = 0; j &lt; colCount; j++) document.write(value + ' ');
<i> </i> document.write('&lt;br /&gt;');
<i> </i> value++;
<i> </i> colCount++;
<i> </i>}

&lt;/script&gt;


Would do the job.
Copy linkTweet thisAlerts:
@BlondieCauthorOct 14.2014 — You are becoming my hero! This is the first course that I'm wishing I hadn't taken although I think it's more the instructor I'm struggling with. I need to keep the two separate as I want to continue to have a desire for learning this and not being brought to tears out of frustration. My current course text is Beginning JavaScript by Paul Wilton and Jeremy McPeak - do you have any suggestions as to what may help me with this? I found HTML fairly easy and was hoping I'd catch onto this the same way.

I didn't know about the multiple var - it hasn't been in the text or our notes and yet time and time again I find myself dealing with more than one var. Shouldn't the rowCount have a [COLOR="#0000CD"];[/COLOR]?

The text and course notes also use new array, yet W3Schools advises against it so I've gone with their advise of just using array and also found some reading as to why and as to how the new array came into play. At least I'm clear on this one now.

I need to break apart what your coded so I understand.

  • - values - is this what I previously has as myNumber? Why would it be left undefined?

  • - colCount - if the instructor has specified the column count as he did the rowCount would it be best practice to also include that number?

  • - the r and n I know from my text.

  • - is the [COLOR="#0000CD"]i[/COLOR] for iteration?

  • - where does the [COLOR="#0000CD"]j[/COLOR] come from?


  • I tried running it but it didn't work. Is that because it still has [COLOR="#0000CD"]myNumber[/COLOR] in the document.write?
    Copy linkTweet thisAlerts:
    @deathshadowOct 14.2014 — my bad, the colCount shoud NOT have a semi-colon. All but the last one should be comma's. Last one in a 'set' of VAR always gets a semi-colon saying 'this is the end of the statemet'.

    Be leery of W3Schools since they are horiffically bad web-rot filled with inaccuracies. Just in case you are unaware they have absolutely NOTHING to do with the W3C and are NOT affiliated with it in any way. If you need a flat reference you are better off sticking to the one on MDN.

    "Values" -- the prompt assigns it, though that should be "value", not values. Gah, typo's galore. What I get for typing it in the quick reply box instead of a real editor. I also screwed up the inner loop which should be <= 0 since we start from zero, and mistyped isNan instead of isNaN. (I [b]HATE[/b] case sensitive programming langauges)

    "colCount" starts at zero because we only want one repeat the first row. We increment it inside the outer loop so that each row after has one more repeat than the last.

    Most developers use i, j, and k as standard 'temporary' counters. You look at most C syntax code (and JS is a C syntax language) you'll see them used. Some other languages use t, n, v. I'm not aware of the origin of this, but it's standard practice nonetheless.

    http://en.wikipedia.org/wiki/Loop_counter

    Here's a version without the typo's.

    &lt;script type="text/javascript"&gt;

    <i> </i>var
    <i> </i> value,
    <i> </i> rowCount = 6,
    <i> </i> colCount = 0,
    <i> </i> errorText;

    <i> </i>do {
    <i> </i> value = prompt(errorText + 'Please enter a number', 1);
    <i> </i> errorText = (
    <i> </i> (isNaN(value) || (value == 0)) ?
    <i> </i> "Please enter a non-zero numberrn" :
    <i> </i> false
    <i> </i> );
    <i> </i>} while (errorText);

    <i> </i>document.write('You entered ' + value + '&lt;BR&gt;');

    <i> </i>for (var i = 0; i &lt; rowCount; i++) {
    <i> </i> for (var j = 0; j &lt;= colCount; j++) document.write(value + ' ');
    <i> </i> document.write('&lt;br /&gt;');
    <i> </i> value++;
    <i> </i> colCount++;
    <i> </i>}

    &lt;/script&gt;


    So my bad. I really shouldn't post untested code from the laptop. Can't type on those rinky flat zero travel keyboards worth ****.
    Copy linkTweet thisAlerts:
    @deathshadowOct 14.2014 — Oh, and thinking on it, I see no reason to trap just zero since it's passing negative numbers, and it might be a good idea to trap "cancel" returning null. Actually running it, I cleaned it up a bit more since the prompt was outputting 'undefined' -- my bad. Thankfully an empty string can also be treated as 'false'.

    &lt;script type="text/javascript"&gt;

    <i> </i>var
    <i> </i> value,
    <i> </i> rowCount = 6,
    <i> </i> colCount = 0,
    <i> </i> errorText = '';

    <i> </i>do {
    <i> </i> value = prompt(errorText + 'Please enter a number', 1);
    <i> </i> errorText = (
    <i> </i> (value != null &amp;&amp; isNaN(value)) ?
    <i> </i> "Error, you entered a non-numeric value, try again.rn" :
    <i> </i> ''
    <i> </i> );
    <i> </i>} while (errorText);

    <i> </i>if (value == null) {

    <i> </i> document.write('You have cancelled this program.');

    <i> </i>} else {

    <i> </i> document.write('You entered ' + value + '&lt;BR&gt;');

    <i> </i> for (var i = 0; i &lt; rowCount; i++) {
    <i> </i> for (var j = 0; j &lt;= colCount; j++) document.write(value + ' ');
    <i> </i> document.write('&lt;br /&gt;');
    <i> </i> value++;
    <i> </i> colCount++;
    <i> </i> }

    <i> </i>}

    &lt;/script&gt;
    Copy linkTweet thisAlerts:
    @BlondieCauthorOct 15.2014 — Hey! Thank you for the additional comments and explanations - I'm saving those so I have them to refer to. And thanks for the heads up on W3Schools. In my two HTML courses there was a real focus on W3C and I printed of a binder full of their documentation to refer to. I wasn't sure if W3Schools was associated with them or not and now I know.

    Where and how did you learn JavaScript? Knowing all the little tips is also very helpful. I picked up on the Nan thing and realized it was just a keystroke thing - that one I've read over a few times in my text.

    What is MDN? I had something else to ask too - I should have written down at work.

    By the way... helping me also helped another person in the course who was stuck on getting number 10 to appear on the first row as the instructor had not replied to her email asking for help - so we both thank you.
    Copy linkTweet thisAlerts:
    @deathshadowOct 15.2014 — Where and how did you learn JavaScript?[/quote]
    Well, I had been programming C for about fifteen years before I ever even HEARD of JavaScript... so for me all I needed to "learn" javascript was a decent reference. JS is a C syntax language, and for the most part the minor differences in syntax and object implementation are minor at best. I've also been using JS for about almost a decade and a half, so I've got a decent bit of experience under my belt.

    Pretty much I've been programming since 1977, starting out in RCA 1802 machine language... can even hand assemble Z80, 6502, 6809 and 8088 machine language -- along the way I've done Pascal, C, ADA, Fortran, DiBOL, COBOL, Paradox -- so I come at coding with a slightly different view than most people.

    It's actually really hard for me to point people at good learning sources, because when it comes to the "common sense" of programming, there's been little if anything released for books or tutorials in close to two decades... which is why a hefty chunk if not the vast majority of stuff people vomit up and call a website fails to meet even the simplest of well established "good practices"

    What is MDN?[/quote]
    Mozilla Developer Network -- They have a very good online reference for JavaScript... I used to think it was excellent until I started finding really bad code in their polyfills and examples, but I tend to have a much higher standard than most people. Much of the code flubs read like piss poor ports from C code where the nuances of JavaScript were outright ignored.

    Still, it's probably the best I've found online so far:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript
    Copy linkTweet thisAlerts:
    @BlondieCauthorOct 15.2014 — You have a VERY extensive background. You've mentioned languages I've never heard of. You must get your brain picked constantly for "how to" stuff. There isn't a single person in my workplace that knows JavaScript - most don't know what it is.

    In your code, why is var value not defined as a number?
    Copy linkTweet thisAlerts:
    @BlondieCauthorOct 15.2014 — I remembered the other thing I wanted to ask - debuggers - suggestions for one I can use and understand? We haven't covered this and yet I thought we should have at the beginning.
    Copy linkTweet thisAlerts:
    @BlondieCauthorOct 15.2014 — Still looking at both sets of your code and seeing where you made the changes and just getting a feel for reading it.

    With the second code the [COLOR="#0000CD"]document.write[/COLOR] line after[COLOR="#0000CD"] if (value == null)[/COLOR] isn't executing. This line is skipped and the rest of the program executes with [COLOR="#0000CD"]You entered[/COLOR] blank, then blank on the first row then the rest of the numbers fill in.

    It won't be caught higher up as your code is checking for a non empty cell and a value that is not a number. But the [COLOR="#0000CD"]if (value == null)[/COLOR] should catch it and then write the message. I noticed the [COLOR="#0000CD"]var errorText[/COLOR] is different in both blocks of code - it looks like in the second block the[COLOR="#0000CD"] ' '[/COLOR] catches the user input after the try again message which the first block didn't have so this shouldn't be the cause.
    Copy linkTweet thisAlerts:
    @BlondieCauthorOct 15.2014 — Still going through everything. If I click the cancel button I then see the [COLOR="#0000CD"]"You have cancelled this program"[/COLOR] line. I was expecting to see that if I manually deleted the number out of the input box.
    Copy linkTweet thisAlerts:
    @BlondieCauthorOct 15.2014 — I changed [COLOR="#0000CD"]if (value == null)[/COLOR] to [COLOR="#0000CD"]if (!value)[/COLOR] and when I manually delete the number from the user input box so that it's empty, the message writes.
    Copy linkTweet thisAlerts:
    @deathshadowOct 15.2014 — With the second code the [COLOR="#0000CD"]document.write[/COLOR] line after[COLOR="#0000CD"] if (value == null)[/COLOR] isn't executing.[/quote]
    Should only run if you hit the "cancel" button or press the ESC key during the prompt. That's the only time VALUE should be null. A "blank" entry shouldn't make it past isNaN, unless there's something screwy with a certain browser implementation. That's where testing across multiple browsers comes into play. (and also why quite literally zero REAL software uses "prompt" anymore)

    Don't have to assign "value" a value as it's immediately assigned a value inside the do/while... that's the first thing the do/while does!

    The second one was also flawed on logic, again what I get for not testing. The third is the only properly "working" one. Technically in the third and final example the "errorText" when pre-declared/allocated doesn't need the ="" either, as the inline conditional is assigning it a value as well.
    Copy linkTweet thisAlerts:
    @BlondieCauthorOct 16.2014 — Thank you for answering all of my questions and helping me understand this and what I'm doing. It's helping me to stay positive and interested in JavaScript. I won't let the experience of the wrong instructor for me keep me from learning and enjoying this.
    ×

    Success!

    Help @BlondieC spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.18,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...