COMP 1231 Web Programming Ben Blanc Week 5
COMP 1231 Web Programming Ben Blanc
Week 5 Iteration Structures
Add Lab Instructor • Please add me as in instructor by doing the following: -Navigate my. gblearn. com -login using w 6##### ID -Go to the Profile tab near the top of the page –Scroll down to Instructors section -select my name from the drop down and click "Add Instructor"
Types of Iteration • the while statement and its variants • the do/while statement • the for statement
While Loop Statement • The while loop statement is the most basic iterative control structures. It repeatedly runs a block of code until condition is no longer true. If the condition is not true to begin with then the code never runs. Syntax: while (condition) { code block to be executed }
While Loop Statement Example var x=1 while(x<15) { document. write(‘the value of x is ’+x+’ ’); x++; } ***Don’t forget to update variable value so you don’t create an infinite loop
The Do/While Loop • The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. Syntax: do { code block to be executed } while (condition)
While Loop Statement Example var x=1 do { document. write(‘the value of x is ’+x+’ ’); x++; } while(x<15)
The For Loop • The for loop is often the tool you will use when you want to create a loop. Syntax: for (statement 1; statement 2; statement 3) { the code block to be executed }
For loop explanation • Statement 1 is executed before the loop (the code block) starts. *Normally you will use statement 1 to initiate the variable used in the loop (var i=0). • This is not always the case, Java. Script doesn't care, and statement 1 is optional.
For loop explanation • Statement 2 defines the condition for running the loop (the code block). • Often statement 2 is used to evaluate the condition of the initial variable. • This is not always the case, Java. Script doesn't care, and statement 2 is optional. • If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
For loop explanation • Statement 3 is executed each time after the loop (the code block) has been executed. • Often statement 3 increases the initial variable. • This is not always the case, Java. Script doesn't care, and statement 3 is optional.
Break and Continue Statements • The break statement "jumps out" of a loop. • The continue statement "jumps over“ (skips) one iteration in the loop.
For loop examples var x; For (x=1; x<10; x++) { document. write(x+’<br/>’)} __________________ var x=1; for( ; x<10; x++) { document. write(x+’<br/>’)}
For loop examples var x; For ( ; ; x++) { If(x<10){break; } document. write(x+’<br/>’) }
For loop examples var x; For ( ; ; ) { If(x<10){break; } document. write(x+’<br/>’); x++ }
- Slides: 16