CS 80: Internet Programming
Instructor: Mark Edmonds
Algorithm
Pseudocode
Pseudocode
// leap year pseudocode
if year is divisible by 400 then
is_leap_year
else if year is divisible by 100 then
not_leap_year
else if year is divisible by 4 then
is_leap_year
else
not_leap_year
Pseudocode
leapYear = false
if year % 400 == 0
leapYear = true
else if year % 100 != 0 and year % 4 == 0
leapYear = true
Pseudocode
leapYear = false
if year % 400 == 0 or (year % 100 != 0 and year % 4 == 0)
leapYear = true
if...else
statement, our
programs executed sequentially
if...else
introduced branching,
or a conditional jump, meaning the program
would "choose a fork in the road" based on some boolean
evaluation
if...else
gave us control over what
program statements to executes for cases we cared
aboutgoto
statement
goto
statementif...else
)while, do...while, for, for...in
)Javascript Keywords
if
statement
if
is a
single-selection statement. It selects
or ignores a single action (program
statement(s))if
statement
as having a single entry point and single exit
pointif...else
statement
if...else
is a
double-selection statement
Ternary Operator (Conditional Operator)
We can shorthand the if else statement with a ternary operator of the following form:
cond ? true_action : false_action
Example:
document.writeln( student_grade >= 60 ? "Passed" : "Failed" ); // immediately using the result
var courseResult = student_grade >= 60 ? "Passed" : "Failed"; // assignment to the result
Ternary Operator (Conditional Operator)
if...else
student_grade
was 50,
this the same as calling
document.writeln("Failed");
or
assigning pass_fail = "Failed";
else
'sif...else
statements
{}
, which start a block
statement
else
'sVariable Scope
Example block statement:
// javascript blocks and scope
var a1 = 3;
{
var a2 = 5;
}
console.log(a1 + a2);
This behavior is different from C/C++!
else
'sVariable Scope
a2
would be out of scopea2
would be from its
declaration to its closing curly braceif...else
...else
'sif...else
's?else
'sConsider the following possibilities (hint: the indentation does not affect the semantic meaning)
// dangling else's
if ( x > 5 )
if ( y > 5 )
document.writeln( "<p>x and y are > 5</p>" );
else
document.writeln( "<p>x is <= 5</p>" );
// dangling else's
if ( x > 5 )
if ( y > 5 )
document.writeln( "<p>x and y are > 5</p>" );
else
document.writeln( "<p>x is <= 5</p>" );
else
'sThe first indentation reflects the semantics. Why?
// dangling else's
if ( x > 5 )
if ( y > 5 )
document.writeln( "<p>x and y are > 5</p>" );
else
document.writeln( "<p>x is <= 5</p>" );
// dangling else's
if ( x > 5 )
if ( y > 5 )
document.writeln( "<p>x and y are > 5</p>" );
else
document.writeln( "<p>x is <= 5</p>" );
else
'sif
if...else
is considered a single
conditional statementif
the
else
belongs toelse
'sFix:
// dangling else's
if ( x > 5 ){
if ( y > 5 )
document.writeln( "<p>x and y are > 5</p>" );
} else
document.writeln( "<p>x is <= 5</p>" );
I (personally) recommend always wrapping conditionals, loops, etc. with block statements:
// dangling else's
if ( x > 5 ) {
if ( y > 5 ){
document.writeln( "<p>x and y are > 5</p>" );
}
} else {
document.writeln( "<p>x is <= 5</p>" );
}
else
'sConsider another error-prone situation:
// dangling else's
if ( grade >= 60 )
document.writeln( "<p>Passed</p>" );
else
document.writeln( "<p>Failed</p>" );
document.writeln( "<p>You must take this course again.</p>" );
Under what circumstances will "You must take this course again" be printed to the user?
else
's// dangling else's
if ( grade >= 60 )
document.writeln( "<p>Passed</p>" );
else
document.writeln( "<p>Failed</p>" );
document.writeln( "<p>You must take this course again.</p>" );
The Javascript interpreter does not read indentation for semantics
The last line is not associated with the
else
Semantic version:
// dangling else's
if ( grade >= 60 )
document.writeln( "<p>Passed</p>" );
else
document.writeln( "<p>Failed</p>" );
document.writeln( "<p>You must take this course again.</p>" );
else
'sFix:
// dangling else's
if ( grade >= 60 )
document.writeln( "<p>Passed</p>" );
else {
document.writeln( "<p>Failed</p>" );
document.writeln( "<p>You must take this course again.</p>" );
}
else
'selse
'sif
and else
will
associate with the next statementif...else
.+
for a *
.Repeat an action a number of times while a condition is true
Example shopping pseudocode:
While there are more items on my shopping list
Purchase next item and cross it off my list
When the condition becomes false, the loop exits
Critical part: the loop must do something that will eventually cause the condition to be false
Example for shopping:
// shopping list
var shopping_list = ["pants", "grocercies", "car"];
var i = 0;
// purchase all items in the list
while(i < shopping_list.length)
{
purchase(shopping_list[i]); // purchase the item
i = i + 1; // move to the next item
}
function purchase(item){
window.alert("Purchased " + item);
}
If you think visually, consider the following code flowchart
var product = 2;
while ( product <= 1000 )
{
product = 2 * product;
}
If you think visually, consider the following code + flowchart
We can think about a loop as a repeated cycle in a flowchart until a condition becomes false
Class Average
Class Average
Pseudocode:
Set total to zero
Set grade counter to zero
Input number of students
Print table header
While grade counter is less than number of students
Input the next grade
Add the grade into the total
Add one to the grade counter
Print grade to table
Set the class average to the total divided by number of students
Print the class average to table
class_average.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Class Average Problem</title>
<style>
table,
th,
td {
border: 1px solid black;
}
table {
border-collapse: collapse;
}
th,
td {
padding: 15px;
text-align: left;
}
</style>
<script>
var total; // sum of grades
var gradeCounter; // number of grades entered
var grade; // grade typed by user
var average; // average of all grades
// initialization phase
total = 0; // clear total
gradeCounter = 0;
var numStudents = window.prompt("Enter the number of students: ", "0");
numStudents = parseInt(numStudents);
if (numStudents == 0)
{
document.writeln("The number of students is 0");
}
else
{
//setup table
document.writeln("<table>");
document.writeln("<caption><strong>Exam scores</strong></caption>");
document.writeln("<thead>\n<tr>\n<th>Student Number</th>\n<th>Grade</th>\n</thead>");
document.writeln("<tbody>");
// loop, processing phase
while (gradeCounter < numStudents) {
// prompt for input and read grade from user
grade = window.prompt("Enter integer grade:", "0");
// convert grade from a string to an integer
grade = parseInt(grade);
// add gradeValue to total
total = total + grade;
// add 1 to gradeCounter
gradeCounter = gradeCounter + 1;
// add data to table
document.writeln("<tr>\n<td>" + gradeCounter + "</td>\n<td>" + grade + "</td>\n</tr>");
} // end while
// calculate the average
average = total / numStudents;
// display average of exam grades
document.writeln("</tbody>");
document.writeln("<tfoot>\n<tr>\n<th>Average</th>\n<th>" + average + "</th>\n</tr>\n</tfoot>");
document.writeln("</table>");
}
</script>
</head>
<body>
</body>
</html>
class_average_functions.html
class_average_functions.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Class Average Problem</title>
<style>
table,
th,
td {
border: 1px solid black;
}
table {
border-collapse: collapse;
}
th,
td {
padding: 15px;
text-align: left;
}
</style>
<script>
function collectGrades() {
var total; // sum of grades
var gradeCounter; // number of grades entered
var grade; // grade typed by user
var average; // average of all grades
var grades = []; // array to store grades
// initialization phase
total = 0; // clear total
gradeCounter = 0;
var numStudents = window.prompt("Enter the number of students: ", "0");
numStudents = parseInt(numStudents);
// loop, processing phase
while (gradeCounter < numStudents) {
// prompt for input and read grade from user
grade = window.prompt("Enter integer grade:", "0");
// convert grade from a string to an integer
grade = parseInt(grade);
// add gradeValue to total
total = total + grade;
// add 1 to gradeCounter
gradeCounter = gradeCounter + 1;
// add grade to our grades array
grades.push(grade);
} // end while
return grades;
}
function displayGrades(grades, average){
if (grades.length == 0)
{
document.writeln("The number of students is 0");
return;
}
//setup table
document.writeln("<table>");
document.writeln("<caption><strong>Exam scores</strong></caption>");
document.writeln("<thead>\n<tr>\n<th>Student Number</th>\n<th>Grade</th>\n</thead>");
document.writeln("<tbody>");
// loop, processing phase
for(var i = 0; i < grades.length; i++) {
// add data to table
document.writeln("<tr>\n<td>" + i + "</td>\n<td>" + grades[i] + "</td>\n</tr>");
} // end while
// display average of exam grades
document.writeln("</tbody>");
document.writeln("<tfoot>\n<tr>\n<th>Average</th>\n<th>" + average + "</th>\n</tr>\n</tfoot>");
document.writeln("</table>");
}
function calculateAverage(array){
// loop over grades to calculate average
var average = 0;
if (array.length > 0){
for(var i = 0; i < array.length; i++){
average += array[i];
}
average /= array.length;
}
return average;
}
var grades = collectGrades();
var average = calculateAverage(grades);
displayGrades(grades, average);
</script>
</head>
<body>
</body>
</html>
Real Estate License
Real Estate License
Real Estate License
Pseudocode:
Initialize passes to zero
Initialize failures to zero
Initialize student to zero
While student counter is less than ten
Input the next exam result
If the student passed
Add one to passes
Else
Add one to failures
Add one to student counter
Print the number of passes
Print the number of failures
If more than eight students passed
Print "Bonus to Instructor!";
bonus.html
<!DOCTYPE html>
<!-- Fig. 7.11: analysis.html -->
<!-- Examination-results calculation. -->
<html>
<head>
<meta charset="utf-8">
<title>Analysis of Examination Results</title>
<script>
// initializing variables in declarations
var passes = 0; // number of passes
var failures = 0; // number of failures
var student = 0; // student counter
var result; // an exam result
// process 10 students; counter-controlled loop
while (student < 10) {
result = window.prompt("Enter result (1=pass,2=fail)", "0");
if (result == "1")
{
passes = passes + 1;
}
else
{
failures = failures + 1;
}
student = student + 1;
} // end while
document.writeln("<h1>Examination Results</h1>");
document.writeln("<p>Passed: " + passes +"; Failed: " + failures + "</p>");
if (passes > 8)
{
document.writeln("<p>Bonus to instructor!</p>");
}
</script>
</head>
<body></body>
</html>
Modifying a variable (changing its value) is extremely common. We have a shorthand way doing this:
c = c + 3;
c += 3;
More generally, any statement of the form:
variable = variable operator expression;
Can always be written as:
variable operator= expression; // operator could be +, -, *, /, %
// for example
c *= 4; // multiply by 4
*
, /
,
%
Consider the following. Carefully consider the value
of counter1
and counter2
:
var a = 10;
var counter1 = 0;
var counter2 = 0;
var i = 0;
while(counter1++ < a)
{
//loop 1
console.log("Loop 1, i: ", i);
i++;
}
i=0;
while(++counter2 < a)
{
//loop 2
console.log("Loop 2, i: ", i);
i++;
}
console.log(counter1);
console.log(counter2);
counter1
and counter2
?counter1
and counter2
?
counter1
will be 11 (loop 1 runs 10
times, but counter1 is incremented an extra time
(postincrement))counter2
will be 10 (loop 2 runs 9
times)for
while
for(initialization_statement; loop_condition; loop_end_statement)
{
// loop body
}
// in practice
for (var i = 0; i < 10; i++)
{
// loop body
}
// which is the same as
var i = 0;
while (i < 10){
i++;
}
do...while
var i = 0;
do {
// loop body
i++;
}
while(i < 10);
sortedList.html
<!doctype html>
<!-- sortedList.html -->
<!-- Input several names and display them in a sorted list. -->
<html>
<head>
<meta charset="utf-8" />
<title>Sorted List</title>
</head>
<body>
<h1>People</h1>
<ol id="ol"></ol>
<script>
var name; // name entry
var people = []; // array of people
// get names
while (true) {
name = prompt("Name: ", "Done");
if (name === "Done") {
break; // stop getting names
}
people.push(name); // add name to end of array
}
// sort the array
people.sort();
// output the list
document.getElementById("ol").innerHTML = "<li>" + people.join("</li><li>") + "</li>";
</script>
</body>
</html>