Control Structures Functions Decision making Loops

Slides:



Advertisements
Similar presentations
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Advertisements

CS0004: Introduction to Programming Repetition – Do Loops.
Creating PHP Pages Chapter 7 PHP Decisions Making.
Objectives Using functions to organize PHP code
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
Chapter 4 Functions and Control Structures PHP Programming with MySQL.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Arrays and Control Structures CST 200 – JavaScript 2 –
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Client-Side Scripting JavaScript.  produced by Netscape for use within HTML Web pages.  built into all the major modern browsers. properties  lightweight,
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
ALBERT WAVERING BOBBY SENG. Week 4: JavaScript  Quiz  Announcements/questions.
Logic and Control. 4-2 Decision (selection) structure: if (condition) { statement etc. } Example: if (age == 15) { document.write(“ you are a fifteen”);
L OO P S While writing a program, there may be a situation when you need to perform some action over and over again. In such situation you would need.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
JavaScript, Fourth Edition
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
CIS 133 Mashup Javascript, jQuery and XML Chapter 3 Building Arrays and Controlling Flow.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
JavaScript, Sixth Edition
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Learning Javascript From Mr Saem
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
>> Introduction to JavaScript
CHAPTER 10 JAVA SCRIPT.
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Tutorial 12 Working with Arrays, Loops, and Conditional Statements
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
JavaScript Syntax and Semantics
Programming Fundamentals
Chapter 6: Conditional Statements and Loops
JavaScript: Control Statements.
Week#2 Day#1 Java Script Course
CHAPTER 4 CLIENT SIDE SCRIPTING PART 2 OF 3
JavaScript: Control Statements I
ITM 352 Flow-Control: Loops
The structure of computer programs
Control Structures - Repetition
Arrays, For loop While loop Do while loop
Chapter 8 JavaScript: Control Statements, Part 2
Structured Program
During the last lecture we had a discussion on Data Types, Variables & Operators
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
3 Control Statements:.
Objectives In this chapter, you will:
CPS120: Introduction to Computer Science
CIS 136 Building Mobile Apps
Web Programming and Design
Chapter 8 JavaScript: Control Statements, Part 2
Structural Program Development: If, If-Else
Presentation transcript:

Control Structures Functions Decision making Loops

Functions Controlling when code executes

Functions vs. Methods A JavaScript function is a block of code designed to perform a particular task – an action of some sort A JavaScript function is executed when "something" invokes it (calls it). You can create your own functions, as we will learn later, or use JS built-in functions, also called intrinsic functions. Intrinsic Functions are built into Javascript objects, so they get a special name, they are called methods. Functions are NOT associated with an object, whereas Methods are! Functions must be contained within a <script> element

Defining Functions function nameOfFunction(parameters) { statements; } Syntax function nameOfFunction(parameters) { statements; } Parameter Variable used within a function Placed within parentheses following a function name Multiple parameters allowed calc_square_root(number1, number2)

Lets Practice Define a function named “displayMyBank” Inside the function, use a document.write statement, to write out the name of your bank The function does not need parameters Syntax function nameOfFunction(parameters) { statements; }

Calling Functions Function statements do the actual work and are contained within curly braces Functions can be written anywhere in the web page, but are usually within the document head, or an external .js file Calls to the function are within the body section and consist of the function name followed by parentheses function printStudentNames() { document.write(“<p>” + Joe + “</p>”); document.write(“<p>” + Sam + “</p>”); document.write(“<p>” + Bob + “</p>”); } </script> </head> <body> <script> printStudentNames(); </script>

Calling Functions using parameters If a function needs additional information, providing it is called Passing arguments The function must be designed to receive that data, and that data is called a parameter Arguments vs. Parameters – refer to the same memory location, therefore the same data function averageNumbers(a, b, c) { var sum_of_numbers = a + b + c; var result = sum_of_numbers / 3; return result; } averageNumbers(1,2,3);

Lets Practice Write the function named “displayMyName” which receives a memory location. The function will refer to the memory location using the parameter name someonesName Next, Write a statement to call the function named “displayMyName” providing it your own name as an argument Refer to the example below: function averageNumbers(a, b, c) { var sum_of_numbers = a + b + c; var result = sum_of_numbers / 3; return result; } averageNumbers(1,2,3);

Functions which return data A function can return information to the statement that called it A Return statement Returns a value to the statement calling the function Uses the return keyword with the variable or value to send to the calling statement

Calling Functions (cont’d.) Example of a function receiving parameters and returning result: function averageNumbers(a, b, c) { var sum_of_numbers = a + b + c; var result = sum_of_numbers / 3; return result; } var ans; ans=averageNumbers(1,2,3);

Understanding Variable Scope Where in a program a declared variable can be used Global variable Declared outside a function Available to all parts of a program Local variable Declared inside a function Only available within the function in which it is declared Cease to exist when the function ends Keyword var required

Understanding Variable Scope (cont’d.) If variable declared within a function and does not include the var keyword Variable automatically becomes a global variable Program may contain global and local variables with the same name Local variable takes precedence Value assigned to local variable of the same name Not assigned to global variable of the same name

Understanding Variable Scope (cont’d.) var pitcher = "Josh Beckett"; function duplicateVariableNames() { var pitcher = "Tim Lincecum"; document.write("<p>" + pitcher + "</p>"); // value printed is Tim Lincecum } duplicateVariableNames(); // value printed is Josh Beckett

Lets Practice Inside your function, “displayMyBank” Declare a variable called myBank and set it’s value to the name of your bank Modify the document.write statement, to write out the name of your bank, using the variable

Functions vs. Methods At this point, just think of a function as something you create, and a method is a function that someone already created, and is available thru an object. The syntax for using a method is: ObjectName.methodname(); For example, the document object has a method called write, so when we want to use it, we type document.write(); Some methods need information and some do not. If information is needed, it goes INSIDE the parenthesis, as in document.write(“My name is Monica”);

Document Object - getElementByID A powerful Method is getElementByID. This method allows JavaScript to interact with an HTML element. To do so, you pass getElementByID the name of the HTML element you are interested in, as in document.getElementByID(“tax”) So, somewhere in the HTML of the page, there has to be a field named “tax”, as in <input type=“text” id=“tax” value=“” /> Now that the html element, in this case a textbox, can be referenced, you can decide what part of it you want to work with. In this case, its value, as in document.getElementByID(“tax”).value

More methods Being able to reference what the user types into a form field, such as a textbox, is what gives Javascript its gusto! It does pose problems, because we do not know for sure what the user may have typed. If we expect the user to type a number in our textbox, there is no guarantee they will do that. So, we need to check what is entered, to make sure the right stuff is entered. We do this by using 1 or more of these additional methods: isNaN parseInt parseFloat

isNaN() The isNaN() method determines whether a value is an illegal number (Not-a-Number) This function returns true if the value is NaN, and false if it is Syntax isNaN(value) document.write(isNaN("Ima String"))  isNan returns true document.write(isNaN(0/0))  isNan returns true document.write(isNaN("348"))  isNan returns false document.write(isNaN(348))  isNan returns false

parseInt() The parseInt() method parses a string and returns an integer. If the first character cannot be converted to a number, parseInt() returns NaN (not a number) document.write(parseInt("10") + "<br />");  parseInt returns 10 document.write(parseInt("10.33") + "<br />");  parseInt returns 10 document.write(parseInt("34 45 66") + "<br />");  parseInt returns 34 document.write(parseInt(" 60 ") + "<br />");  parseInt returns 60 document.write(parseInt("He was 40") + "<br />");  parseInt returns NaN

parseFloat() The parseFloat() method n parses a string and returns a floating point number document.write(parseFloat("10") + "<br />");  parseFloat returns 10 document.write(parseFloat("10.33") + "<br />");  parseFloat returns 10.33 document.write(parseFloat("34 45 66") + "<br />");  parseFloat returns 34 document.write(parseFloat(" 60 ") + "<br />");  parseFloat returns 60 document.write(parseFloat("He was 40") + "<br />");  parseFloat returns NaN

Putting it all together Suppose we have a web page that has a textbox on it, and we want the user to only enter a number in the textbox. We can ensure this, using a combination of functions: getElementById to get the value of what they typed isNaN – to see if they typed a number alert – to tell them if they made an error, and if no errors, parseInt or parseFloat to convert the number in the textbox to a true integer or decimal

FLOW CONTROL FlowCHARTS

Flow Control Flowcharts Process of determining the order in which statements execute in a program Special types of JavaScript statements used in flow control Flowcharts A diagram that uses special symbols to display the flow of execution in a program Handy to ensure program reaches a logical conclusion Comprised of various symbols

Designing Program Flow Start and End symbols Indicate the beginning and end of the program Arrows Show flow of control Input/Output Accept data or represent the results of computations Decision Contain a yes/no question or a true/false test Connector Entry point/hookup point Process Show a statement; piece of logic Start

Designing Program Flow for sweaters.html Start Declare variables for prices Assign values to variables Display line 1 Display line 2 Display line 3 Display line 4 End

Decisions Flow control using: if and switch commands

Making Decisions Decision making Process of determining which statements execute in a program Decision-making statements, decision-making structures, or conditional statements Used when you need to adopt one path out of the given two paths Conditional statements allow your program to make correct decisions and perform right actions Runs a command or command block only when certain circumstances are met JavaScript supports 2 kinds of conditional statements which are used to perform different actions based on different conditions if .. else switch

if Statements – single action Used to execute specific programming code If conditional expression evaluation returns a truthy value Syntax if (condition) { javascript statements ) } Command block begins/ends with curly braces

If/else Statements – dual action Tests a condition and has 2 possible actions if (condition) { JS commands if condition is true } else JS commands ifconditions Is not true yes no

if/else Statements (cont’d.) Example: var today = "Tuesday" if (today === "Monday") { document.write("<p>Today is Monday</p>"); } else { document.write("<p>Today is not Monday</p>");

if and if/else Statements – multiple actions Nested decision-making structures One decision-making statement contains another decision-making statement

if and if/else Statements – multiple actions Nested if statement An if statement contained within an if statement or within an if/else statement var salesTotal = 75; if (salesTotal > 50) { if (salesTotal < 100) { document.write("<p>The sales total is between 50 and 100.</p>"); }

Nested if/elseif statements An if/else statement contained within an if statement or within an if/else statement if (gameLocation[i] === "away") { paragraphs[1].innerHTML = "@ "; } else { if (gameLocation[i] === "home") { paragraphs[1].innerHTML = "vs "; nested if/else version if (gameLocation[i] === "away") { paragraphs[1].innerHTML = "@ "; } else if (gameLocation[i] === "home") { paragraphs[1].innerHTML = "vs "; else if version

switch Statements Controls program flow by executing a specific set of statements based on an expression until a match is found Examines the expression and then evaluates a series of possible values see if a value meets the criteria (sort of like a multiple choice question) The switch statement is given an expression to evaluate The case statements contain the possible values and the code to execute for each possible value The interpreter checks each case against the value of the expression until a match is found If nothing matches, a default condition will be used. Break statement stops the matching

switch Statements (cont’d.) function city_location(americanCity) { switch (americanCity) { case "Boston": return "Massachusetts"; break; case "Chicago": return "Illinois"; case "Los Angeles": return "California"; case "Miami": return "Florida"; case "New York": return "New York"; default: return "United States"; } document.write("<p>" + city_location("Boston") + "</p>");

REPETITION Flow of control using: while, do while, AND for-in commands

Working with Program Loops A program loop is a set of commands that is executed repeatedly until a stopping condition has been met Four kinds of loops While Do While For For loop Requires a counter variable tracks the number of times a set of commands is run The collection of commands that is run each time through a loop is collectively known as a command block

while Statements while (expression) { statements } while statement Repeats a statement or series of statements As long as a given conditional expression evaluates to a truthy value Syntax while (expression) { statements } NEW TERM!! Iteration Each repetition of a looping statement

while Statements (cont’d.) A WHILE statement runs as long as a specific condition is met Counter Variable incremented or decremented with each loop statement iteration Examples: while statement using an increment operator while statement using a decrement operator while statement using the *= assignment operator

while Statements (cont’d.) var count = 1; while (count <= 5) { document.write(count + "<br />"); count++; } document.write("<p>You have printed 5 numbers.</p>"); Result in browser:

while Statements (cont’d.) var count = 1; while (count <= 100) { document.write(count + "<br />"); count *= 2; } Result in browser:

while Statements (cont’d.) var count = 10; while (count > 0) { document.write(count + "<br />"); count--; } document.write("<p>We have liftoff.</p>"); Result in browser is ??:

while Statements (cont’d.) Infinite loop Loop statement that never ends Example: var count = 1; while (count <= 10) { window.alert("The number is " + count + "."); } WHATS CAUSING THIS TO NEVER STOP?

do/while Statements do/while statement Syntax Similar to the while loop except that the condition check happens at the end of the loop. Executes a statement or statements at least once Then repeats the execution as long as a given conditional expression evaluates to a truthy value Syntax do { statements; } while (expression); Note the semicolon used at the end of the do...while loop

do/while Statements (cont’d.) Examples: var count = 2; do { document.write("<p>The count is equal to " + count + ".</p>"); count++; } while (count < 2); var count = 2; while (count < 2) { document.write("<p>The count is equal to " + count + ".</p>"); count++; }

for Statements Repeats a statement or series of statements Syntax Most compact form of looping Includes the following three important parts: The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins. The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out. The iteration statement where you can increase or decrease your counter Repeats a statement or series of statements As long as a given conditional expression evaluates to a truthy value Syntax for (counter_declaration; condition; counter_modifier) { statements }

for Statements (cont’d.) For loops are often used to cycle through the different values contained within an array To loop through the contents of an array, use length property: var brightestStars = ["Sirius", "Canopus", "Arcturus", "Rigel", "Vega"]; for (var count = 0; count < brightestStars.length; count++) { document.write(brightestStars[count] + "<br />"); } Result in browser:

for Statements (cont’d.) var count = 1; while (count < brightestStars.length) { document.write(count + "<br />"); count++; } for (var count = 1; count < brightestStars.length; count++) { document.write(count + "<br />"); }

“For In” Loop This loop is used to loop through an object's properties or associative arrays. SYNTAX for (myvariablename in object) { statement or block to execute; } In each iteration one property from object is assigned to variablename and this loop continues until all the properties of the object are exhausted. for (var x in Array) { txt=txt + Array[x]; } alert(txt);

Using continue Statements to Resume Execution for (var count = 1; count <= 5; count++) { if (count === 3) { continue; } document.write("<p>" + count + "</p>"); Result in browser:

Using BREAK Statements to Exit Execution for (var count = 1; count <= 5; ++count) { if (count == 3) break; document.write("<p>" + count + "</p>"); }