Chapter 5. Selection 5-1

Size: px
Start display at page:

Download "Chapter 5. Selection 5-1"

Transcription

1 Chapter 5 Selection 5-1

2 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow of instructions in a program. This is done using selection statements. When we make the computer choose between two alternatives we will define one of the alternatives as begin true and the other as being false. This choice will be made using a boolean expression. Boolean Expression an expression that evaluates to either true or false When boolean expressions are formed they must set up a relationship between items in the expression. This relationship is set up using a set of operators called the relational operators. Relational Operators: == (equal) < (less than) > (greater than) <= (less than or equal) >= (greater than or equal)!= (not equal) NOTE: The assignment operator is (=) but the relational operator is(= =). In other words, if you are assigning a value to a variable, use (=) but if you are asking whether two things are equal, use (= =). 5-2

3 Comparing Floating Point Numbers It is common to use numeric values in decision statements. Due to the way floating point numbers are stored in memory, do not compare two floating point values for equality. Floating point numbers must be rounded when they are stored in memory and rarely evaluate to be exactly the same. What we want to do is check to see if they are close enough to equal for us to call them equal. One easy method for doing this is to compare the absolute value of the difference of the numbers with some very small epsilon value. Given the following const float EPSILON = ; float val1, val2; if (fabs(val1 - val2) < EPSILON) cout << "values are equal"; fabs is a C++ library function that returns the absolute value of a floating point expression. 5-3

4 Examples of boolean expressions: Expression Result 5 == 5 TRUE a < c TRUE > 10 FALSE 10!= 20 TRUE 6 <= 6 TRUE 5 >= 9 FALSE A < Z TRUE a < Z FALSE (WHY?) Given two variables n1 and n2, assume n1 contains 5 and n2 contains 3. Evaluate each of the following boolean expressions: n1 + 3!= n2 + 5 n1 * 2 <= n2 * 2 n1 >= n2 n2 <= n1 n2 + n1 + 3 == n1 + 6 The precedence order when the relational operators are added is as follows: * / % + - < <= > >= ==!= = Parentheses may be used to alter the order of evaluation. 5-4

5 The C++ If-Then and If-Then-Else Statements The use of the If-Then and If-Then-Else statements in a program allows the programmer to include all possible options in the program code and the computer to select the appropriate option during program execution. Flowchart for the If-Then statement boolean expression F T statement The boolean expression is evaluated and if it evaluates to TRUE the statement inside the If is executed and the program continues to the next executable statement. If the expression evaluates to FALSE, the statement inside the If is ignored and the program continues with the next executable statement. GENERAL FORM of the If-Then statement: if (boolean expression) statement; 5-5

6 hours <= 40 F T output No overtime if (hours <= 40) cout << No overtime << endl; cout << Continue << endl; Given a value of 25 in the location hours, the program would output No overtime Continue If location hours contained the value 50, the program would output Continue 5-6

7 Nested If-Then Statements A nested If-Then is an If-Then that contains another If-Then within it. Suppose we wanted to identify 18 year old males. We could first determine whether the age requirement was met and if so, check to see whether the individual is a male. Outer If age == 18 T F sex == M T Inner If F output The Marine Corps is looking for a few good men. if (age == 18) if (sex == M ) cout << The Marine Corps is looking for a few good men. ; 5-7

8 The If-Then-Else Statement In the If-Then statement a condition was evaluated and if the condition was true, an instruction was executed and the program continued on, if the condition was false, the program simply continued on. The If-Then-Else statement assures that some action will take place before the program continues. If the condition is true then do this else do that. GENERAL FORM If-Then-Else Statement if (Expression) statement 1; else statement 2; Flowchart for If-Then-Else F boolean T expression statement 2 statement 1 5-8

9 Example: F hours <= 40 T output overtime due output no overtime C++ code: if (hours <= 40) cout << no overtime ; else cout << overtime due ; It is possible to nest If-Then-Else statements just as we did with If-Then statements. 5-9

10 If-Then-Else Exercise 1.) Draw the flowchart for a program that will receive three integers from the user. Your program is to output the largest of the three. We will assume that the three values are not equal. KEEP THIS AS AN EXAMPLE OF THE CORRECT FLOWCHART STYLE FOR NESTED IF/ELSE STATEMENTS. 5-10

