CpSc 217 - Structured and Dynamic Web Programming
The notes found on these pages all reference the textbook given above.
Unless otherwise stated, the citation of the information on these web pages
is that text.
This chapter is a partial
Review from 130
Basics
- var var_list
- var a, b, c
- a = 3
- b = a * b - c
- s = "hello" + ", how are you?"
Equality and Relational Operators
- = = != //be careful with = =
- < > <= >=
- Boolean expressions: not, and, or
! && ||
- Precedence revisited
Conditional Programming
- Not sequential
- When needed to choose between two (or more) alternatives
- IF syntax
for single statements
if ( condition )
statement;
- examples of Javascript code
if ( input_num < 0 )
document.write ( "Error message<br>");
- IF syntax for multiple statements
if ( condition )
{
statement1;
statement2;
}
- examples of Javascript code
if ( grade == 100 )
{
document.write(
"Excellent job<br>");
bonus = 1;
}
IF-ELSE syntax
- single statements
if ( condition )
statement;
else
statement;
- examples of Javascript code
if (x < 0 )
document.write( "negative number<br>");
else
document.write( "non-negative number<br>");
- Nested IFs
- More than two possible actions
- Second if can be nested inside of the 1st "if" part or the 1st "else" part
- Examples
if ( x <0 )
document.write( "negative number<br>");
else
if ( x == 0 )
document.write( "zero<br>");
else
document.write( "positive number<br>");
ELSE IFs
if (x < 0 )
document.write( "negative number<br>");
else if (x == 0)
document.write( "zero<br>");
else
document.write(" "positive number<br>");
Multi-way selection: The Switch statement
- Used in place of if-elseif-elseifÂ…
- Syntax
switch ( variable)
{
case1: statements;
break;
case2: statements;
break;
. . .
casen: statements;
break;
default: statements;
}
Loops
- while, for, do
- Increment/Decrement revisited
WHILE Loops
- Syntax
while (condition)
{
statements_in_the_loop;
}
-
initialize;
while (test) {
statement
increment
}
- Semantics
- Evaluate the condition
- If the condition is true
Execute the statements in the loop
Jump back to the top of the loop (step 1.)
- Otherwise
Execute statements after the loop
int sum = 0, i = 1;
while (i < 10)
{
sum = sum + i;
i++;
}
FOR loop & Counter Controlled loops
- Syntax for initial, final, and modifier
for (initialize_lcv; condition; modify_lcv)
{
statements_in_loop;
}
statements_after_loop
- Semantics
- Initialize lcv
- Evaluate the condition
- If the condition is true
Execute the statements in the loop
Jump back to the top of the loop (step 1.)
- Otherwise
Execute statements after the loop
- EXAMPLES
for (I=0; I<9; I++)
document.write( I);
- Also a for in loop
- Used with arrays and objects
for (variable in object)
statement
Break
- Used to exit loop
- Caution when using
- Not "structured"
- Sometimes appropriate
Continue
- Used to skip to next iteration of loop
- Caution when using
- Not "structured"
- Rarely appropriate