Chapter 2 - Algorithms and Design

Slides:



Advertisements
Similar presentations
Chapter 4 - Control Statements
Advertisements

Introduction to Computing Science and Programming I
Flow Control if, while, do-while Juan Marquez (03_flow_control.ppt)
 Control structures  Algorithm & flowchart  If statements  While statements.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
ITEC113 Algorithms and Programming Techniques
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
A High-Level Model For Software Development
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
Review Algorithm Analysis Problem Solving Space Complexity
Chapter 1 Pseudocode & Flowcharts
ALGORITHMS AND FLOWCHARTS
Fundamentals of Python: From First Programs Through Data Structures
The University of Texas – Pan American
Fundamentals of Python: First Programs
PROGRAMMING, ALGORITHMS AND FLOWCHARTS
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 2 - Algorithms and Design
Input, Output, and Processing
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Flowcharts.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping with.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Visual Basic Programming
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
1 Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping.
ITEC113 Algorithms and Programming Techniques
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
Structured Program Development Angela Chih-Wei Tang ( 唐 之 瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2010.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Control Structures RepetitionorIterationorLooping Part I.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
A First Book of C++ Chapter 5 Repetition.
Chapter 7 Problem Solving with Loops
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Algorithms and Pseudocode
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Flow Charts And Pseudo Codes Grade 12. An algorithm is a complete step-by- step procedure for solving a problem or accomplishing a task.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
Topics Designing a Program Input, Processing, and Output
REPETITION CONTROL STRUCTURE
© 2016 Pearson Education, Ltd. All rights reserved.
Algorithms and Flowcharts
Chapter 5: Control Structure
( Iteration / Repetition / Looping )
Lecture 07 More Repetition Richard Gesick.
ALGORITHMS AND FLOWCHARTS
Control Structure Senior Lecturer
Structured Program
ALGORITHMS AND FLOWCHARTS
3 Control Statements:.
Faculty of Computer Science & Information System
2.6 The if/else Selection Structure
Flowcharts and Pseudo Code
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Chapter 2 - Algorithms and Design
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Chapter 2 - Algorithms and Design 1 Chapter 2 - Algorithms and Design Example Algorithm and Variables print Statement input Statement Assignment Statement if Statement Flowcharts Flow of Control Looping with Flowcharts Looping with Pseudocode Tracing Pseudocode Syntax Summary Loop Terminatation Counter loop User query loop Sentinel value loop Nested Loops

Example Algorithm and Variables 2 Example Algorithm and Variables Here's a pseudocode algorithm that calculates the area of a rectangle: print "Enter a length: " input length print "Enter a width: " input width area ← length * width print "The area is " + area Above, note that some of the words (length, width, and area) appear with monospace font. Monospace font is when each character’s width is uniform. We use monospace font to indicate that something is a variable. A variable is a box/container that can hold a value. length, width, and area are variables.

3 print Statement print "Enter a length: " input length print "Enter a width: " input width area ← length * width print "The area is " + area The print statement causes the specified item(s) to be displayed. For example, the first line in the above algorithm causes this to be displayed: Enter a length: You can print different types of items. Later we'll talk about printing numbers, but for now, let's focus on printing characters…. If you want to print a sequence of characters, surround the characters with quotes. A sequence of characters surrounded by quotes is called a string. For example, in the first line, "Enter a length: " is a string. If you want to use one print statement to print a string plus something else, insert a + sign between each of the things that you’re printing. The + sign performs string concatenation. print statement Use a + sign to concatenate a string to something else.

input Statement The input statement: 4 input Statement print "Enter a length: " input length print "Enter a width: " input width area ← length * width print "The area is " + area The input statement: Causes the algorithm to wait for the user to enter a value. After the user enters a value, the value is stored in the specified variable. The first two print statements are called prompts because they prompt the user to enter a value. input statement

5 Assignment Statement print "Enter a length: " input length print "Enter a width: " input width area ← length * width print "The area is " + area The assignment statement is represented by a backwards arrow (←). It puts the right-hand-side expression's value into the left-hand-side variable. Suppose that 2 and 4 were entered as input for the above algorithm. Here's a picture of what the assignment statement does: assignment statement

6 if Statement Use an if statement if you need to ask a question in order to determine what to do next. There are three forms for an if statement: “if” “if, else” “if, else if” Format for the “if” form of the if statement: if <condition> <statement(s)> Classroom notation: I use angled brackets "<>" to surround a description of what should be placed at a particular position. Thus, in your algorithms, don't write the word "condition," the word "statement(s)," or the <>'s. Instead, provide an actual condition and an actual statement(s). Don't forget to indent!

7 if Statement A condition is a question whose answer is either yes or no. The answer to the condition’s question determines which statement executes next. How the “if” form of the if statement works: If the condition is true, execute all subordinate statements; that is, execute all indented statements immediately below the “if.” If the condition is false, jump to the line after the last subordinate statement; that is, jump to the first un-indented statement below the “if.”

if Statement “if” example: 8 if Statement “if” example: lightningFactor ← 3 print “Seconds between lightning and thunder?” input seconds print “Are you flying in an airplane (y/n)?” input inAnAirplane if inAnAirplane equals “y” print “Beware – the lightning may be closer than you think!” lightningFactor ← 3.4 distance ← seconds / lightningFactor print “You are ” + distance + “ kilometers from the lightning.” Note the spelling of the lightningFactor and inAnAirplane variable names. If a variable name requires multiple words (e.g., “lightning factor”), omit the spaces between the words and use all lowercase except for the first letter of the 2nd, 3rd, etc. words. These two statements are subordinate to the encompassing if statement. condition

if Statement Format for the “if, else” form of the if statement: 9 if Statement Format for the “if, else” form of the if statement: if <condition> <statement(s)> else How the “if, else” form of the if statement works: If the condition is true, execute all statements subordinate to the “if,” and skip all statements subordinate to the “else.” If the condition is false, skip all statement(s) subordinate to the “if,” and execute all statements subordinate to the “else.” “if, else” example: if grade ≥ 60 print “Pass” print “Fail”

more else if's here (optional) 10 if Statement Format for the “if, else if” form of the if statement: if <condition> <statement(s)> else if <condition> . else How the “if, else if” form of the if statement works: For the first condition that's true, execute its statement(s) and skip the other statement(s). If none of the conditions are true, execute the else statement(s) (if there is an else). more else if's here (optional) optional

if Statement “if, else if” example: if grade ≥ 90 print "A" 11 if Statement “if, else if” example: if grade ≥ 90 print "A" else if grade ≥ 80 print "B" else if grade ≥ 70 print "C" else if grade ≥ 60 print "D" else print "F"

if Statement If statement summary: Practice problems: 12 if Statement If statement summary: Use the first format (if by itself) for problems where you want to do something or nothing. Use the second format (if, else) for problems where you want to do one thing or another thing. Use the third format (if, else if) for problems where you want to do one thing out of three or more choices. Practice problems: Write an algorithm that prints "warm" if the temperature (a variable) is above 50 degrees and prints "cold" otherwise. Write an algorithm that prints "No school!" if the temperature is below 10 degrees. Write an algorithm that prints "too cold" if the temperature is below 50 degrees, "OK" if the temperature is between 50 and 90 degrees, and "too hot" if the temperature is above 90 degrees.

15 if Statement Write an algorithm that prints "too cold" if the temperature is below 50 degrees, "OK" if the temperature is between 50 and 90 degrees, and "too hot" if the temperature is above 90 degrees.

16 Flowcharts Flowchart = a pictorial representation of a program's logic. Flowchart symbols: Surround print, input, and assignment statements with rectangles: Surround questions (for if conditions and loop conditions) with diamonds: Connect the rectangles and diamonds with arrows, which show the direction of the logic flow: Every flowchart is supposed to have one starting point and one ending point. Don’t forget to connect the bottom components of your flowcharts.

Flowcharts Equivalent flowchart: 17 Flowcharts Equivalent flowchart: Example algorithm that cuts a CEO’s large salary in half: print "Enter CEO salary: " input ceoSalary if ceoSalary ˃ 500000 ceoSalary ← ceoSalary * .5 print "Reduced salary is $" + ceoSalary

18 Flowcharts Draw a flowchart that prints "too cold" if temperature is below 50 degrees, "OK" if the temperature is between 50 and 90 degrees, and "too hot" if the temperature is above 90 degrees. Flowchart:

20 Flow of Control Flow of control – the order in which a program's statements are executed. Statements are grouped according to their flow of control. Sequential statements are executed in sequence, one after the other. Sequential statement examples – print, input, assignment. Branching statements contain one or more choices and only one of the choices is executed. Branching statement examples – the three forms of the if statement. Loop statements cause you to jump back to a previously executed statement. By continuing at that previous statement, a loop is formed.

Looping with Flowcharts 21 Looping with Flowcharts Flowchart: Let's first implement a loop using a flowchart (later we'll implement loops using pseudocode): Draw a flowchart that prints "Happy birthday!" 100 times. Note: We don't need any new flowchart symbols for loops. Flowchart looping is implemented by an arrow going to a previously executed statement.

