CS 370 Statements D R. M I C H A E L J. R E A L E F A L L

Size: px
Start display at page:

Download "CS 370 Statements D R. M I C H A E L J. R E A L E F A L L"

Transcription

1 CS 370 Statements D R. M I C H A E L J. R E A L E F A L L

2 Overview In these slides, we ll talk about good practices related to programming statements: Organizing straight-line code Using conditionals Controlling loops Unusual control structures Table-driven methods

3 Organizing Straight-Line Code

4 Order Dependencies Often a series of statements must be executed in a certain order statements have dependencies Usually data being passed from one statement to the next When statements have dependencies make it clear as possible!

5 Making Dependencies Obvious Make routines so dependencies are obvious E.g., computesum() modifies sum (may be class variable) Use routine parameters (and returned data) to make dependencies obvious Examples: initstatistics(statistics); insertsamples(samples, statistics); computesum(statistics); computemean(statistics); computestandarddev(statistics); statistics = initstatistics(statistics); statistics = insertsamples(samples); statistics = computesum(statistics); statistics = computemean(statistics); statistics = computestandarddev(statistics);

6 Making Dependencies Obvious If a dependency is unclear, add a comment NOT ideal, but may not be able to help it if you can t modify the code for some reason (e.g., maintaining other code) Example: // Must compute mean before computing standard deviation computemean(statistics); computestandarddev(statistics); Check for dependencies inside routines themselves Example: computemean() sets a variable meancomputed Any function that needs the mean will check if meancomputed is true before proceeding (e.g., computestandarddev()) Problems: Creates new code/variables that could introduce new errors Potentially inefficient

7 When Order Doesn t Matter When order does not matter: Group related statements together so code reads from top to bottom Do this: SalesData salesdata; salesdata.computeannual(); salesdata.print(); TravelData traveldata; traveldata.computeannual(); traveldata.print(); NOT this: SalesData salesdata; TravelData traveldata; salesdata.computeannual(); traveldata.computeannual(); salesdata.print(); traveldata.print();

8 When Order Doesn t Matter Quick check: draw imaginary boxes around related statements If they overlap, you have a problem Do this: SalesData salesdata; salesdata.computeannual(); salesdata.print(); TravelData traveldata; traveldata.computeannual(); traveldata.print(); NOT this: SalesData salesdata; TravelData traveldata; salesdata.computeannual(); traveldata.computeannual(); salesdata.print(); traveldata.print();

9 Using Conditionals

10 If Statements Write nominal path through code first then write unusual cases Should be a straight run for the expected case Check whether you want to use: < vs. <= > vs. >=

