Session 5

download Session 5

If you can't read please download the document

description

Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5. Session 5. JavaScript/JScript: Control Structures II. Learning Outcomes. Pada akhir pertemuan ini, diharapkan mahasiswa akan mampu : - PowerPoint PPT Presentation

Transcript of Session 5

  • Session 5JavaScript/JScript: Control Structures IIMatakuliah: M0114/Web Based ProgrammingTahun: 2005Versi: 5

  • Learning OutcomesPada akhir pertemuan ini, diharapkan mahasiswaakan mampu :menghasilkan pemrograman web dengan menggunakan struktur seleksi dan pengulangan pada JavaScript (C3)

  • Outline Materi5.1 Introduction5.2 Essentials of Counter-Controlled Repetition5.3 The for Repetition Structure5.4 Examples using the for Structure5.5 The switch Multiple Selection Structure5.6 The do/while Repetition Structure5.7 The break and continue Statements5.8 The Labeled break and continue statements5.9 Logical Operators5.10 Structured Programming Summary

  • 5.1 IntroductionBefore programming a script have aThorough understanding of problemCarefully planned approach to solve it

    When writing a script, important toUnderstand types of building blocks and tools availableEmploy proven program construction principles

  • 5.2 Essentials of Counter-Controlled RepetitionCounter-controlled repetition requires:1. Name of control variable (or loop counter)2. Initial Value of control variable3. Increment (or decrement) of control variable per loop4. Condition that tests for final value of control variable

    Program readability:Indent statements in body of each control structureBlank line before and after each major control structureAvoid more than three levels of nestingSample Program

  • 5.3 The for Repetition Structurefor repetition structure:Handles all details of counter-controlled repetition

    JavaScript statement: for ( var num = 1 ; i

  • 5.3 The for Repetition StructureEquivalent Structuresfor structure:for ( initialization; loopContinuationTest ; increment )statement;

    while structure:initialization;while ( loopContinuationTest ) {statement;increment;}continue..

  • 5.3 The for Repetition StructureFlowchart:continue..

  • 5.3 The for Repetition StructureThree expressions in for structure are optionalIf loopContinuationTest omitted JavaScript assumes condition is true Leads to infinite loopCan omit initialization expression if variable initialized elsewhere in programCan omit increment statement if incrementation occurs inside structureIf loop-continuation condition initially false, body of for structure not executedDelay loopfor structure empty except for semi-colonLoop still runs specified number of timesUseful for slowing down programs, but more efficient techniques exist (Chapter 15)Sample Program

  • 5.4 Examples using the for StructureDifferent methods for varying control variable in for structureExamples:Control variable: 1 to 100, increments of 1:for ( var i = 1; i = 1; --i );Control variable 7 to 77: , steps of 7:for ( var i = 7; i = 0; k -= 11 );continue..Sample Program

  • 5.4 Examples using the for StructureMath ObjectMath.pow( x, y );Calculates x raised to the yth powerMath.round();Rounds the inputted value to the nearest integerTo output a number with to the second decimal place, use formula:Math.round( amount * 100 ) / 100Example:Math.round( 3.1415 * 100 ) / 100 = 314/100 = 3.14JavaScript represents all numbers as floating-point numbersWhen floating-point numbers rounded, result may not be totally correct (especially when used in equations with other rounded values)Sample Program

  • 5.5 The switch Multiple Selection Structureswitch control structureContains multiple substructuresActions executed depend on variable valueWorks well classifying user inputsbreak statement Skips to end of switch structureShould be at the end of every case sub-structureIf left out, JavaScript will continue to test user input against casescontinue..

  • 5.5 The switch Multiple Selection Structuredefault caseIs executed if variable did not match any of the casesGood practices:Test if user entered valid valueIndent all lines of structure

    continue..

  • 5.5 The switch Multiple Selection StructureJavaScript statement:var choice;choice = window.prompt();switch ( choice ) {case a: actions case b: actions

    case z: actions default: actions}continue..

  • 5.5 The switch Multiple-Selection StructureFlowchart:case a action(s)case a action(s)case acase bcase ztruetruetruefalsefalsefalsecase a action(s)breakbreakbreakbreak action(s)Sample Program

  • 5.6 The do/while Repetition StructureSimilar to while control structureDifferencewhile: structure only executes if condition is initially trueJavaScript statement:while ( condition ) {statement} do/while: structure always executes at least onceJavaScript statement:do {statement} while ( condition );continue..

  • 5.6 The do/while Repetition StructureFlowchart:

    truefalseconditionaction(s)Sample Program

  • 5.7 The break and continue StatementsAlter flow of controlbreak;Exits structurecontinue;Skips remaining statements in structure; continues with next loop iterationWhen used properlyPerforms faster than the corresponding structured techniquesSample Program1Sample Program2

  • 5.8 The Labeled break and continue statementsbreak statement Breaks out of immediately enclosing repetition control structureTo break out of nested structuresUse labeled break statementsBegins with a label (identifier followed by colon)Enclose structures to be broken out of within braces ({})Called labeled compound statementWhen executing break statement, follow format:break label;continue..

  • 5.8 The Labeled break and continue statementsUse of labeled continue statement Follows same syntax and rulesAfter execution, continues with next iteration of enclosing labeled repetition structure

    Good practice to enter output statement to test if labeled statement executed properly

    Sample Program1Sample Program2

  • 5.9 Logical OperatorsLogical operators Used to form more complex conditions by combining simple conditions

    Logical operators are&& (logical AND)|| (logical OR) ! (logical NOT or logical negation) continue..

  • 5.9 Logical Operators&& (logical AND)All statements connected by && operators in a condition must be true for condition to be truecontinue..

    expression1

    expression2

    expression1 && expression2

    false

    false

    false

    false

    true

    false

    true

    false

    false

    true

    true

    true

  • 5.9 Logical Operators|| (logical OR)Any statement connected by || operators in a condition must be true for condition to be truecontinue..

    expression1

    expression2

    expression1 || expression2

    false

    false

    false

    false

    true

    true

    true

    false

    true

    true

    true

    true

  • 5.9 Logical Operators! (logical NOT or logical negation) ! operator in front of a condition reverses the meaning of the condition.A true value becomes falseA false value becomes trueSample Program

  • 5.10 Structured Programming SummaryRules for Forming Structured ProgramsBegin with the simplest flowchartAny rectangle (action) can be replaced by two rectangles (actions) in sequenceAny rectangle (action) can be replaced by any control structure (sequence, if, if/else, switch, do/while or for)Rules 2 and 3 may be applied as often as you like and in any ordercontinue..

  • 5.10 Structured Programming SummaryRepeatedly Applying Rule 2 to the Simplest Flowchartcontinue..

  • 5.10 Structured Programming SummaryApplying Rule 3 to the Simplest Flowchartcontinue..

  • 5.10 Structured Programming SummaryStructured approach: 7 single-entry/single-exit piecesSelection control structuresif structure (single selection)if/else structure (double selection)switch structure (multiple selection)Repetition control structureswhile structuredo/while structurefor structurefor/in structure (Chap 12)continue..

  • 5.10 Structured Programming SummaryAny form of control in JavaScript can be expressed through if structure (selection)while structure (repetition)Control structures combined in two waysStackingNesting

  • End of Session 5