Looping with Pseudocode 23 Looping with Pseudocode Use a loop statement if you need to do the same thing repeatedly. loop format: while <condition> { <statement(s)> } How the while loop works: While the condition is true, execute the statement(s) and jump back to the condition. When the condition finally becomes false, jump below the subordinate statement(s) and continue with the next statement. the loop's heading the loop's body

Looping with Pseudocode 24 Looping with Pseudocode Loop terminology: The number of times that the loop repeats is called the number of iterations. It's possible for a loop to repeat forever. That's called an infinite loop. (Note: It's also possible for a loop to repeat zero times.) Example: Write an algorithm that prints "Happy Birthday!" five times. count ← 1 while count ≤ 5 { print "Happy birthday!" count ← count + 1 }

Tracing What is tracing? How to trace: 25 Tracing What is tracing? It's when a human executes an algorithm (or a program) line by line and carefully records everything that happens. It's used to 1) verify that an algorithm is correct or 2) find errors/bugs in an algorithm. How to trace: Setup: If there is input, provide a column heading labeled "input." Provide a column heading for each variable. Provide a column labeled "output." Whenever there's an input statement, cross off the next input value under the input column heading. Update a variable's value by writing the new value underneath the variable's column heading and crossing off the old value. Whenever there's a print statement, write the printed value under the output column heading. For full credit on the homework, your variable and output values must be 100% accurate.