11 If Statements Put normal case after if instead of after the else Makes it easier to find expected path through code Particularly bad if you mix them Mixing error and nominal cases: Error case Nominal case Nominal case Error case openfile(inputfile, status); if(status == ERROR) { displayerror( Cannot open file! ); else { readfile(inputfile, filedata, status); if(status == SUCCESS) { printfiledata(filedata); else { displayerror( Cannot read file! );

12 If Statements Nominal case Nominal case Error case Error case Better layout: openfile(inputfile, status); if(status == SUCCESS) { readfile(inputfile, filedata, status); if(status == SUCCESS) { printfiledata(filedata); else { displayerror( Cannot read file! ); else { displayerror( Cannot open file! );

13 If Statements Follow the if clause with a meaningful clause DON T do this: if( condition ) { // Do nothing else { // Do something Do this: if(!condition ) { // Do something

14 Else Clause Consider the else clause Think about whether you need one GM study: 50%-80% of if statements should have an else clause Arguably, even if you don t need one, coding an empty else clause (with a comment explaining what it means) at least means you considered it Test the else clause Easy to forget to test in favor of the original if Make sure you haven t swapped the if and else clauses Common mistake

15 Chains of If-Else If you don t have case statements (or if you can t use them with the situation you have) have to resort to chain of if-else clauses E.g., testing for a control character, letter, or number When using these: Simplify complicated boolean tests routines Put most common cases first Means reader can find common cases quickly Make sure all cases are covered Put final else statement with error message so you can catch missing cases

16 Deep Nesting Deep nesting Excessive levels of indentation Estimated that one shouldn t nest deeper than 3 levels Hard to avoid, but can employ different strategies to reduce it Possible strategies to reduce deep nesting: Retest part of a condition Use a break block Convert a nested if to set a of if-then-elses Convert a nested if to a case statement Factor deeply nested code into its own routine Use objects and polymorphic dispatch Redesign entirely

17 Deep Nesting: Retesting Retest part of a condition Not always the best idea Tradeoff: nesting levels for more complicated tests Nested version: if(image.data!= null) { // Piles of code if(featuretracker!= null) { // Buckets of code if(featuretracker.allocatedest()) { // Acres of code if(featuretracker.processimage(image)) { // Oodles of code

18 Deep Nesting: Retesting Retest part of a condition Less nested version: if(image.data!= null) { // Piles of code if(featuretracker!= null) { // Buckets of code if( (image.data!= null) && (featuretracker!= null) && featuretracker.allocatedest()) { // Acres of code if(featuretracker.processimage(image)) { // Oodles of code

19 Deep Nesting: Retesting Less nested version with better knowledge of code: if(image.data!= null) { // Piles of code bool featuretrackerallocatedsuccess = false; if(featuretracker!= null) { // Buckets of code featuretrackerallocatedsuccess = featuretracker.allocatedest(); if(featuretrackerallocatedsuccess) { // Acres of code if( (image.data!= null) && featuretrackerallocatedsuccess) { if(featuretracker.processimage(image)) { // Oodles of code

20 Deep Nesting: Break Block Use a break block Method: Have a bunch of code that must be executed in sequence Put it inside a do-while loop (with while(false)) If a condition that prevents execution occurs, break Kind of uncommon; should only be used if your team is familiar with the idea do { if(image.data == null) { break; // Piles of code if(featuretracker == null) { break; // Buckets of code if(!featuretracker.allocatedest()) { // Cleanup code? break; // Acres of code if(!featuretracker.processimage(image)) { break; // Oodles of code while(false);

21 Deep Nesting: If to If-Else Chain Convert a nested if to set a of if-then-elses Overgrown Decision Tree: if( pixel > 10) { if(pixel > 100) { if(pixel > 200) { thresholdedpixel = CLASS_D; else { thresholdpixel = CLASS_C; else { thresholdpixel = CLASS_B; else { thresholdpixel = CLASS_A;

22 Deep Nesting: If to If-Else Chain Convert a nested if to set a of if-then-elses Note: example below works particularly well because numbers increasing neatly Converted to if-elses: if(pixel > 200) { thresholdedpixel = CLASS_D; else if(pixel > 100) { thresholdpixel = CLASS_C; else if(pixel > 10) { thresholdpixel = CLASS_B; else { thresholdpixel = CLASS_A;

23 Deep Nesting: If to If-Else Chain Convert a nested if to set a of if-then-elses Alternative: allows more complicated number ranges (and allows different order of else-if statements Alternative converted to if-elses: if(pixel > 200) { thresholdedpixel = CLASS_D; else if((pixel > 100) && (pixel <= 200)) { thresholdpixel = CLASS_C; else if((pixel > 10) && (pixel <= 100)) { thresholdpixel = CLASS_B; else if (pixel <= 10) { thresholdpixel = CLASS_A;

24 Deep Nesting: OOP Approach Use objects and polymorphic dispatch Analogous to breaking code off into routines Have multiple subclasses same function implemented differently FeatureExtractor *extractor = null; switch(featuretype) { case LBP: extractor = LBPFeatureExtractor(); break; case GABOR: extractor = GaborFeatureExtractor(); break; default: DisplayError( UNKNOWN FEATURE ); return; if(extractor!= null) { extractor->extractfeatures(images);

25 Case Statements: Ordering Ordering of case statements: If equal importance alphabetical or numerical Put normal case first (and then the weird ones after that) Order cases by frequency Can find most common cases easily

26 Case Statements: Tips Keep case actions simple If you need to do something complicated, move it to a routine Don t try to force-fit using a case statement Example: C++ only supports ordinal types for case statements Checking a command string Use the first letter of the command TERRIBLY IDEA If you can t use a case statement, then use an if-else chain

27 Case Statements: Tips Don t use the default case for regular values only use it for detecting invalid values Otherwise, more difficult to understand and modify Be VERY careful with falling through in case statements I.e., not putting a break statement at the end of a case Good idea to avoid it If you must, comment the end of the case clearly where the fall-through occurs

28 Controlling Loops

29 Loop-with-Exit Loop Loop-with-Exit loop Loop that has an exit condition in the middle of the loop rather than (just) at the beginning or end Visual Basic explicit C++/Java while loop with break Can be used if you find yourself repeating part of the loop structure before the loop executes Not in common use Regular while with repeated code: getnextcameraimage(image); while(image.data!= null) { blurimage(image); displayimage(image); getnextcameraimage(image); Loop-with-exit loop alternative: while(true) { getnextcameraimage(image); if(image.data == null) { break; blurimage(image); displayimage(image);

30 For Loops for loops simple activities that don t require external loop controls Consequently, avoid changing loop index value inside loop if you have to do this, consider a while loop instead

31 Loops in General Think of body of loop as black box Should be able to understand loop conditions without having to look inside Use while(true) for infinite loops Don t fake it with a for loop that goes up to Don t abuse flexible for loop structures If you need a while loop, just use it

32 Loop Processing Use { for loops all the time Good defensive strategy Improves readability Avoid empty loops Usually caused by doing actual processing in the loop condition Move the processing to the loop body while( ( inputchar = datafile.getchar() )!= CHAR_EOF) { ; do { inputchar = datafile.getchar(); while ( inputchar!= CHAR_EOF);

33 Loop Processing Keep loop-housekeeping statements at either beginning or end of loop Example: Put things like j++ at end of loop Make each loop perform only one function Similar to routines

34 Loop Termination Make sure loop actually ends Make loop termination conditions obvious PLEASE don t set loop index to a value inside the loop to force an exit! Avoid code that depends on loop index s final value

35 Unusual Control Structures

36 Multiple Returns There s a little debate on whether you should: Use only ONE return statement in your routine Allow for multiple return statements Cases where multiple returns can be useful: Use an early return IFF: Know answer already before rest of code in routine executes No cleanup code needed Prevents MORE code from being written Guard clauses Check for conditions that prevent further processing can just return However, multiple returns Makes code potentially more confusing May forget return is possible

37 Recursion Recursion Can be useful for certain classes of problems Otherwise: Can make code more difficult to understand Can be less efficient When using recursion: Make sure it STOPS Use safety counters to prevent infinite recursion E.g., pass counter in as parameter and increment it on each call Limit recursion to ONE routine Don t have A call B call C call A Consider whether you really have to You can do anything with stacks and iteration that you can do with recursion

38 Table-Driven Methods

39 Table-Driven Methods Table-drive methods Using look-up table for logic Alternative to things like if and case statements Can make logic statements easier and more direct Example: checking type of character have table chartypetable that stores character type for each ASCII char chartype = chartypetable[ inputchar ];

40 Issues Two issues one must consider when dealing with tabledriven methods: How will you look up entries in the table? Examples: Days in month easy index is 1-12 Social security number harder (can t just use number directly) Possible access methods: Direct access Index access Stair-step access What will you store in the table? Data? Single value? Object? An action?

41 Table Access: Direct Access Direct Access Table Put in index(es) and jump straight to value you want Easy example: days in month More complex example: Insurance rate table Need age, marital status, and smoking status 3 dimensions lots of possible values Age has specified ranges: 0-17, 18-65, 66+ (we ll talk about this in a second ) Can read table off file or database can change values without changing code!

42 Fudging Table-Lookup Keys In the previous example, age actually had three ranges we cared about How can we handle this with our table? Duplicate information to make key work directly In other words, data for ages 0-17 are repeats Advantages: straightforward Disadvantages: Redundant and space-consuming Prone to errors if you forget/miss a column when changing data Transform the key to make it work directly Change any age between 0-17 to one key (maybe 17) If you do this: Isolate the key transformation in its own routine Can also use built-in transformation functions (e.g., Java s HashMap)

43 Table Access: Indexed Access Indexed Access Tables Use primary data to look up key in index table use key to access value from lookup table Example: Part numbers 0 through 9999 Only 100 items actually in stock

44 Table Access: Indexed Access Advantages: If each entry in main lookup table is large less space to create index array Can create multiple index mappings One by name, one by age, etc.

45 Table Access: Stair-Step Access Stair-Step Access Tables Entries are for valid ranges of data rather than distinct data points Example: grade ranges char grade = { F, D, C, B, A float limits = { 60.0, 70.0, 80.0, 90.0, Loop through limits can compare with value If value < limit[i] grade[i] Advantages: Works with floating-point indices Allows for irregularly spaced data Wastes less space than other approaches Disadvantages: Can be slower for a large number of ranges cost of search

46 Table Access: Stair-Step Access Things to look out for when using stair-step access: Watch the endpoints Check whether you want < or <= Consider a binary rather than sequential search Put stair-step table lookup in its own routine

Racket Style Guide Fall 2017

Racket Style Guide Fall 2017 CS17 Integrated Introduction to Computer Science Hughes Racket Style Guide Fall 2017 Contents 1 Introduction 1 2 Naming 1 3 Formatting 1 4 Equality 3 5 Conditionals 4 5.1 Prefer Cond to If......................................

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

CS 3 Introduction to Software Engineering. 3: Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction

More information

Repetition Structures

Repetition Structures Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

More information

CS 370 The Pseudocode Programming Process D R. M I C H A E L J. R E A L E F A L L

CS 370 The Pseudocode Programming Process D R. M I C H A E L J. R E A L E F A L L CS 370 The Pseudocode Programming Process D R. M I C H A E L J. R E A L E F A L L 2 0 1 5 Introduction At this point, you are ready to beginning programming at a lower level How do you actually write your

More information

1 ICS 161: Design and Analysis of Algorithms Lecture notes for January 23, Bucket Sorting

1 ICS 161: Design and Analysis of Algorithms Lecture notes for January 23, Bucket Sorting 1 ICS 161: Design and Analysis of Algorithms Lecture notes for January 23, 1996 2 Bucket Sorting We ve seen various algorithms for sorting in O(n log n) time and a lower bound showing that O(n log n) is

More information

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution. Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #16: Java conditionals/loops, cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Midterms returned now Weird distribution Mean: 35.4 ± 8.4 What

More information

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently. The Science of Computing I Lesson 4: Introduction to Data Structures Living with Cyber Pillar: Data Structures The need for data structures The algorithms we design to solve problems rarely do so without

More information

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017 Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls

More information

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

CPSC 3740 Programming Languages University of Lethbridge. Control Structures Control Structures A control structure is a control statement and the collection of statements whose execution it controls. Common controls: selection iteration branching Control Structures 1 15 Howard

More information

Classes, interfaces, & documentation. Review of basic building blocks

Classes, interfaces, & documentation. Review of basic building blocks Classes, interfaces, & documentation Review of basic building blocks Objects Data structures literally, storage containers for data constitute object knowledge or state Operations an object can perform

More information

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode STUDENT OUTLINE Lesson 8: Structured Programming, Control Structures, if- Statements, Pseudocode INTRODUCTION: This lesson is the first of four covering the standard control structures of a high-level

More information

CS 142 Style Guide Grading and Details

CS 142 Style Guide Grading and Details CS 142 Style Guide Grading and Details In the English language, there are many different ways to convey a message or idea: some ways are acceptable, whereas others are not. Similarly, there are acceptable

More information

These are notes for the third lecture; if statements and loops.

These are notes for the third lecture; if statements and loops. These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Spring 2017 Exceptions and Assertions 1 Outline General concepts about dealing with errors and failures Assertions: what, why, how For things you believe

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

Loops. CSE 114, Computer Science 1 Stony Brook University Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

More information

Making Decisions In Python

Making Decisions In Python Making Decisions In Python In this section of notes you will learn how to have your programs choose between alternative courses of action. Decision Making Is All About Choices My next vacation? Images:

More information

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting Your factors.c and multtable.c files are due by Wednesday, 11:59 pm, to be submitted on the SoC handin page at http://handin.cs.clemson.edu.

More information

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1 topics: introduction to java, part 1 cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 cis20.1-fall2007-sklar-leci.2 1 Java. Java is an object-oriented language: it is

More information

Hash Tables. CS 311 Data Structures and Algorithms Lecture Slides. Wednesday, April 22, Glenn G. Chappell

Hash Tables. CS 311 Data Structures and Algorithms Lecture Slides. Wednesday, April 22, Glenn G. Chappell Hash Tables CS 311 Data Structures and Algorithms Lecture Slides Wednesday, April 22, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org 2005

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lección 03 Control Structures Agenda 1. Block Statements 2. Decision Statements 3. Loops 2 What are Control

More information

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

QUIZ. What are 3 differences between C and C++ const variables?

QUIZ. What are 3 differences between C and C++ const variables? QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,

More information

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful

More information

If Statements, For Loops, Functions

If Statements, For Loops, Functions Fundamentals of Programming If Statements, For Loops, Functions Table of Contents Hello World Types of Variables Integers and Floats String Boolean Relational Operators Lists Conditionals If and Else Statements

More information

Lecture 7 Tao Wang 1

Lecture 7 Tao Wang 1 Lecture 7 Tao Wang 1 Objectives In this chapter, you will learn about: Interactive loop break and continue do-while for loop Common programming errors Scientists, Third Edition 2 while Loops while statement

More information

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

1.7 Limit of a Function

1.7 Limit of a Function 1.7 Limit of a Function We will discuss the following in this section: 1. Limit Notation 2. Finding a it numerically 3. Right and Left Hand Limits 4. Infinite Limits Consider the following graph Notation:

More information

The compiler is spewing error messages.

The compiler is spewing error messages. Appendix B Debugging There are a few different kinds of errors that can occur in a program, and it is useful to distinguish between them in order to track them down more quickly. Compile-time errors are

More information

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet. Mr G s Java Jive #2: Yo! Our First Program With this handout you ll write your first program, which we ll call Yo. Programs, Classes, and Objects, Oh My! People regularly refer to Java as a language that

More information

Program Syntax; Operational Semantics

Program Syntax; Operational Semantics 9/5 Solved Program Syntax; Operational Semantics CS 536: Science of Programming, Fall 2018 A. Why Our simple programming language is a model for the kind of constructs seen in actual languages. Step-by-step

More information

CMSC 201 Fall 2018 Python Coding Standards

CMSC 201 Fall 2018 Python Coding Standards CMSC 201 Fall 2018 Python Coding Standards The purpose of these coding standards is to make programs readable and maintainable. In the real world you may need to update your own code more than 6 months

More information

Variables and Data Representation

Variables and Data Representation You will recall that a computer program is a set of instructions that tell a computer how to transform a given set of input into a specific output. Any program, procedural, event driven or object oriented

More information

Chapter 4: Making Decisions

Chapter 4: Making Decisions Chapter 4: Making Decisions 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than or equal to

More information

Testing. Prof. Clarkson Fall Today s music: Wrecking Ball by Miley Cyrus

Testing. Prof. Clarkson Fall Today s music: Wrecking Ball by Miley Cyrus Testing Prof. Clarkson Fall 2017 Today s music: Wrecking Ball by Miley Cyrus Review Previously in 3110: Modules Specification (functions, modules) Today: Validation Testing Black box Glass box Randomized

More information

Code Reuse: Inheritance

Code Reuse: Inheritance Object-Oriented Design Lecture 14 CSU 370 Fall 2008 (Pucella) Tuesday, Nov 4, 2008 Code Reuse: Inheritance Recall the Point ADT we talked about in Lecture 8: The Point ADT: public static Point make (int,

More information

PAIRS AND LISTS 6. GEORGE WANG Department of Electrical Engineering and Computer Sciences University of California, Berkeley

PAIRS AND LISTS 6. GEORGE WANG Department of Electrical Engineering and Computer Sciences University of California, Berkeley PAIRS AND LISTS 6 GEORGE WANG gswang.cs61a@gmail.com Department of Electrical Engineering and Computer Sciences University of California, Berkeley June 29, 2010 1 Pairs 1.1 Overview To represent data types

More information

Repetition Through Recursion

Repetition Through Recursion Fundamentals of Computer Science I (CS151.02 2007S) Repetition Through Recursion Summary: In many algorithms, you want to do things again and again and again. For example, you might want to do something

More information

6.001 Notes: Section 15.1

6.001 Notes: Section 15.1 6.001 Notes: Section 15.1 Slide 15.1.1 Our goal over the next few lectures is to build an interpreter, which in a very basic sense is the ultimate in programming, since doing so will allow us to define

More information

Chapter 4: Making Decisions

Chapter 4: Making Decisions Chapter 4: Making Decisions CSE 142 - Computer Programming I 1 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >=

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

Propositional Logic. Part I

Propositional Logic. Part I Part I Propositional Logic 1 Classical Logic and the Material Conditional 1.1 Introduction 1.1.1 The first purpose of this chapter is to review classical propositional logic, including semantic tableaux.

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable CISC-124 20180122 Today we looked at casting, conditionals and loops. Casting Casting is a simple method for converting one type of number to another, when the original type cannot be simply assigned to

More information

Programming Style. Quick Look. Features of an Effective Style. Naming Conventions

Programming Style. Quick Look. Features of an Effective Style. Naming Conventions Programming Style Quick Look An effective programming style helps you write code that is easier to understand, debug, maintain, and port from system to system. This article discusses the general features

More information

Programming Logic and Design Ninth Edition

Programming Logic and Design Ninth Edition Programming Logic and Design Ninth Edition Chapter 3 Understanding Structure The Disadvantages of Unstructured Spaghetti Code Spaghetti code Logically snarled program statements Often a complicated mess

More information

LECTURE 04 MAKING DECISIONS

LECTURE 04 MAKING DECISIONS PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 04 MAKING DECISIONS

More information

Control Structures in Java if-else and switch

Control Structures in Java if-else and switch Control Structures in Java if-else and switch Lecture 4 CGS 3416 Spring 2017 January 23, 2017 Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 1 / 26 Control Flow Control flow refers to the specification

More information

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Writing a Simple Java Program Intro to Variables Readings Your textbook is Big Java (3rd Ed). This Week s Reading: Ch 2.1-2.5, Ch

More information

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/ CS61C Machine Structures Lecture 4 C Pointers and Arrays 1/25/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Pointers (1) Common C Error There is a difference

More information

5 The Control Structure Diagram (CSD)

5 The Control Structure Diagram (CSD) 5 The Control Structure Diagram (CSD) The Control Structure Diagram (CSD) is an algorithmic level diagram intended to improve the comprehensibility of source code by clearly depicting control constructs,

More information

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style CS125 : Introduction to Computer Science Lecture Notes #4 Type Checking, Input/Output, and Programming Style c 2005, 2004, 2002, 2001, 2000 Jason Zych 1 Lecture 4 : Type Checking, Input/Output, and Programming

More information

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop Topics C H A P T E R 4 Repetition Structures Introduction to Repetition Structures The for Loop: a Count- Sentinels Nested Loops Introduction to Repetition Structures Often have to write code that performs

More information

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture 15 Branching : IF ELSE Statement We are looking

More information

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false. CS101, Mock Boolean Conditions, If-Then Boolean Expressions and Conditions The physical order of a program is the order in which the statements are listed. The logical order of a program is the order in

More information

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi.

Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi. Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture 18 Tries Today we are going to be talking about another data

More information

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14 Statements Control Flow Statements Based on slides from K. N. King Bryn Mawr College CS246 Programming Paradigm So far, we ve used return statements and expression statements. Most of C s remaining statements

More information

Python for Informatics

Python for Informatics Python for Informatics Exploring Information Version 0.0.6 Charles Severance Chapter 3 Conditional execution 3.1 Boolean expressions A boolean expression is an expression that is either true or false.

More information

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes Overview For this lab, you will use: one or more of the conditional statements explained below

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 7 Part 2 The Department of Computer Science Quick review one-way or simple decision if : two-way decision

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #17. Loops: Break Statement

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #17. Loops: Break Statement Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #17 Loops: Break Statement (Refer Slide Time: 00:07) In this session we will see one more feature that is present

More information

If you don t, it will return the same thing as == But this may not be what you want... Several different kinds of equality to consider:

If you don t, it will return the same thing as == But this may not be what you want... Several different kinds of equality to consider: CS61B Summer 2006 Instructor: Erin Korber Lecture 5, 3 July Reading for tomorrow: Chs. 7 and 8 1 Comparing Objects Every class has an equals method, whether you write one or not. If you don t, it will

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

More information

Functional abstraction

Functional abstraction Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

More information

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( ) Review CSE 143 Java Hashing Want to implement Sets of objects Want fast contains( ), add( ) One strategy: a sorted list OK contains( ): use binary search Slow add( ): have to maintain list in sorted order

More information

CSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem:

CSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem: Expression evaluation CSE 504 Order of evaluation For the abstract syntax tree + + 5 Expression Evaluation, Runtime Environments + + x 3 2 4 the equivalent expression is (x + 3) + (2 + 4) + 5 1 2 (. Contd

More information

Optimizations. Optimization Safety. Optimization Safety CS412/CS413. Introduction to Compilers Tim Teitelbaum

Optimizations. Optimization Safety. Optimization Safety CS412/CS413. Introduction to Compilers Tim Teitelbaum Optimizations CS412/CS413 Introduction to Compilers im eitelbaum Lecture 24: s 24 Mar 08 Code transformations to improve program Mainly: improve execution time Also: reduce program size Can be done at

More information

An Introduction to Python

An Introduction to Python An Introduction to Python Day 2 Renaud Dessalles dessalles@ucla.edu Python s Data Structures - Lists * Lists can store lots of information. * The data doesn t have to all be the same type! (unlike many

More information

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Introduction to Object-Oriented Programming Conditional Execution Christopher Simpkins chris.simpkins@gatech.edu CS 1331 (Georgia Tech) Conditional Execution 1 / 14 Structured Programming In reasoning

More information

CHAPTER 3: FUNDAMENTAL OF SOFTWARE ENGINEERING FOR GAMES.

CHAPTER 3: FUNDAMENTAL OF SOFTWARE ENGINEERING FOR GAMES. CHAPTER 3: FUNDAMENTAL OF SOFTWARE ENGINEERING FOR GAMES www.asyrani.com TOPICS COVERED C++ Review and Best Practices Data, Code, and Memory in C++ Catching and Handling Errors C++ REVIEW AND BEST PRACTICES

More information

Chapter01.fm Page 1 Monday, August 23, :52 PM. Part I of Change. The Mechanics. of Change

Chapter01.fm Page 1 Monday, August 23, :52 PM. Part I of Change. The Mechanics. of Change Chapter01.fm Page 1 Monday, August 23, 2004 1:52 PM Part I The Mechanics of Change The Mechanics of Change Chapter01.fm Page 2 Monday, August 23, 2004 1:52 PM Chapter01.fm Page 3 Monday, August 23, 2004

More information

Programming with Python

Programming with Python Programming with Python Dr Ben Dudson Department of Physics, University of York 21st January 2011 http://www-users.york.ac.uk/ bd512/teaching.shtml Dr Ben Dudson Introduction to Programming - Lecture 2

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

Decisions. Arizona State University 1

Decisions. Arizona State University 1 Decisions CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 4 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17)

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17) BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17) 1 Learning Outcomes At the end of this lecture, you should be able to: 1. Explain the concept of selection control structure

More information

Typed Racket: Racket with Static Types

Typed Racket: Racket with Static Types Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type

More information

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved. Chapter 4: Expressions Chapter 4 Expressions 1 Chapter 4: Expressions Operators Expressions are built from variables, constants, and operators. C has a rich collection of operators, including arithmetic

More information

Unit #2: Recursion, Induction, and Loop Invariants

Unit #2: Recursion, Induction, and Loop Invariants Unit #2: Recursion, Induction, and Loop Invariants CPSC 221: Algorithms and Data Structures Will Evans 2012W1 Unit Outline Thinking Recursively Recursion Examples Analyzing Recursion: Induction and Recurrences

More information

First-Order Translation Checklist

First-Order Translation Checklist CS103 Winter 2019 First-Order Translation Checklist Cynthia Lee Keith Schwarz In this handout, we ve distilled five specific points that you should check in your first-order logic statements before submitting

More information

Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time)

Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time) CSE 11 Winter 2017 Program Assignment #2 (100 points) START EARLY! Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time) PROGRAM #2: DoubleArray11 READ THE ENTIRE ASSIGNMENT BEFORE STARTING In lecture,

More information

MANAGING YOUR MAILBOX: TRIMMING AN OUT OF CONTROL MAILBOX

MANAGING YOUR MAILBOX: TRIMMING AN OUT OF CONTROL MAILBOX MANAGING YOUR : DEALING WITH AN OVERSIZE - WHY BOTHER? It s amazing how many e-mails you can get in a day, and it can quickly become overwhelming. Before you know it, you have hundreds, even thousands

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Object Oriented Programming with Java

Object Oriented Programming with Java Object Oriented Programming with Java What is Object Oriented Programming? Object Oriented Programming consists of creating outline structures that are easily reused over and over again. There are four

More information

5. Selection: If and Switch Controls

5. Selection: If and Switch Controls Computer Science I CS 135 5. Selection: If and Switch Controls René Doursat Department of Computer Science & Engineering University of Nevada, Reno Fall 2005 Computer Science I CS 135 0. Course Presentation

More information

C++ Programming Style Guide

C++ Programming Style Guide C++ Programming Style Guide Computer Science Program Cedarville University Goal: Our goal is to produce well-written code that can be easily understood and will facilitate life-cycle maintenance. These

More information

Civil Engineering Computation

Civil Engineering Computation Civil Engineering Computation First Steps in VBA Homework Evaluation 2 1 Homework Evaluation 3 Based on this rubric, you may resubmit Homework 1 and Homework 2 (along with today s homework) by next Monday

More information

Program Structures. Slides adapted from Craig Zilles

Program Structures. Slides adapted from Craig Zilles Program Structures Slides adapted from Craig Zilles 1 Unix and Command Line ls list files cat concatenate files mostly used to output file cd change directory change to home directory if no directory given

More information

while (condition) { body_statements; for (initialization; condition; update) { body_statements;

while (condition) { body_statements; for (initialization; condition; update) { body_statements; ITEC 136 Business Programming Concepts Week 01, Part 01 Overview 1 Week 7 Overview Week 6 review Four parts to every loop Initialization Condition Body Update Pre-test loops: condition is evaluated before

More information

Some Extra Information on Graph Search

Some Extra Information on Graph Search Some Extra Information on Graph Search David Kempe December 5, 203 We have given basic definitions of graphs earlier in class, and talked about how to implement them. We had also already mentioned paths,

More information

Homework 7: Subsets Due: 11:59 PM, Oct 23, 2018

Homework 7: Subsets Due: 11:59 PM, Oct 23, 2018 CS17 Integrated Introduction to Computer Science Klein Contents Homework 7: Subsets Due: 11:59 PM, Oct 23, 2018 1 Bookends (Practice) 2 2 Subsets 3 3 Subset Sum 4 4 k-subsets 5 5 k-subset Sum 5 Objectives

More information

Control Structures. Outline. In Text: Chapter 8. Control structures Selection. Iteration. Gotos Guarded statements. One-way Two-way Multi-way

Control Structures. Outline. In Text: Chapter 8. Control structures Selection. Iteration. Gotos Guarded statements. One-way Two-way Multi-way Control Structures In Text: Chapter 8 1 Control structures Selection One-way Two-way Multi-way Iteration Counter-controlled Logically-controlled Gotos Guarded statements Outline Chapter 8: Control Structures

More information

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute Module 02 Lecture - 45 Memoization Let us continue our discussion of inductive definitions. (Refer Slide Time: 00:05)

More information

CSE 374 Programming Concepts & Tools

CSE 374 Programming Concepts & Tools CSE 374 Programming Concepts & Tools Hal Perkins Fall 2017 Lecture 8 C: Miscellanea Control, Declarations, Preprocessor, printf/scanf 1 The story so far The low-level execution model of a process (one

More information