Conditional Repetition - Thinking Like Computers - Lecture Slides, Slides of Artificial Intelligence

During the course work of Thinking Like Computers, we study the key concept of artificial intelligence. The main points in these lecture slides are given as:Conditional Repetition, While Loops, While Loop Page, Priming Loop, Loop Tests, Counter-Driven Loops, Infinite Loops, Variables and Repetition, Countdown Page, Hailstone Sequences, Strings Objects

Typology: Slides

2012/2013

Uploaded on 04/24/2013

banani
banani 🇮🇳

4.3

(3)

91 documents

1 / 7

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
CSCI 100
Think Like Computers
Lecture 20
Fall 2008
Last Time …
Coding style
Conditional execution
logical operators and logical connectives
if statement
if branch
else branch
nested if statement
cascading if statement
Conditional Repetition
an if statement is known as a control
statement
it is used to control the execution of other
JavaScript statements
provides for conditional execution
is useful for solving problems that involve
choices
either do this or don't, based on some condition (if)
either do this or do that, based on some condition
(if-else)
Conditional Repetition
closely related to the concept of conditional
execution is conditional repetition
many problems involve repeating some task
over and over until a specific condition is met
e.g., rolling dice until a 7 is obtained
e.g., repeatedly prompting the user for a valid
input
in JavaScript, while loops provide for
conditional repetition
While Loops
a while loop resembles an if statement in
that its behavior is dependent on a
boolean condition.
however, the statements inside a while loop’s
curly braces (a.k.a. the loop body) are
executed repeatedly as long as the condition
remains true
general form:
While Loops
when the browser encounters a while loop,
it first evaluates the boolean test
if the test succeeds, then the statements inside
the loop are executed in order, just like an if
statement
once all the statements have been executed,
program control returns to the beginning of the
loop
the loop test is evaluated again, and if it
succeeds, the loop body statements are
executed again
this process repeats until the boolean test fails
Docsity.com
pf3
pf4
pf5

Partial preview of the text

Download Conditional Repetition - Thinking Like Computers - Lecture Slides and more Slides Artificial Intelligence in PDF only on Docsity!

CSCI 100

Think Like Computers

Lecture 20

Fall 2008

Last Time …

• Coding style

• Conditional execution

• logical operators and logical connectives

• if statement

Š if branch

Š else branch

• nested if statement

• cascading if statement

Conditional Repetition

• an if statement is known as a control

statement

Š it is used to control the execution of other

JavaScript statements

Š provides for conditional execution

Š is useful for solving problems that involve

choices

ƒ either do this or don't, based on some condition (if)

ƒ either do this or do that, based on some condition

(if-else)

Conditional Repetition

• closely related to the concept of conditional

execution is conditional repetition

Š many problems involve repeating some task

over and over until a specific condition is met

Š e.g., rolling dice until a 7 is obtained

Š e.g., repeatedly prompting the user for a valid

input

Š in JavaScript, while loops provide for

conditional repetition

While Loops

• a while loop resembles an if statement in

that its behavior is dependent on a

boolean condition.

Š however, the statements inside a while loop’s

curly braces (a.k.a. the loop body ) are

executed repeatedly as long as the condition

remains true

Š general form:

While Loops

• when the browser encounters a while loop,

it first evaluates the boolean test

Š if the test succeeds, then the statements inside

the loop are executed in order, just like an if

statement

Š once all the statements have been executed,

program control returns to the beginning of the

loop

Š the loop test is evaluated again, and if it

succeeds, the loop body statements are

executed again

Š this process repeats until the boolean test fails

While Loop Example

• example: roll two dice repeatedly until

doubles are obtained

  • sample output: - note: even though while loops and if statements look similar, they are very different control statements Š an if statement may execute its code 1 time or not at all Š a while loop may execute its code an arbitrary number of times (including not at all)

While Loop Page

Priming the Loop

  • sometimes, you can avoid redundancy by "priming the loop" Š assign initial values to the variables so that the loop test succeeds and the loop can proceed
  • note the redundancy in the code Š must perform the initial dice roll before the loop begins Š then, have to repeatedly re-roll inside the loop

Loop Tests

  • note: the loop test defines the condition under which the

loop continues

Š this is often backwards from the way we think about loops Š e.g., read input until you get a positive number (i.e., until input > 0) while (input <= 0) {... } Š e.g., keep rolling dice until you get doubles (i.e., until roll1 == roll2) while (roll1 != roll2) {... } Š e.g., keep rolling dice until you get double fours (i.e., until roll1 == 4 && roll2 = 4) while (roll1 != 4 || roll2 != 4) {... }

