COMP 110 Prasun Dewan 1
|
|
|
- Caitlin McBride
- 9 years ago
- Views:
Transcription
1 COMP 110 Prasun Dewan Conditionals Real-life algorithms seldom do the same thing each time they are executed. For instance, our plan for studying this chapter may be to read it in the park, if it is a sunny day, and in the library, otherwise. Similarly, the execution of most non-trivial programs depends on the results of tests. We will study new statements, called conditionals, that allow us to write such programs. They allow us to break away from the straight-line execution of the programs we have seen so far (where statements are executed one after the other along a linear execution path); in particular, they allow branching in the execution path. Because of the real-life analogy, using conditionals is relatively straightforward. The main challenge is to use them elegantly; therefore, we will also learn several general rules on their usage. if- statement Suppose we need a procedure, printpassfailstatus, that takes a numeric score as an argument, and prints the string PASS or FAIL based on whether the score is above the pass cutoff. Thus, assuming the cutoff is 50, the call printpassfailstatus(95) should print: and: should print: PASS printpassfailstatus(30) FAIL In order to write this method, we need a mechanism that allows the execution of different statements based on some condition. The if- statement, illustrated below, is one mechanism for supporting such conditional execution: public static void printpassfailstatus(int score) { if (score < PASS_CUTOFF) System.out.println("FAIL"); System.out.println("PASS"); 1 Copyright Prasun Dewan, 2000.
2 Figure 1. if- statement In general, the statement has the syntax: if (<boolean expression>) <statement1>; <statement2>; (Note that parentheses are required around <boolean expression>). What this statement depends on <boolean expression>. If <boolean expression> evaluates to true, it executes <statement1>, otherwise it executes <statement2>. <statement 1> is called the then part or then branch; <statement 2> is called the part or branch ; and <boolean expression> is called the condition of the if-. Thus, in the method above, the if- tests the boolean expression: score < PASS_CUTOFF. In case this expression returns true, the statement branches to the then part: System.out.println("FAILED"); Otherwise the statement branches to the part: System.out.println("PASSED"); When the method is called with the argument, 30, the boolean expression evaluates to true, resulting in the then part being executed; and when it is called with the argument 30, it evaluates to false, resulting in the part being executed. Reading if- Novice programmers sometimes add a redundant test in the condition of an if-: if (score < PASS_CUTOFF == true) This expression perhaps reads better in English if we read: if (<boolean expression>)
3 as it is written. However, it should be really read as: if (<boolean expression>) is true because, as mentioned above, the if- evaluates the value of its condition and executes the then-part if the value is true. Thus, the above if- should be read as: if (score < PASS_CUTOFF == true) is true Now it does not read well. It is equivalent but more long-winded than saying: if (score < PASS_CUTOFF ) is true In general, avoid testing a boolean expression for equality or inequality with the true and false values. Boolean Expression vs. if- Let us consider a variation of the method above that, instead of printing a string, returns a boolean value to indicate the pass/fail status. We might be tempted to structure this function like the procedure: public static boolean hasfailed(int score) { if (score < PASS_CUTOFF) return true; return false; The if- we use here is similar to the one we used in the previous example except that its then and parts return the false and true values, rather than printing the strings FAILED and PASSED, respectively. There is a simpler way to write this function: public static boolean hasfailed(int score) { return (score < PASS_CUTOFF); The function returns true if the boolean expression score < PASS_CUTOFF is true and false otherwise, which is exactly what our previous version did. It is easy to detect that the if above is unnecessary if we read it as: if (score < PASS_CUTOFF) is true return true; return false; The statement is essentially returning the value of its condition. Since an if- can implement more general logic than a boolean expression, we are often tempted to use them for all logic. Therefore,
4 once you have written an if-, check if a simple boolean expression would have sufficed instead. If all the then and branches do is compute the true (false) and false (true) values, respectively, then get rid of the if- and use (the negation of the) condition as the computed value. Compound Statement What if we wanted to perform more than one statement in the then or branch? Java lets us create a compound statement by enclosing a series of statements within the delimiters { and, as shown below: public void fancyprintgrade(int score) { if (score < PASS_CUTOFF ) { System.out.println("FAILED"); { System.out.println("PASSED"); System.out.println("Congratulations!"); As far as the if- is concerned, there is only one statement in the then or the part. The statement happens to be a compound statement containing a list of statements. We have actually already seen examples of a compound statement the body of a method and the try and catch block. We will see later the use of the compound statement in other constructs. A compound statement is also called a statement list, statement block or simply block. Putting the delimiters ({ and ) of a compound statement on their own lines takes too much space; therefore the convention is to put them on the lines containing the if and keywords, as shown below: public void fancyprintgrade(int score) { if (score < PASS_CUTOFF) { System.out.println("FAILED"); { System.out.println("PASSED"); System.out.println("Congratulations!");
5 Code Duplication Again It is possible to write a better implementation of the procedure above: public void factoredfancyprintgrade(int score) { if (score < PASS_CUTOFF) { System.out.println("FAILED"); { System.out.println("PASSED"); System.out.println("Congratulations!"); While the previous implementation indicates the exact set of steps to be taken in each case, it repeats code in the two branches. It is preferable to share code that must be executed in both branches, for the reasons we saw earlier. Less Typing: We have to type less. With today s cut and paste features, this is not the major advantage, however, as we saw before. Clarity: We can clearly identify the code that is executed in both cases. Otherwise we would have to explicitly compare the two branches to see what code is executed in both cases. For instance, in the example above, we would have to count the number of * s to se if the same number of them are being printed in the two cases. Change: Suppose we wanted to change the number of * s that must be printed in both cases. In the non-sharing approach, we would have to duplicate the changes in both branches. It is easy to forget to change one of them or change them differently. So the sharing approach is more resilient to program changes. The general principle, which we saw earlier, is to avoid duplication of code in a program. In the context of an if-, it implies that we should share code in the then and branches. We will later see the application of this principle to other statements. if Statement Sometimes we wish to take no action in an branch. In this case, the if statement can be used instead of the if- statement. It has the syntax: Example: if (<boolean expression>) <statement>; if (score == MAX_SCORE) System.out.println ("Perfect Score! Congratulations!");
6 Figure 2. if statement Figure 3. Nesting in the parts We can always use an if- statement instead of an if statement by putting nothing (the "null" statement) in the part: if (score == MAX_SCORE) System.out.println ("Perfect Score! Congratulations!"); ; But the if statement is more elegant when the is a null statement. Beginning programmers, used mainly to the if- statement and unfamiliar with the null statement, tend to sometimes put a spurious assignment in the part: if (score == MAX_SCORE) System.out.println ("Perfect Score! Congratulations!"); score = score; Like the previous solution, this is correct but even less elegant! We shall refer to if- and if statements as conditionals, because their execution depends on some condition. An if- statement is used to choose between the execution of two statements based on
7 the condition; while an if statement is used to determine whether a statement should be executed based on the condition. Nested Conditionals Consider the following function, which takes returns a letter grade based on the argument score: public static char tolettergrade(int score) { return 'A'; if (score >= B_CUTOFF) return 'B'; if (score >= C_CUTOFF) return 'C'; if (score >= D_CUTOFF) return 'D'; return 'F'; The use of the if statement here might seem at odds with the syntax we gave: if (<boolean expression>) <statement1> <statement2> In fact, you might think of it as a special kind of statement in which the keywords if replace the keyword. But actually, it is simply a sequence of nested conditionals, that is, if- statements whose or then branches contains other conditionals (Figure 3). The following format clarifies this: return 'A'; if (score >= B_CUTOFF) return 'B'; if (score >= C_CUTOFF) return 'C'; if (score >= D_CUTOFF) return 'D'; return 'F'; Since this format takes more space, we prefer the previous one, in which we used the same indentation for the enclosing and enclosed conditionals. then vs. Branching We could have written this function in other several other ways. In the implementation above, all the branching (nesting) occurs in the parts of the if- statements (Figure 3). This is because we
8 started our comparisons with the highest cutoff, A_CUTOFF. If we started our comparisons with the lowest one, D_CUTOFF, all the branching would occur in the then parts. if (score >= D_CUTOFF) if (score >= C_CUTOFF) if (score >= B_CUTOFF) return 'A'; return 'B'; // score < B_CUTOFF return 'C'; // score < C_CUTOFF return 'D'; // score < D_CUTOFF return 'F'; However, this implementation is more awkward to read since the parts of the inner if- statements get separated from their conditions. In fact, we need comments to remind ourselves of the correspondence between these part and their conditions. Therefore, it is better to nest the branches rather than the then branches. Linear Vs Balanced Branching Both solutions, the branching is linear, that is, it occurs on one side (then or ) of the decision tree, with the other side not containing any conditional. If we started our comparisons, not with the extreme values, A_CUTOFF and D_CUTOFF, but instead with a value in between, we would get a more balanced branching: if (score >= B_CUTOFF) return 'A'; return 'B'; // score < B_CUTOFF if (score < C_CUTOFF) if (score < D_CUTOFF) return 'F'; return 'D'; // score >= C_CUTOFF return 'C'; Again, some parts get separated from their conditions in this solution. Moreover, the solution is confusing because sometimes we check if a value is greater than a cutoff and sometimes if it is less. In summary, choose linear branching over balanced branching; and branching on the side over branching on the then side.
9 Nested Vs Non-nested Solution We could have done the problem without nested conditionals, as shown below: result = 'A'; if ((score < A_CUTOFF) && (score >= B_CUTOFF)) result = 'B'; if ((score < B_CUTOFF) && (score >= C_CUTOFF)) result = 'C'; if ((score < C_CUTOFF) && (score >= D_CUTOFF)) result = 'D'; if (score < D_CUTOFF) result = F'; return result; The problem with this alternative is that there are two tests in the second, third, and fourth ifs, while there is only one test in the previous version for each if. Thus the previous version is more efficient - it will run faster. Moreover, you had to write less too! The second solution essentially violates the principle of avoiding redundant computation. Multiple & Early Returns As the various nested implementations of the function tolettergrade how, it is possible for a function to have more than one return statement. When there are multiple alternative paths through a function, it is usual to have a return at the end of each path. It is also possible to have an early return, that is, a return in the middle of a path. When Java encounters a return statement, it terminates execution of the method, ignoring any statements that follow it. An early return can be a useful feature, as illustrated by the following alternative solution to the letter grade problem. It uses independent if statements without doing redundant computation: return 'A'; if (score >= B_CUTOFF) return 'B'; if (score >= C_CUTOFF) return 'C'; if (score >= D_CUTOFF) return 'D'; return F'; This solution works because the then part of each of the if statements is a return statement, telling the method to ignore the following statements in the program. When we execute an if statement in this solution, we know that the condition of the previous if statement was false, which is equivalent to putting it in the part of the preceding if statement. Thus, this program is equivalent to our first solution:
10 return 'A'; if (score >= B_CUTOFF) return 'B'; if (score >= C_CUTOFF) return 'C'; if (score >= D_CUTOFF) return 'D'; return F'; It is somewhat preferable than the first solution since it requires a bit less typing. In summary, a nested if then statement with multiple returns can sometimes be elegantly replaced by a series of if statements with early returns. Explicit return in a Procedure Java allows us to do an early return from a procedure also: public void printlettergrade(int score) { if (score < 0) { System.out.println ("Illegal score"); return; System.out.println( Letter Grade: + tolettergrade(score )); In a procedure, the return keyword does not take an argument, because no value is to be returned. It is usual to have early returns in a procedure for various error conditions. In the absence of early returns, the normal (error-free) processing of the procedure would be in an part of an if-: public void printlettergrade(int score) { if (score < 0) { System.out.println ("Illegal score"); return; System.out.println( Letter Grade: + tolettergrade(score )); This solution requires an extra level of indentation, which is a significant disadvantage because the screen real-estate tends to be limited. Dangling Else Problem Consider the following nested if statement: if (score >= B_CUTOFF)
11 System.out.println ("excellent!"); System.out.println ("bad"); Which if statement does the statement match with? If you typed this text using the J editor, this is how it would be automatically formatted. This may lead you to believe that it matches the outer if statement. But you could manually format it as: if (score >= B_CUTOFF) System.out.println ("excellent!"); System.out.println ("bad"); Now it looks as if it matches the inner if statement. Our syntax rule of an if- statement allows for both interpretations. This ambiguity is called the dangling problem. It is resolved by making an match the closest if. So, in this example, the second interpretation is the correct one. The possibility for confusion here is another reason for not nesting in a then branch. Summary An if- conditional is used to choose between the execution of two statements based on the value of a boolean expression. An if conditional is used to determine whether a statement should be executed based on the value of a boolean expression. A conditional can nest other conditionals to create an arbitrary number of alternative execution paths within a method. In a nested conditional, branching in the part is preferred to branching in the then part or balanced branching. An part matches the closest then part. A nested if-then conditional with multiple returns can sometimes be elegantly replaced by a series of if statements with early returns. An if- statement can sometimes be elegantly and efficiently replaced by a boolean expression. Avoid testing a boolean expression for equality or inequality with the true and false values.
12 Exercises 1. Write a more concise version of the following function: public static boolean haspassed(int score) { if (score < PASS_CUTOFF) return false; return true; 2. The following code fragment has repeated code in the two branches of the if- statement. Write an equivalent function that does not have repeated code. public void fancyprintgrade(int score) { if (score < PASS_CUTOFF == true) { System.out.println("FAILED"); System.out.println("Need to take the course again."); { System.out.println("PASSED"); System.out.println("Congratulations!"); 3. Write a procedure, internetlogin to simulate process of manually logging in to an internet provider. The procedure takes as arguments the expected name and password of the user. It prompts the user for a name and password and checks the values input are consistent with the expected values. It then prompts the user for a command, and if the string ppp is entered, it outputs the string Connection Succeeded, and returns to its caller. In case the wrong user name, password, or command are entered, it gives an error message indicating the erroneous input, and returns to its caller. The following window illustrates two possible interactions during calls to internetlogin( John Smith, open sesame ). Write the procedure using: a) branching in the parts of nested if- statements. b) branching in the then parts of nested if- statements. c) a series of if statements with early returns. d) a single, non-nested, if- statement that calls an auxiliary boolean function, readandcheckinput that takes as arguments the kind of user input ( Name, Password, Command ) and the expected value for the entry, prompts the user for the input, reads the input, and returns true or false based on whether the actual user input is the same as the expected value.
13 Check for string equality by invoking the equals method on a string, rather than using the Java == operator. Thus, to check that a string s1 is the same as string s2, evaluate s1.equals(s2) rather than s1==s2. See chapter 17 for the difference between == and equals. 4. Extend the temperature driver class of Chapter 7, Question 4. to allow the user to enter the three temperatures in centigrade or Fahrenheit, depending on what the user chooses at the beginning of the interaction, as shown below:
16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution
16. Recursion COMP 110 Prasun Dewan 1 Loops are one mechanism for making a program execute a statement a variable number of times. Recursion offers an alternative mechanism, considered by many to be more
CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement
CompSci 125 Lecture 08 Chapter 5: Conditional Statements Chapter 4: return Statement Homework Update HW3 Due 9/20 HW4 Due 9/27 Exam-1 10/2 Programming Assignment Update p1: Traffic Applet due Sept 21 (Submit
Moving from CS 61A Scheme to CS 61B Java
Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you
Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go
Debugging ESE112 Java Programming: API, Psuedo-Code, Scope It is highly unlikely that you will write code that will work on the first go Bugs or errors Syntax Fixable if you learn to read compiler error
Conditions & Boolean Expressions
Conditions & Boolean Expressions 1 In C++, in order to ask a question, a program makes an assertion which is evaluated to either true (nonzero) or false (zero) by the computer at run time. Example: In
Conditional Statements. 15-110 Summer 2010 Margaret Reid-Miller
Conditional Statements 15-110 Summer 2010 Margaret Reid-Miller Conditional statements Within a method, we can alter the flow of control (the order in which statements are executed) using either conditionals
CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013
Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)
Building Java Programs
Building Java Programs Chapter 4: Conditional Execution These lecture notes are copyright (C) Marty Stepp and Stuart Reges, 2007. They may not be rehosted, sold, or modified without expressed permission
2 SYSTEM DESCRIPTION TECHNIQUES
2 SYSTEM DESCRIPTION TECHNIQUES 2.1 INTRODUCTION Graphical representation of any process is always better and more meaningful than its representation in words. Moreover, it is very difficult to arrange
Pseudo code Tutorial and Exercises Teacher s Version
Pseudo code Tutorial and Exercises Teacher s Version Pseudo-code is an informal way to express the design of a computer program or an algorithm in 1.45. The aim is to get the idea quickly and also easy
Writing Control Structures
Writing Control Structures Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 5-1 Objectives After completing this lesson, you should be able to do the following: Identify
Parsing Technology and its role in Legacy Modernization. A Metaware White Paper
Parsing Technology and its role in Legacy Modernization A Metaware White Paper 1 INTRODUCTION In the two last decades there has been an explosion of interest in software tools that can automate key tasks
Sudoku puzzles and how to solve them
Sudoku puzzles and how to solve them Andries E. Brouwer 2006-05-31 1 Sudoku Figure 1: Two puzzles the second one is difficult A Sudoku puzzle (of classical type ) consists of a 9-by-9 matrix partitioned
6. Control Structures
- 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,
Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators
Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero THEN the Average is Sum divided by Count Conditions
Introduction to Python
Caltech/LEAD Summer 2012 Computer Science Lecture 2: July 10, 2012 Introduction to Python The Python shell Outline Python as a calculator Arithmetic expressions Operator precedence Variables and assignment
Computer Programming C++ Classes and Objects 15 th Lecture
Computer Programming C++ Classes and Objects 15 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2013 Eom, Hyeonsang All Rights Reserved Outline
ECE 122. Engineering Problem Solving with Java
ECE 122 Engineering Problem Solving with Java Introduction to Electrical and Computer Engineering II Lecture 1 Course Overview Welcome! What is this class about? Java programming somewhat software somewhat
Selection Statements
Chapter 5 Selection Statements 1 Statements So far, we ve used return statements and expression ess statements. e ts. Most of C s remaining statements fall into three categories: Selection statements:
Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007
Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,
Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language
Translation Translating to Java Introduction to Computer Programming The job of a programmer is to translate a problem description into a computer language. You need to be able to convert a problem description
CASCADING IF-ELSE. Cascading if-else Semantics. What the computer executes: What is the truth value 1? 3. Execute path 1 What is the truth value 2?
CASCADING IF-ELSE A cascading if- is a composite of if- statements where the false path of the outer statement is a nested if- statement. The nesting can continue to several levels. Cascading if- Syntax
Sample CSE8A midterm Multiple Choice (circle one)
Sample midterm Multiple Choice (circle one) (2 pts) Evaluate the following Boolean expressions and indicate whether short-circuiting happened during evaluation: Assume variables with the following names
C H A P T E R Regular Expressions regular expression
7 CHAPTER Regular Expressions Most programmers and other power-users of computer systems have used tools that match text patterns. You may have used a Web search engine with a pattern like travel cancun
1.4 Compound Inequalities
Section 1.4 Compound Inequalities 53 1.4 Compound Inequalities This section discusses a technique that is used to solve compound inequalities, which is a phrase that usually refers to a pair of inequalities
AP Computer Science Java Subset
APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall
Chapter 5. Selection 5-1
Chapter 5 Selection 5-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow
CHAPTER 2. Logic. 1. Logic Definitions. Notation: Variables are used to represent propositions. The most common variables used are p, q, and r.
CHAPTER 2 Logic 1. Logic Definitions 1.1. Propositions. Definition 1.1.1. A proposition is a declarative sentence that is either true (denoted either T or 1) or false (denoted either F or 0). Notation:
The Rules 1. One level of indentation per method 2. Don t use the ELSE keyword 3. Wrap all primitives and Strings
Object Calisthenics 9 steps to better software design today, by Jeff Bay http://www.xpteam.com/jeff/writings/objectcalisthenics.rtf http://www.pragprog.com/titles/twa/thoughtworks-anthology We ve all seen
Lecture 3: Finding integer solutions to systems of linear equations
Lecture 3: Finding integer solutions to systems of linear equations Algorithmic Number Theory (Fall 2014) Rutgers University Swastik Kopparty Scribe: Abhishek Bhrushundi 1 Overview The goal of this lecture
A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:
Binary Search Trees 1 The general binary tree shown in the previous chapter is not terribly useful in practice. The chief use of binary trees is for providing rapid access to data (indexing, if you will)
Software Engineering Techniques
Software Engineering Techniques Low level design issues for programming-in-the-large. Software Quality Design by contract Pre- and post conditions Class invariants Ten do Ten do nots Another type of summary
Visual Basic Programming. An Introduction
Visual Basic Programming An Introduction Why Visual Basic? Programming for the Windows User Interface is extremely complicated. Other Graphical User Interfaces (GUI) are no better. Visual Basic provides
6 3 4 9 = 6 10 + 3 10 + 4 10 + 9 10
Lesson The Binary Number System. Why Binary? The number system that you are familiar with, that you use every day, is the decimal number system, also commonly referred to as the base- system. When you
JavaScript: Introduction to Scripting. 2008 Pearson Education, Inc. All rights reserved.
1 6 JavaScript: Introduction to Scripting 2 Comment is free, but facts are sacred. C. P. Scott The creditor hath a better memory than the debtor. James Howell When faced with a decision, I always ask,
Statements and Control Flow
Contents 1. Introduction 2. Types and Variables 3. Statements and Control Flow 4. Reading Input 5. Classes and Objects 6. Arrays 7. Methods 8. Scope and Lifetime 9. Utility classes 10. Introduction to
Visual Logic Instructions and Assignments
Visual Logic Instructions and Assignments Visual Logic can be installed from the CD that accompanies our textbook. It is a nifty tool for creating program flowcharts, but that is only half of the story.
Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.
Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to
2) Write in detail the issues in the design of code generator.
COMPUTER SCIENCE AND ENGINEERING VI SEM CSE Principles of Compiler Design Unit-IV Question and answers UNIT IV CODE GENERATION 9 Issues in the design of code generator The target machine Runtime Storage
Getting Started with the Internet Communications Engine
Getting Started with the Internet Communications Engine David Vriezen April 7, 2014 Contents 1 Introduction 2 2 About Ice 2 2.1 Proxies................................. 2 3 Setting Up ICE 2 4 Slices 2
First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science
First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca
Lecture 2 Notes: Flow of Control
6.096 Introduction to C++ January, 2011 Massachusetts Institute of Technology John Marrero Lecture 2 Notes: Flow of Control 1 Motivation Normally, a program executes statements from first to last. The
We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.
LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.
Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.
1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays
NUMBER SYSTEMS. William Stallings
NUMBER SYSTEMS William Stallings The Decimal System... The Binary System...3 Converting between Binary and Decimal...3 Integers...4 Fractions...5 Hexadecimal Notation...6 This document available at WilliamStallings.com/StudentSupport.html
JavaScript: Control Statements I
1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can
1 Introduction. 2 An Interpreter. 2.1 Handling Source Code
1 Introduction The purpose of this assignment is to write an interpreter for a small subset of the Lisp programming language. The interpreter should be able to perform simple arithmetic and comparisons
J a v a Quiz (Unit 3, Test 0 Practice)
Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points
While Loop. 6. Iteration
While Loop 1 Loop - a control structure that causes a set of statements to be executed repeatedly, (reiterated). While statement - most versatile type of loop in C++ false while boolean expression true
Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition
Chapter 2: Algorithm Discovery and Design Invitation to Computer Science, C++ Version, Third Edition Objectives In this chapter, you will learn about: Representing algorithms Examples of algorithmic problem
NUMBER SYSTEMS APPENDIX D. You will learn about the following in this appendix:
APPENDIX D NUMBER SYSTEMS You will learn about the following in this appendix: The four important number systems in computing binary, octal, decimal, and hexadecimal. A number system converter program
Boolean Expressions 1. In C++, the number 0 (zero) is considered to be false, all other numbers are true.
Boolean Expressions Boolean Expressions Sometimes a programmer would like one statement, or group of statements to execute only if certain conditions are true. There may be a different statement, or group
VB.NET Programming Fundamentals
Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements
Writing an essay. This seems obvious - but it is surprising how many people don't really do this.
Writing an essay Look back If this is not your first essay, take a look at your previous one. Did your tutor make any suggestions that you need to bear in mind for this essay? Did you learn anything else
Chapter 8 Selection 8-1
Chapter 8 Selection 8-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow
UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger
UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS 61B Fall 2014 P. N. Hilfinger Unit Testing with JUnit 1 The Basics JUnit is a testing framework
Python Programming: An Introduction To Computer Science
Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e 1 Objectives æ To understand the concept of Boolean expressions and the bool data
Object Oriented Software Design
Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction
Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, 2008. 1 Introduction 1. 2 Invoking Shell Scripts 2
Unix Shell Scripts Norman Matloff July 30, 2008 Contents 1 Introduction 1 2 Invoking Shell Scripts 2 2.1 Direct Interpretation....................................... 2 2.2 Indirect Interpretation......................................
Unit 1 Number Sense. In this unit, students will study repeating decimals, percents, fractions, decimals, and proportions.
Unit 1 Number Sense In this unit, students will study repeating decimals, percents, fractions, decimals, and proportions. BLM Three Types of Percent Problems (p L-34) is a summary BLM for the material
Guide to Performance and Tuning: Query Performance and Sampled Selectivity
Guide to Performance and Tuning: Query Performance and Sampled Selectivity A feature of Oracle Rdb By Claude Proteau Oracle Rdb Relational Technology Group Oracle Corporation 1 Oracle Rdb Journal Sampled
In mathematics, it is often important to get a handle on the error term of an approximation. For instance, people will write
Big O notation (with a capital letter O, not a zero), also called Landau's symbol, is a symbolism used in complexity theory, computer science, and mathematics to describe the asymptotic behavior of functions.
Module 2 Stacks and Queues: Abstract Data Types
Module 2 Stacks and Queues: Abstract Data Types A stack is one of the most important and useful non-primitive linear data structure in computer science. It is an ordered collection of items into which
Mathematical Induction
Mathematical Induction In logic, we often want to prove that every member of an infinite set has some feature. E.g., we would like to show: N 1 : is a number 1 : has the feature Φ ( x)(n 1 x! 1 x) How
Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C
Basic Java Constructs and Data Types Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C 1 Contents Hello World Program Statements Explained Java Program Structure in
Discrete Mathematics and Probability Theory Fall 2009 Satish Rao, David Tse Note 2
CS 70 Discrete Mathematics and Probability Theory Fall 2009 Satish Rao, David Tse Note 2 Proofs Intuitively, the concept of proof should already be familiar We all like to assert things, and few of us
CALCULATIONS & STATISTICS
CALCULATIONS & STATISTICS CALCULATION OF SCORES Conversion of 1-5 scale to 0-100 scores When you look at your report, you will notice that the scores are reported on a 0-100 scale, even though respondents
Programming Languages
Programming Languages Programming languages bridge the gap between people and machines; for that matter, they also bridge the gap among people who would like to share algorithms in a way that immediately
Concepts and terminology in the Simula Programming Language
Concepts and terminology in the Simula Programming Language An introduction for new readers of Simula literature Stein Krogdahl Department of Informatics University of Oslo, Norway April 2010 Introduction
CS 2112 Spring 2014. 0 Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions
CS 2112 Spring 2014 Assignment 3 Data Structures and Web Filtering Due: March 4, 2014 11:59 PM Implementing spam blacklists and web filters requires matching candidate domain names and URLs very rapidly
public static void main(string[] args) { System.out.println("hello, world"); } }
Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static
CS 106 Introduction to Computer Science I
CS 106 Introduction to Computer Science I 01 / 21 / 2014 Instructor: Michael Eckmann Today s Topics Introduction Homework assignment Review the syllabus Review the policies on academic dishonesty and improper
C++ INTERVIEW QUESTIONS
C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get
Iteration CHAPTER 6. Topic Summary
CHAPTER 6 Iteration TOPIC OUTLINE 6.1 while Loops 6.2 for Loops 6.3 Nested Loops 6.4 Off-by-1 Errors 6.5 Random Numbers and Simulations 6.6 Loop Invariants (AB only) Topic Summary 6.1 while Loops Many
Sources: On the Web: Slides will be available on:
C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,
Chapter 8: Bags and Sets
Chapter 8: Bags and Sets In the stack and the queue abstractions, the order that elements are placed into the container is important, because the order elements are removed is related to the order in which
Part I. Multiple Choice Questions (2 points each):
Part I. Multiple Choice Questions (2 points each): 1. Which of the following is NOT a key component of object oriented programming? (a) Inheritance (b) Encapsulation (c) Polymorphism (d) Parallelism ******
INTRUSION PREVENTION AND EXPERT SYSTEMS
INTRUSION PREVENTION AND EXPERT SYSTEMS By Avi Chesla [email protected] Introduction Over the past few years, the market has developed new expectations from the security industry, especially from the intrusion
The last three chapters introduced three major proof techniques: direct,
CHAPTER 7 Proving Non-Conditional Statements The last three chapters introduced three major proof techniques: direct, contrapositive and contradiction. These three techniques are used to prove statements
COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012
Binary numbers The reason humans represent numbers using decimal (the ten digits from 0,1,... 9) is that we have ten fingers. There is no other reason than that. There is nothing special otherwise about
Java Interview Questions and Answers
1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java
Lecture 4: Writing shell scripts
Handout 5 06/03/03 1 Your rst shell script Lecture 4: Writing shell scripts Shell scripts are nothing other than les that contain shell commands that are run when you type the le at the command line. That
Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java
Outline. Written Communication Conveying Scientific Information Effectively. Objective of (Scientific) Writing
Written Communication Conveying Scientific Information Effectively Marie Davidian [email protected] http://www.stat.ncsu.edu/ davidian. Outline Objectives of (scientific) writing Important issues
Not agree with bug 3, precision actually was. 8,5 not set in the code. Not agree with bug 3, precision actually was
Task 1 Task 2 Task 3 Feedback Presence SUM Matrikkel Rühm [5] [1] [2] [1] [1] [10] Feedback to students A64129 1. rühm 0 0 No submission found A72068 1. rühm 5 1 2 1 1 For Bug 3. Actually the variable
MATLAB Programming. Problem 1: Sequential
Division of Engineering Fundamentals, Copyright 1999 by J.C. Malzahn Kampe 1 / 21 MATLAB Programming When we use the phrase computer solution, it should be understood that a computer will only follow directions;
NP-Completeness and Cook s Theorem
NP-Completeness and Cook s Theorem Lecture notes for COM3412 Logic and Computation 15th January 2002 1 NP decision problems The decision problem D L for a formal language L Σ is the computational task:
Designing with Exceptions. CSE219, Computer Science III Stony Brook University http://www.cs.stonybrook.edu/~cse219
Designing with Exceptions CSE219, Computer Science III Stony Brook University http://www.cs.stonybrook.edu/~cse219 Testing vs. Debugging Testing Coding Does the code work properly YES NO 2 Debugging Testing
IF The customer should receive priority service THEN Call within 4 hours PCAI 16.4
Back to Basics Backward Chaining: Expert System Fundamentals By Dustin Huntington Introduction Backward chaining is an incredibly powerful yet widely misunderstood concept, yet it is key to building many
language 1 (source) compiler language 2 (target) Figure 1: Compiling a program
CS 2112 Lecture 27 Interpreters, compilers, and the Java Virtual Machine 1 May 2012 Lecturer: Andrew Myers 1 Interpreters vs. compilers There are two strategies for obtaining runnable code from a program
A Little Set Theory (Never Hurt Anybody)
A Little Set Theory (Never Hurt Anybody) Matthew Saltzman Department of Mathematical Sciences Clemson University Draft: August 21, 2013 1 Introduction The fundamental ideas of set theory and the algebra
Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game
Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game Directions: In mobile Applications the Control Model View model works to divide the work within an application.
Subversion workflow guide
Subversion workflow guide Joanne Carr January 2010 Contents 1 Before we start: some definitions, etc. 2 2 UKRmol-in repository layout 3 3 Checking out 3 4 Monitoring and dealing with
Capabilities of a Java Test Execution Framework by Erick Griffin
Capabilities of a Java Test Execution Framework by Erick Griffin Here we discuss key properties and capabilities of a Java Test Execution Framework for writing and executing discrete Java tests for testing
Automata and Computability. Solutions to Exercises
Automata and Computability Solutions to Exercises Fall 25 Alexis Maciel Department of Computer Science Clarkson University Copyright c 25 Alexis Maciel ii Contents Preface vii Introduction 2 Finite Automata
Chapter 14: Boolean Expressions Bradley Kjell (Revised 10/08/08)
Chapter 14: Boolean Expressions Bradley Kjell (Revised 10/08/08) The if statements of the previous chapters ask simple questions such as count
CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team
CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team Lecture Summary In this lecture, we learned about the ADT Priority Queue. A
Aim To help students prepare for the Academic Reading component of the IELTS exam.
IELTS Reading Test 1 Teacher s notes Written by Sam McCarter Aim To help students prepare for the Academic Reading component of the IELTS exam. Objectives To help students to: Practise doing an academic
Lecture Notes on Binary Search Trees
Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 17 October 23, 2014 1 Introduction In this lecture, we will continue considering associative