11 The Conditional Operator The conditional operator is a shortcut method that may be used to create simple if/else expressions. GENERAL FORM: Expression? expression : expression; Example: overtime = hrswkd > 40? (hrswkd-40)*rate*1.5 : 0.0; The part of the conditional expression that precedes the? is the expression to be tested (like the expression in parentheses in an if statement). If the expression is true, the statement between the? and : is executed otherwise the expression after the : is executed. The statement above could replace the block if shown below. if (hrswkd > 40) overtime = hrswkd-40) * rate * 1.5; else overtime = 0.0; or even cout << Overtime is << (hrswkd > 40? (hrswkd-40)* rate * 1.5 : 0.0); 5-11

12 Logical/Boolean Operators and Expressions George Boole s The Mathematical Analysis of Logic was published in The formal axioms of logic were set forth in this book and the field of symbolic logic was built. This logic eventually formed the basis for the development of digital computers. We will use the boolean operators to form complex decision statements. NOT! unary operator AND && binary operator OR binary operator By using these operators in conjunction with the relational operators, more complex expressions may be formed. NOT (!) precedes a single expression and gives its opposite as the result. hrswkd <= 40 is equivalent to!(hrswkd > 40) 5-12

13 AND (&&) combines two logical expressions and requires that both expressions be TRUE for the entire expression to be TRUE num1 <= 10 && num1!= 5 The value of num1 would need to be less than or equal to 10 and also not equal to 5 for this expression to be TRUE OR ( ) combines two logical expressions and states that if either or both of the expressions are TRUE, the entire expression is TRUE num1 <1 num1 > 10 If the value of num1 is not in the range 1-10 this expression evaluates to TRUE Rewrite the following expressions:!(num1 == num2)!(num1 == num2 num1 == num3)!(num1 == num2 && num3 > num4) 5-13

14 In math books the notation 5 < x < 15 is common. It means that x is between 5 and 15. While the expression is legal in C++ the result is unexpected. What is the result and why? How should the expression be written? 5-14

15 Short-Circuit Evaluation: Evaluation of a logical expression in left-toright order with evaluation stopping as soon as the final truth can be determined. When AND is used in an expression, the computer stops evaluation as soon as a FALSE condition is found. When OR is used in an expression, evaluation can stop as soon as the first TRUE condition is found. Some languages use full evaluation of logical expressions where both subexpressions are evaluated before the && or operator is applied. Precedence of Operators ( ) Highest ++ --! * / % + - < <= > >= ==!= && = Lowest 5-15

16 Exercises 1 Given the following values for variables a, b and c: a = TRUE b = FALSE c = TRUE evaluate each of the following expressions a) a && b a && c b)!(a && c) b c)!a c && b 2. Rewrite the following expressions so they would be valid in C++. a) a, b and c are all less than 10 b) a > b >= c c) a does not equal either b or c d) a equals b but does not equal c 5-16

17 Boolean Expressions Programming Exercise A military academy accepts candidates according to the following height and weight requirements. Gender Min. Height Max. Height Min. Weight Max. Weight Male 62 in. 78 in. 130 lbs. 250 lbs. Female 60 in. 72 in. 110 lbs. 185 lbs. Design a program that accepts as input the gender, height and weight of a candidate. Check to see if the candidate meets the height requirements and store the result in a bool variable called heightok. Next check the weight requirements and store the result in a bool variable called weightok. Using these results, determine whether the candidate was accepted, rejected for height only, rejected for weight only or rejected for both height and weight. Output an appropriate message for each possible outcome. 5-17

18 Multi-way Selection The switch statement in C++ provides a way to eliminate some nested if structures. The general form for the switch statement is switch (IntegralExpression) SwitchLabel statement;.. The general form for the SwitchLabel is case ConstantExpression: default: where The switch expression is the expression whose value determines which label is selected. It cannot be a floating point expression. The SwitchLabel is either a case label or a default label. In the case label, the ConstantExpression must be an integral literal or a named constant. Each case constant may appear only once in the statement. The switch expression is evaluated and if the value matches one of the constants in the case label, control branches to to the statement following the label. From there it proceeds sequentially until the end of the switch statement or until a break is encountered. If there is no matching label for the expression, it looks for a default label and if found, executes the statement following the label. If no default label is present, control transfers to the statement following the end of the switch statement. 5-18

19 Example: classcode F S J R default Freshman Sophomore Junior Senior Invalid switch (classcode) case F : cout << You are a freshman ; break; case S : cout << You are a sophomore ; break; case J : cout << You are a junior ; break; case R : cout << You are a senior ; break; default : cout << You entered an invalid code ; break; // not necessary but a good habit 5-19

