Friday, November 14, 2014

Lesson 6: More on loops

Since loops are so important in programming let's do a few more examples.

Array is variable to store multiple values, referenced by an index. It is very useful to hold data that you can go through each. In Javascript (and C, C++, Java), index starts at 0. Example:

var weekDays = ["Monday","Tuesday","Wednesday","Thursday","Friday"];
alert(weekDays[0]);
alert(weekDays[1]);
alert(weekDays[2]);

// or do this in a loop
for (var i=0; i < weekDays.length; i++) {
  alert(weekDays[i])
}
Now, let's do something more useful. How about I give you a list of number and you tell me which one is largest. In real life, data may be read from a file, but sorry, javascript in browser can't do that.

// Find the largest number
var data = [20,12,15,22,44,98,2]
var largest = 0;
for (var i=0; i < data.length; i++) {
  var n = Number(data[i])
  if (n > largest) {
    largest = n;
  }
}
alert("largest: "+largest);

Now that was hard coded list.

How about you enter from a input text box. separate by comma. The split method lets you easily do that.

  var greetings="Hello how are you"
  var splitted = greetings.split(" ");
  for (var i=0; i < splitted.length; i++) {
     alert(splitted[i]);
  }
Enter a list of numbers (separated by comma):
Your turn: how about you find the smallest number on a list?

Double for loop

You can do loop within a loop. Behold, the multiplication table you spent so much time to remember:

function createmulttable() {
var s= ""
for (var i=1; i < 10; i++) {
  for (var j=1; j < 10; j++) {
    var p = i*j;
    if (p < 10) s = s+" ";
    s = s + i*j+" ";
 }
 s = s+"<br>" // line break
}
document.getElementById("multtable").innerHTML = "<pre>"+s+"</pre>";
}
Make sure you have this div defined:
<div id="multtable"></div>

Sign up Sheet - demonstrating breaking down problem to small ones (and writing functions)

Enter lines:

No comments:

Post a Comment