DeMorgan's Law: !(X && Y) == (!X || !Y) !(X || Y) == (!X && !Y)

Counter-Driven Loops

• since a while loop is controlled by a condition, it

is usually impossible to predict the number of

repetitions that will occur

Š e.g., how many dice rolls will it take to get doubles?

• a while loop can also be used to repeat a task

some fixed number of times

Š implemented by using a while loop whose test is

based on a counter

Š general form of counter-driven while loop:

Counter-Driven Loops

examples :

Example: Hailstone Sequences

• it is conjectured that, no matter what

positive integer you start with, you will

always end up in the 4-2-1 loop

Š this has been verified for all starting number

up to 1,200,000,000,

Š but, it still has not been proven to hold for ALL

starting numbers

Š we can define a JavaScript function for

experimenting with this problem

ƒ the hailstone function will generate the

sequence given a starting number

Strings as Objects

• so far, your interactive Web pages have

manipulated strings in simple ways

Š use prompt or a text box/area to input a word or

phrase

Š store that text in a (string) variable

Š incorporate the text in a message, possibly using + to

concatenate

Strings as Objects

• strings are different from numbers and Booleans

in that they are objects

Š a software object is a unit of code that encapsulates

both data and operations that can be performed on

that data

Š a string is a software object that models words and

phrases

data: a sequence of characters, enclosed in quotes operations include: make upper case, make lower case,

determine the number of characters,

access a particular character,

search for a particular character, …

Object-Oriented Programming

  • objects are fundamental in the dominant approach to

developing software systems: object-oriented

programming (OOP)

Š OOP encourages programmers to design programs around software objects ƒ the programmer identifies the real-world objects involved in a system (e.g., for a banking program: bank account, customer, teller, …) ƒ then designs and builds software objects to model these real-world objects

Š OOP is effective for managing large systems, since individual objects can be assigned to different teams and developed independently Š OOP also supports code reuse, since the same or similar objects can be combined in different ways to solve different kinds of problems

Object-Oriented Programming

• example: a doorbell button

Š has physical components/properties: color, shape,

label, …

Š has functionality: when you press the button, the bell

rings

• an HTML button is a software object that models

a real-world button

Š has physical components/properties: color, shape,

label, …

Š has functionality: when you click on the button,

JavaScript code is executed

Properties and Methods

• using object-oriented terminology,

Š the characteristics of an object are called properties

ƒ e.g., a string object has a length property that identifies the number of characters in the string

Š the operations that can be performed on the string are

called methods

ƒ e.g., the toLowerCase method makes a copy of the string with all upper-case letters converted to lower-case

Properties and Methods

  • properties and methods are not new concepts

Š a property is a special kind of a variable (it stores a value) Š a method is a special kind of function (it performs some action)

  • what is special is that they are associated with (or

"belong to") an object

Š e.g., each string object will have its own variable to stores it length

  • to access an object property, specify: object name, a

period, property name

str1 = "foo"; str2 = "Hi there"; len1 = str1.length; len2 = str2.length;

Properties and Methods

  • similarly, to call a method: object name, period, method

call

Š e.g., str.toLowerCase() calls the toLowerCase method on str (which returns a lower-case copy of the string) Š e.g., str.toUpperCase() calls the toUpperCase method on str (which returns an upper-case copy of the string)

Properties and Methods

  • note: the toLowerCase and toUpperCase methods do

not change the string object they are called on (only an

assignment can do that!)

Š instead, they return modified copies of the string

String Manipulation Page

Common String Methods

  • useful methods exist that allow programmers to access

and manipulate individual components of a string

Š components are identifiable via indices , or numbers that correspond to the order in which individual characters occur in a string Š indices are assigned in ascending order from left to right, so that the first character in the string is at index 0

  • the charAt method provides access to a single

character within the string

Š it takes an index as an input and returns the character at that particular index word = "foo"; ch = word.charAt(0); // ASSIGNS ch = "f"

Common String Methods

• the substring method provides access to an

entire sequence of characters within the string

Š it takes two numbers as inputs, representing the

starting (inclusive) and ending (exclusive) indices of

the substring, and returns the substring

  • word = "foo"; sub = word.substring(1, 3); // ASSIGNS sub = "oo"

General Searches

• rather than having to search for vowels

individually, an entire class of characters can be

specified using /[... ]/

Strings and Repetition

• some tasks involve repeatedly performing the

same operations

Š to accomplish such tasks, we can combine while

loops with string methods such as charAt and

search

• example: a while loop used to access and

process each character in a string

Š the characters that comprise the string are

concatenated one-by-one onto another string,

resulting in an exact copy

Strings and Repetition