20 The fact that without the break statement, the program follows through can be helpful in some situations. Suppose we wanted to allow for lower case input as well. switch (classcode) case F : case f : cout << You are a freshman ; break; case S : case s : cout << You are a sophomore ; break; etc. Switch Exercises: 1. Flowchart a code segment that reads a letter grade from the keyboard and prints good work for A and B students, average work for C students, and poor work for D and F students. Draw this flowchart as a nested if. 2 Write the C++ code to match the flowchart from #1. 3 Draw the flowchart to convert the nested if into a switch statement. 4 Write the C++ code for the flowchart from #

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

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

More information

Chapter 8 Selection 8-1

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

More information

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be... What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

More information

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

Conditions & Boolean Expressions

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

More information

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

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

More information

Lecture 2 Notes: Flow of Control

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

More information

Conditionals (with solutions)

Conditionals (with solutions) Conditionals (with solutions) For exercises 1 to 27, indicate the output that will be produced. Assume the following declarations: final int MAX = 25, LIMIT = 100; int num1 = 12, num2 = 25, num3 = 87;

More information

Object Oriented Software Design

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

More information

Chapter One Introduction to Programming

Chapter One Introduction to Programming Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of

More information

ALGORITHMS AND FLOWCHARTS

ALGORITHMS AND FLOWCHARTS ALGORITHMS AND FLOWCHARTS A typical programming task can be divided into two phases: Problem solving phase produce an ordered sequence of steps that describe solution of problem this sequence of steps

More information

Selection Statements

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:

More information

While Loop. 6. Iteration

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

More information

6. Control Structures

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,

More information

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements 9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

More information

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics

More information

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions Phys4051: C Lecture 2 & 3 Functions (Review) Comment Statements Variables & Operators Branching Instructions Comment Statements! Method 1: /* */! Method 2: // /* Single Line */ //Single Line /* This comment

More information

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

The While Loop. Objectives. Textbook. WHILE Loops

The While Loop. Objectives. Textbook. WHILE Loops Objectives The While Loop 1E3 Topic 6 To recognise when a WHILE loop is needed. To be able to predict what a given WHILE loop will do. To be able to write a correct WHILE loop. To be able to use a WHILE

More information

ALGORITHMS AND FLOWCHARTS. By Miss Reham Tufail

ALGORITHMS AND FLOWCHARTS. By Miss Reham Tufail ALGORITHMS AND FLOWCHARTS By Miss Reham Tufail ALGORITHMS AND FLOWCHARTS A typical programming task can be divided into two phases: Problem solving phase produce an ordered sequence of steps that describe

More information

Statements and Control Flow

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

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Logic in Computer Science: Logic Gates

Logic in Computer Science: Logic Gates Logic in Computer Science: Logic Gates Lila Kari The University of Western Ontario Logic in Computer Science: Logic Gates CS2209, Applied Logic for Computer Science 1 / 49 Logic and bit operations Computers

More information

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

More information

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction IS0020 Program Design and Software Tools Midterm, Feb 24, 2004 Name: Instruction There are two parts in this test. The first part contains 50 questions worth 80 points. The second part constitutes 20 points

More information

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. 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

More information

Comp151. Definitions & Declarations

Comp151. Definitions & Declarations Comp151 Definitions & Declarations Example: Definition /* reverse_printcpp */ #include #include using namespace std; int global_var = 23; // global variable definition void reverse_print(const

More information

Boolean Expressions 1. In C++, the number 0 (zero) is considered to be false, all other numbers are true.

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

More information

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures The C++ Language Loops Loops! Recall that a loop is another of the four basic programming language structures Repeat statements until some condition is false. Condition False True Statement1 2 1 Loops

More information

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1 QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For

More information

UEE1302 (1102) F10 Introduction to Computers and Programming

UEE1302 (1102) F10 Introduction to Computers and Programming Computational Intelligence on Automation Lab @ NCTU UEE1302 (1102) F10 Introduction to Computers and Programming Programming Lecture 03 Flow of Control (Part II): Repetition while,for & do..while Learning

More information

Chapter 14: Boolean Expressions Bradley Kjell (Revised 10/08/08)

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

More information

VB.NET Programming Fundamentals

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

More information

COMPUTER SCIENCE 1999 (Delhi Board)

