CSC103 Lab 3

From dftwiki3
Revision as of 20:13, 12 October 2008 by Thiebaut (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

<meta name="keywords" content="computer science, How Computers Work, Dominique Thiebaut, smith college" /> <meta name="description" content="Dominique Thiebaut's Web Page" /> <meta name="title" content="Dominique Thiebaut -- Computer Science" /> <meta name="abstract" content="Dominique Thiebaut's Computer Science Web pages" /> <meta name="author" content="thiebaut at cs.smith.edu" /> <meta name="distribution" content="Global" /> <meta name="revisit-after" content="10 days" /> <meta name="copyright" content="(c) D. Thiebaut 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,2008" /> <meta name="robots" content="FOLLOW,INDEX" />

Back to CSC103 Weekly Schedule

In this lab you will experience programming a computer at a high level. The high-level language we'll use is Javascript.

Depending on where you are on campus, you may have Dreamweaver installed on your computer. We will use Dreamweaver in this lab, but if it is not available, you can use Notepad or TextEdit just as well. The advantage of Dreamweaver is that it can be used to display the contents of Web pages, which is the environment we're going to work in.


Skeleton Program

Nope, it doesn't have anything to do with the upcoming Halloween! Instead, a skeleton program in computer science refers to a simple program that has all the ingredients found in all programs, without the actual code that makes the program do something interesting.

  • CSC103 Dreamweaver Code.png
    Start Dreamweaver, and click on Code at the top left of the window as shown in the image below. If you do not have Dreamweaver on your computer, use Notepad or TextEdit.



  • Type in the following code in the edit window:
<html><head><title>CSC103 Javascript Program</title></head>
<body>
<h1>My first program</h1>
<script language="JavaScript" type="text/javascript"><!--

//Enter your code below this line:


//Do not write below this line.
//-->
</script>
</body></html>
  • Modify the two captions highlighted in the image below, and personalize them:


CSC103 Dreamweaver.png

  • Save your file on your H: drive, and call it skel.html.
  • View your file!
CSC103 Dreamweaver browser.png 

If you are using Dreamweaver, click on the globe icon, and select one of the browsers listed. If you are not using Dreamweaver, use the browser of your choice (Firefox, Internet Explorer, Safari) and direct it to open a file, and give it the path of your file on your H: drive.


  • Et voila!

CSC103 Javascript skeletong.png

In case you do not have an editor or Dreamweaver available

Use the editor at squarefree.com; just paste the squeleton program in the top window and see the result of its execution in the bottom page.

Printing text on the Web page

Printing text on the Web page in Javascript is done with the command document.write( "..." ); where you replace the ellipsis with the text you want to see appear.

Here's an example, which you should type in your file:

//Enter your code below this line:

document.write( "<h2>Monday, Oct 6, 2008</h2>" );
document.write( "<h3>CSC103 Lab with my partner</h3>" );

//Do not write below this line.
  • If you're in Dreamweaver, save your file with Save As and give it a name such as printText.html. Similarly if you're using Notepad or TextEdit.
  • Load this file in the browser.
  • Modify your printText.html file and make your Javascript program display the following information with two document.write( ... ) statements.
<P>Our class web site can be found <a href="http://cs.smith.edu/~thiebaut/classes/103">here</a>.
<P>The main page for Smith College is <a href="http://www.smith.edu">here</a>.

Note: Alex discovered that because the two lines contain double-quotes already, we need to use single-quotes to "sandwich" the strings for document.write.

Here's the way it should look like:

 document.write( '<P>Our Web site is <a href="http://cs.smith.edu/~thiebaut/classes/103">here</a>.');

Adding comments to your program

Comments are created by putting // on a line of a Javascript program. Everything that follows the // is not read by the browser.

Example:

//Enter your code below this line:

// display the date
document.write( "<h2>Monday, Oct 6, 2008</h2>" );

// display a subtitle
document.write( "<h3>CSC103 Lab with my partner</h3>" );

// show links to useful pages:
document.write( "<P>Our class web site can be found <a href="http://cs.smith.edu/~thiebaut/classes/103">here</a>.");
document.write( "<P>The main page for Smith College is <a href="http://www.smith.edu">here</a>.");

//Do not write below this line.

Using variables to store strings of characters

Most programming languages support variables. A variable is a name assciated with some area of memory containing information that the program needs.

Example:

// Define identity of programmer
var firstName = "Dominique";
var lastName = "Thiébaut";
var office = "McConnell Hall 208";

document.write( "<P>CSC103  Instructor:" + firstName + " " + lastName );

The <P> string is an html tag that starts a new paragraph, forcing the text that follows to be on a new line.

Exercise

  • Modify your Javascript program so that it uses 4 variables for your first name, last name, your class, and for your box number. Make the program output this information so that it displays in this fashion:



Alex Andra , Class of 2010.

Box 1234

Using variables to store numbers

Example:

// Number of operations performed by a 3GHz processor in one second
var numberOpsPerSec =  3000000000; 

// Length of time required for a human being to perform same number of 1-second actions
var numberSeconds =  numberOpsPerSec;
var numberMinutes = numberSeconds / 60;
var numberHours = numberMinutes / 60;
var numberDays = numberHours / 24;
var numberYears = numberDays / 365;

// display the information
document.write( "<P>If a human being were to carry out the same number of" );
document.write( " basic operations a 3 GHz processor performs in one second," );
document.write( " it would take:<P>" );
document.write( numberSeconds + " seconds, or<P>" );
document.write( numberMinutes + " minutes, or<P>" );
document.write( numberHours + " hours, or<P>" );
document.write( numberDays + " days, or<P>" );
document.write( numberYears + " years!" );

Exercise

  • Change the 3000000000 number and replace it by 1000000000.
  • Verify that the program outputs a new series of numbers that are 1/3 the numbers above.


That's what programs are good for! They allow us to encapsulate recipes of actions in scripts and by submitting different inputs to these scripts, we get new outputs!

A Javascript Program that adds two numbers together!

Exercise

  • Using the example of the previous section, write a program that will store two numbers, say 3 and 9 in two different variables, say x and y, and that computes the sum of the two and stores the result in a third variable, say z.
  • Make your program output the result in the following way:


x = 3

y = 9

z = 3 + 9 = 12


  • Modify the line that defines the variable x and store a different number into it:


   var x = 10;


  • Do not modify any other line in your code!
  • Run your program. Verify that the output of the program is consistent with the new change:


x = 10

y = 9

z = 10 + 9 = 19

Loops in Javascript

A typical loop in Javascript looks like this:

  var i;
  for ( i = 1;  i <= 10; i++ ) {

         // javascript statements 

  }

First, we define a variable i which will be our loop counter. Then we have a construct with three clauses:

  • i = 1 : this indicates that when the loop starts, i takes on the value 1.
  • i <= 10 : as long as i is less than or equal to 10, the loop keeps on going.
  • i++ : every time we are done doing all the statements in the body of the loop, i get incremented.

To see this in action, create a new javascript program with the following code in it:

// define loop counter and "accumulator" variable
var i;
var x = 1;

// loop 10 times
for ( i=1; i<=10; i++ ) {
       document.write("Number " + x + " is " + x );
       document.write("<br>");
       x = x + 1;  // double value of x
} 

  • Run it. Do you recognize something we have seen before?
  • Modify the program so that it prints all the numbers between 10 and 20.
  • Modify the program so that it computes and display the sum of all the numbers, from 1 to 10.

Challenging problem of the day

First a story (taken from Wikipedia):


When the creator of the game of chess (in some tellings, an ancient Indian mathematician, in others, a legendary dravida vellalar named Sessa or Sissa) showed his invention to the ruler of the country, the ruler was so pleased that he gave the inventor the right to name his prize for the invention. The man, who was very wise, asked the king this: that for the first square of the chess board, he would receive one grain of wheat (in some tellings, rice), two for the second one, four on the third one and so forth, doubling the amount each time. The ruler, who was not strong in math, quickly accepted the inventor's offer, even getting offended by his perceived notion that the inventor was asking for such a low price, and ordered the treasurer to count and hand over the wheat to the inventor. However, when the treasurer took more than a week to calculate the amount of wheat, the ruler asked him for a reason for his tardiness. The treasurer then gave him the result of the calculation, and explained that it would be impossible to give the inventor the reward. The ruler then, to get back at the inventor who tried to outsmart him, told the inventor that in order for him to receive his reward, he was to count every single grain that was given to him, in order to make sure that the ruler was not stealing from him.


  • Write a Javascript program that displays the number of grains of wheat (or rice) that one must put on the 64th square of the chess board. Your program should display only one number, as follows:


The number of grains of wheat on the 64th square of the board is xxxxxxxxxxxxx.


You must figure out how to make your program compute xxxxxxxxxxxx!
To test your program, make it compute first the number of grains on the 1st square, or the 5th square, for which the answers are easy to check. There should be 1 grain on the first square, and 16 on the 5th square.

Javascript Resources

Here is a list of good resources for learning/playing with Javascript.

  • Tutorials and examples of Javascript code. Try the editor, where you can test code and see the result of executing it in the same window.
  • A complete tutorial from Brown University.

















THE END!










































 var i;
 var sum = 0;
  
  // loop 10 times
  for ( i=1; i<=10; i++ ) {
        document.write("Number " + i + " is " + sum );
        document.write("<br>");
        sum = sum + i;  
 } 
 document.write( "<P>sum = " + sum + "<br>" );



<html>
<head>
<title>Skeleton</title>
</head>
<body>
<h1>My first Javascript Program</h1>
<script language="JavaScript" type="text/javascript"><!--

//Enter your code below this line:

var i;
var rice = 1;

for ( i=1; i<=64; i++ ) {

	document.write( rice + " grains on square " + i + "<br>" );
	rice = rice * 2;
}
rice = rice / 2;
document.write( "<P>" + rice + " grains on the 64th square<br>" );
//Do not write below this line.

//-->
</script>
</body>
</html>