Pseudocode Summary print <variables, strings, math expressions> 26 Pseudocode Summary print <variables, strings, math expressions> Use quotes to surround strings. input <variable> Variables (no spaces, all lowercase except for first letter of 2nd, 3rd, etc. words) Assignment statement <variable> ← <value> math operators: +, -, /, * if <condition> else if <condition> else while <condition> { … }

Loop Termination There are three basic ways to terminate/exit loops: 27 Loop Termination There are three basic ways to terminate/exit loops: Counter loop Use a counter variable to keep track of the number of iterations. Example – "Happy birthday" algorithm. User query Ask the user if he/she wants to continue. Example – miles-to-kilometers conversion algorithm (coming up). Sentinel value Use a special value to indicate that there's no more input. Example – bowling scores algorithm (coming up).

28 User-Query Example Write an algorithm that converts a series of user-entered miles values to kilometer values. The program should continue as long as the user answers "y" to a "Continue?" prompt. continue ← "y" while continue equals "y" { print "Enter a distance in miles: " input miles km ← miles * 1.609 print "The equivalent distance in kilometers is " + km print "Continue? (y/n): " input continue }

Sentinel Value Example 29 Sentinel Value Example Write an algorithm that reads in bowling scores repeatedly until a sentinel value of -1 is entered. Print the average score. As always, your algorithm should be robust. (Robust means that the algorithm works even for the weird cases, not just the easy cases.)

Sentinel Value Example 32 Sentinel Value Example Remember: Your algorithms should be robust. Is the bowling score algorithm robust? Note: Division by zero in an actual computer program causes the program to "crash" (= terminate immediately) rather than continuing to the end of the program. Moral: Prevent division by zero by using an appropriate if statement.

Nested Loops A nested loop is a loop that's inside another loop. 33 Nested Loops A nested loop is a loop that's inside another loop. Example: Write an algorithm that finds the largest prime number from a list of user-entered numbers. The user indicates he/she is done by entering a negative number. For each entered number, how can you determine whether the number is prime? When the user finally enters a negative number, the algorithm prints the largest prime number entered or “No prime numbers were entered.”

Nested Loops 34 largestPrime ← 1 print “Enter a number (negative to quit): ” input num while num ≥ 0 { count ← 2 prime ← “yes” while count < num and prime equals “yes” if num / count has no remainder prime ← “no” else count ← count + 1 } if prime equals “yes” and num > largestPrime largestPrime ← num if largestPrime equals 1 print “No prime numbers were entered.” print “The largest prime number entered was ” + largestPrime + “.”