COMPUTER SCIENCE 1999 (Delhi Board) COMPUTER SCIENCE 1999 (Delhi Board) Time allowed: 3 hours Max. Marks: 70 Instructions: (i) All the questions are compulsory. (ii) Programming Language: C++ QUESTION l. (a) Why main function is special?

More information

Chapter 5 Functions. Introducing Functions

Chapter 5 Functions. Introducing Functions Chapter 5 Functions 1 Introducing Functions A function is a collection of statements that are grouped together to perform an operation Define a function Invoke a funciton return value type method name

More information

13 Classes & Objects with Constructors/Destructors

13 Classes & Objects with Constructors/Destructors 13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.

More information

Boolean Data Outline

Boolean Data Outline 1. Boolean Data Outline 2. Data Types 3. C Boolean Data Type: char or int 4. C Built-In Boolean Data Type: bool 5. bool Data Type: Not Used in CS1313 6. Boolean Declaration 7. Boolean or Character? 8.

More information

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine 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

More information

Moving from C++ to VBA

Moving from C++ to VBA Introduction College of Engineering and Computer Science Mechanical Engineering Department Mechanical Engineering 309 Numerical Analysis of Engineering Systems Fall 2014 Number: 15237 Instructor: Larry

More information

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void 1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

More information

The if Statement and Practice Problems

The if Statement and Practice Problems The if Statement and Practice Problems The Simple if Statement Use To specify the conditions under which a statement or group of statements should be executed. Form if (boolean-expression) statement; where

More information

C++FA 5.1 PRACTICE MID-TERM EXAM

C++FA 5.1 PRACTICE MID-TERM EXAM C++FA 5.1 PRACTICE MID-TERM EXAM This practicemid-term exam covers sections C++FA 1.1 through C++FA 1.4 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A pointer

More information

Conditional Statements. 15-110 Summer 2010 Margaret Reid-Miller

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

More information

Sources: On the Web: Slides will be available on:

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,

More information

Why? A central concept in Computer Science. Algorithms are ubiquitous.

Why? A central concept in Computer Science. Algorithms are ubiquitous. Analysis of Algorithms: A Brief Introduction Why? A central concept in Computer Science. Algorithms are ubiquitous. Using the Internet (sending email, transferring files, use of search engines, online

More information

Boolean Expressions & the if Statement

Boolean Expressions & the if Statement Midterm Results Boolean Expressions & the if Statement September 24, 2007 Average: 91.6 Median: 94 Standard Deviation: 18.80 Maximum: 129 (out of 130) ComS 207: Programming I (in Java) Iowa State University,

More information

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 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

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

if and if-else: Part 1

if and if-else: Part 1 if and if-else: Part 1 Objectives Write if statements (including blocks) Write if-else statements (including blocks) Write nested if-else statements We will now talk about writing statements that make

More information

Intermediate Code. Intermediate Code Generation

Intermediate Code. Intermediate Code Generation Intermediate Code CS 5300 - SJAllan Intermediate Code 1 Intermediate Code Generation The front end of a compiler translates a source program into an intermediate representation Details of the back end

More information

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language Simple C++ Programs Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from

More information

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference? Functions in C++ Let s take a look at an example declaration: Lecture 2 long factorial(int n) Functions The declaration above has the following meaning: The return type is long That means the function

More information

Gates, Circuits, and Boolean Algebra

Gates, Circuits, and Boolean Algebra Gates, Circuits, and Boolean Algebra Computers and Electricity A gate is a device that performs a basic operation on electrical signals Gates are combined into circuits to perform more complicated tasks

More information

Python Programming: An Introduction To Computer Science

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

More information

I PUC - Computer Science. Practical s Syllabus. Contents

I PUC - Computer Science. Practical s Syllabus. Contents I PUC - Computer Science Practical s Syllabus Contents Topics 1 Overview Of a Computer 1.1 Introduction 1.2 Functional Components of a computer (Working of each unit) 1.3 Evolution Of Computers 1.4 Generations

More information

Passing 1D arrays to functions.

Passing 1D arrays to functions. Passing 1D arrays to functions. In C++ arrays can only be reference parameters. It is not possible to pass an array by value. Therefore, the ampersand (&) is omitted. What is actually passed to the function,

More information

WESTMORELAND COUNTY PUBLIC SCHOOLS 2011 2012 Integrated Instructional Pacing Guide and Checklist Computer Math

WESTMORELAND COUNTY PUBLIC SCHOOLS 2011 2012 Integrated Instructional Pacing Guide and Checklist Computer Math Textbook Correlation WESTMORELAND COUNTY PUBLIC SCHOOLS 2011 2012 Integrated Instructional Pacing Guide and Checklist Computer Math Following Directions Unit FIRST QUARTER AND SECOND QUARTER Logic Unit

More information

Boolean Logic in MATLAB

Boolean Logic in MATLAB Boolean Logic in MATLAB When programming, there will be times when you want to control the flow of your code based on certain events occurring or certain values being reached. Primarily, this is handled

More information

Handout #1: Mathematical Reasoning

Handout #1: Mathematical Reasoning Math 101 Rumbos Spring 2010 1 Handout #1: Mathematical Reasoning 1 Propositional Logic A proposition is a mathematical statement that it is either true or false; that is, a statement whose certainty or

More information

Chapter 3 Operators and Control Flow

Chapter 3 Operators and Control Flow Chapter 3 Operators and Control Flow I n this chapter, you will learn about operators, control flow statements, and the C# preprocessor. Operators provide syntax for performing different calculations or

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

Lecture 12: More on Registers, Multiplexers, Decoders, Comparators and Wot- Nots

Lecture 12: More on Registers, Multiplexers, Decoders, Comparators and Wot- Nots Lecture 12: More on Registers, Multiplexers, Decoders, Comparators and Wot- Nots Registers As you probably know (if you don t then you should consider changing your course), data processing is usually

More information

Accentuate the Negative: Homework Examples from ACE

Accentuate the Negative: Homework Examples from ACE Accentuate the Negative: Homework Examples from ACE Investigation 1: Extending the Number System, ACE #6, 7, 12-15, 47, 49-52 Investigation 2: Adding and Subtracting Rational Numbers, ACE 18-22, 38(a),

More information

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

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)

More information

1. True or False? A voltage level in the range 0 to 2 volts is interpreted as a binary 1.

1. True or False? A voltage level in the range 0 to 2 volts is interpreted as a binary 1. File: chap04, Chapter 04 1. True or False? A voltage level in the range 0 to 2 volts is interpreted as a binary 1. 2. True or False? A gate is a device that accepts a single input signal and produces one

More information

COMP 110 Prasun Dewan 1

COMP 110 Prasun Dewan 1 COMP 110 Prasun Dewan 1 12. 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

More information

Python Evaluation Rules

Python Evaluation Rules Python Evaluation Rules UW CSE 160 http://tinyurl.com/dataprogramming Michael Ernst and Isaac Reynolds mernst@cs.washington.edu August 2, 2016 Contents 1 Introduction 2 1.1 The Structure of a Python Program................................

More information

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. 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:

More information

PIC 10A. Lecture 7: Graphics II and intro to the if statement

PIC 10A. Lecture 7: Graphics II and intro to the if statement PIC 10A Lecture 7: Graphics II and intro to the if statement Setting up a coordinate system By default the viewing window has a coordinate system already set up for you 10-10 10-10 The origin is in the

More information

In mathematics, it is often important to get a handle on the error term of an approximation. For instance, people will write

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.

More information

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013 Masters programmes in Computer Science and Information Systems Object-Oriented Design and Programming Sample module entry test xxth December 2013 This sample paper has more questions than the real paper

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 1/e 1 Objectives To understand the programming pattern simple decision and its implementation using

More information

CSC 221: Computer Programming I. Fall 2011

CSC 221: Computer Programming I. Fall 2011 CSC 221: Computer Programming I Fall 2011 Python control statements operator precedence importing modules random, math conditional execution: if, if-else, if-elif-else counter-driven repetition: for conditional

More information

Basic Programming and PC Skills: Basic Programming and PC Skills:

Basic Programming and PC Skills: Basic Programming and PC Skills: Texas University Interscholastic League Contest Event: Computer Science The contest challenges high school students to gain an understanding of the significance of computation as well as the details of

More information

Selection: Boolean Expressions (2) Precedence chart:

Selection: Boolean Expressions (2) Precedence chart: Selection: Boolean Expressions Boolan operators: Return a Boolean value Types: 1. Relational operators Operators: (a) < (less than) (b) > (greater than) (c) = (equal to) (d)

More information

Adding and Subtracting Positive and Negative Numbers

Adding and Subtracting Positive and Negative Numbers Adding and Subtracting Positive and Negative Numbers Absolute Value For any real number, the distance from zero on the number line is the absolute value of the number. The absolute value of any real number

More information

Two-way selection. Branching and Looping

Two-way selection. Branching and Looping Control Structures: are those statements that decide the order in which individual statements or instructions of a program are executed or evaluated. Control Structures are broadly classified into: 1.

More information

Shell Scripts (1) For example: #!/bin/sh If they do not, the user's current shell will be used. Any Unix command can go in a shell script

Shell Scripts (1) For example: #!/bin/sh If they do not, the user's current shell will be used. Any Unix command can go in a shell script Shell Programming Shell Scripts (1) Basically, a shell script is a text file with Unix commands in it. Shell scripts usually begin with a #! and a shell name For example: #!/bin/sh If they do not, the

More information

Lecture Notes on Linear Search

Lecture Notes on Linear Search Lecture Notes on Linear Search 15-122: Principles of Imperative Computation Frank Pfenning Lecture 5 January 29, 2013 1 Introduction One of the fundamental and recurring problems in computer science is

More information

Binary Adders: Half Adders and Full Adders

Binary Adders: Half Adders and Full Adders Binary Adders: Half Adders and Full Adders In this set of slides, we present the two basic types of adders: 1. Half adders, and 2. Full adders. Each type of adder functions to add two binary bits. In order

More information

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Example Assume the following specification: Input: read a number N > 0 Output:

More information

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification: Example Introduction to Programming (in C++) Loops Assume the following specification: Input: read a number N > 0 Output: write the sequence 1 2 3 N (one number per line) Jordi Cortadella, Ricard Gavaldà,

More information

6 3 4 9 = 6 10 + 3 10 + 4 10 + 9 10

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

More information

Common Beginner C++ Programming Mistakes

Common Beginner C++ Programming Mistakes Common Beginner C++ Programming Mistakes This documents some common C++ mistakes that beginning programmers make. These errors are two types: Syntax errors these are detected at compile time and you won't

More information

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. 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

More information

A.2. Exponents and Radicals. Integer Exponents. What you should learn. Exponential Notation. Why you should learn it. Properties of Exponents

A.2. Exponents and Radicals. Integer Exponents. What you should learn. Exponential Notation. Why you should learn it. Properties of Exponents Appendix A. Exponents and Radicals A11 A. Exponents and Radicals What you should learn Use properties of exponents. Use scientific notation to represent real numbers. Use properties of radicals. Simplify

More information

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java

More information

COMBINATIONAL CIRCUITS

COMBINATIONAL CIRCUITS COMBINATIONAL CIRCUITS http://www.tutorialspoint.com/computer_logical_organization/combinational_circuits.htm Copyright tutorialspoint.com Combinational circuit is a circuit in which we combine the different

More information

Writing Control Structures

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

More information

Chapter 3. Cartesian Products and Relations. 3.1 Cartesian Products

Chapter 3. Cartesian Products and Relations. 3.1 Cartesian Products Chapter 3 Cartesian Products and Relations The material in this chapter is the first real encounter with abstraction. Relations are very general thing they are a special type of subset. After introducing

More information

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A Developed By Brian Weinfeld Course Description: AP Computer

More information

The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002. True or False (2 points each)

The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002. True or False (2 points each) True or False (2 points each) The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002 1. Using global variables is better style than using local

More information

Moving from CS 61A Scheme to CS 61B Java

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

More information

Compiler Construction

Compiler Construction Compiler Construction Lecture 1 - An Overview 2003 Robert M. Siegfried All rights reserved A few basic definitions Translate - v, a.to turn into one s own language or another. b. to transform or turn from

More information

C H A P T E R Regular Expressions regular expression

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

More information

Answers to Review Questions Chapter 7

Answers to Review Questions Chapter 7 Answers to Review Questions Chapter 7 1. The size declarator is used in a definition of an array to indicate the number of elements the array will have. A subscript is used to access a specific element

More information

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands C Programming for Embedded Microcontrollers Warwick A. Smith Elektor International Media BV Postbus 11 6114ZG Susteren The Netherlands 3 the Table of Contents Introduction 11 Target Audience 11 What is

More information

Flowcharting, pseudocoding, and process design

Flowcharting, pseudocoding, and process design Systems Analysis Pseudocoding & Flowcharting 1 Flowcharting, pseudocoding, and process design The purpose of flowcharts is to represent graphically the logical decisions and progression of steps in the

More information