Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

Slides:



Advertisements
Similar presentations
True or false A variable of type char can hold the value 301. ( F )
Advertisements

1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Data types and variables
Chapter 2 Data Types, Declarations, and Displays
JavaScript, Third Edition
C++ for Engineers and Scientists Third Edition
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Objectives You should be able to describe: Data Types
Chapter 2: Introducing Data Types and Operators.  Know Java’s primitive types  Use literals  Initialize variables  Know the scope rules of variables.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
2440: 211 Interactive Web Programming Expressions & Operators.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Chapter 2: Using Data.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Flow of Control Part 1: Selection
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Operations Lecture 9.
Chapter 05 (Part III) Control Statements: Part II.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Selection Relational Expressions A condition or logical expression is an expression that can only take the values true or false. A.
Week 3 - Wednesday.  What did we talk about last time?  Other C features  sizeof, const  ASCII table  printf() format strings  Bitwise operations.
Operators Precedence - Operators with the highest precedence will be executed first. Page 54 of the book and Appendix B list C's operator precedence. Parenthesis.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Fluency with Information Technology Third Edition by Lawrence Snyder Chapter.
Decision Statements, Short- Circuit Evaluation, Errors.
CPS120: Introduction to Computer Science Decision Making in Programs.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Dr. Sajib Datta Jan 23,  A precedence for each operator ◦ Multiplication and division have a higher precedence than addition and subtraction.
Introduction to Algorithmic Processes CMPSC 201C Fall 2000.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Branching statements.
Chapter 3 Control Statements
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Chapter 4: Making Decisions.
Lecture 3- Decision Structures
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Introduction to C++ Programming
Chapter 8 JavaScript: Control Statements, Part 2
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Chapter 4: Control Structures I (Selection)
Boolean Expressions to Make Comparisons
Using C++ Arithmetic Operators and Control Structures
CSC215 Lecture Control Flow.
Controlling Program Flow
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation mark \?Question mark \dddASCII code in octal format \xddASCII code in hexadecimal format Escape Sequence Characters

Northeastern University 2 Flow Control 1 Decision Statements Boolean Expressions –Evaluate to TRUE (1) or FALSE (0) only. C++ uses integer to represent Boolean variables, 0 for FALSE and 1 for TRUE. However, any non-zero integer is regarded TRUE in C++. Relational Operations –Comparison between numerical quantities –Evaluate to TRUE (1) if relation is satisfied and FALSE (0) otherwise. –> (greater than), >= (greater than or equal to) –< (less than), <= (less or equal to) –== (equal to), != (not equal to)

Northeastern University 3 Decision Statements Boolean (Logic) Expressions –Operations on Boolean Variables –Binary: && (AND), || (OR) –Unary: ! (NOT or INVERSION) –Truth Table in C++ –Strictly speaking, Boolean algebra has only TRUE (1) or FALSE (0) but no non-zero.

Northeastern University 4 Decision Statements –The AND (&&) operator evaluates to true only when both operands are TRUE. If the first operand is FALSE, we don’t need to know the second operand for evaluation. Similarly, the OR (||) operator evaluates to FALSE only when both operands are FALSE. If the first operand is TRUE, we don’t need to know the second one. This is called short-circuit evaluation.

Northeastern University 5 –Assignment operator = The equal sign = assigns the value of the variable on its right to the memory location of the variable on its left. Unlike in mathematics where x = x + 1 is meaningless, in C++, the same expression means take the present value stored in the memory location corresponding to the identifier x, add 1 to it and store the result back to the same memory location. (x = x + 1 is usually written as x += 1 in C++). –Arithmetic Operators + - * / % (modulus, i.e. positive remainder of integer division) –Relational operators (return 1 if true and 0 if false): == (equal to) ; != (unequal) ; = ; ; && (and) ; || (or) ; ?: (conditional operator) –Assignment Operators = += -= /= %= &= |= ^= >>= <<= –Shift Operators: > –Bitwise Operators: ~ & | –Others: ! ( ) [ ] -->,. Arithmetic Expressions

Northeastern University 6 Operator Precedence An expression may contain multiple operators, operator precedence defines the order that operators in an expression are evaluated when multiple operators are present. The operator precedence in C++ is largely the same as the convention used in arithmetic, i.e.: 1. Function calls in an expression 2. Multiplication (*) and division (/) are performed in sequence 3. Addition (+) and subtraction (-). Operator precedence can be overwritten by using parentheses. It does no harm to put parentheses to force the sequence of the operation you want to perform when you are uncertain of the operator precedence.

Northeastern University 7

8 Precedence and associativity of operators C++ allows concantenation of operators. Precedence rule defines the order of operators and associativity defines the sequence of operation (from left to right or from right to left). Examples: 1. = is right associative,  a = b = 5;  a = (b = 5); 2. * and /, are left associative,  a *b / c;  (a * b) / c; 3. int a = 4, b = 5; double c, d; c = a / b * 2.0;/* c = 0.0 */ d = 2.0 * a / b;/* d = 1.6 */ 4. have higher precedence than &&,  a > b && a b) && (a < c) 5. + has higher precedence than >,  a + b > 0  (a + b) > 0

Northeastern University 9 Type of expression and conversion –The data type of the result of an expression such as x+y is the same as x and y if x and y are the same type –If x is int and y is double or vice versa, then the int is converted to double first before operation, the result is double –General rule for mixed-type expressions: the “smaller” operand is promoted (converted) to the biggest-range data type (normally double) before evaluation, e.g.: x is int and y is char, then y is promoted to int first and x+y evaluates to an int result. –If an assignment operator is used to assign the result of an expression to another variable, the expression is evaluated first according to the above conversion rule and the result is assigned to the value. Another conversion occurs if necessary.

Northeastern University 10 intx, y; double u, v; x = y + u; /* y+u is evaluated as double first. */ /* result is converted to int before assigned to x. */ v = x + y; /* x+y evaluated as int first. */ /* result is converted to double before assigned to v. */ Conversion from double to int may result in loss of precision, e.g.: if y + u = 2.4, x will be evaluated to 2. We can overwrite default conversion rule by casting, e.g. x and y can be cast as double before evaluation. V = (double)x + (double)y; x = 3; y = 5; u = x/y; /* u = 0.0, this is a common mistake */ v = (double)x / (double)y/* v = 0.6 */ Example

Northeastern University 11 Type Casting Syntax –(data_type) Identifier –data_type(Identifier) –static_cast (Identifier)

Northeastern University 12 if statement –Syntax: if (condition) statement ; –The statement following the condition is executed only when the condition is satisfied, e.g. : if (i == 0) cout << “i is zero”; if-else statement –Syntax: if (condition) statement1 ; else statement2 ;

Northeastern University 13 –If condition is satisfied, execute statement1, otherwise execute statement2. –Example: if (a > b) cout << “a is bigger than b.\n”; else cout << “a is not bigger than b.\n”; –We can use Boolean operators to set “compound conditions”, e.g.: validating the range of certain input a if (a 5) cout << “a is out of range.\n”; else cout << “You have entered ” << a << endl;

Northeastern University 14 Compound statement Sometimes a simple statement after the if test condition is not enough to accomplish our job. We can use compound statement to achieve more complicated tasks. –A compound statement is a sequence of statements enclosed in open and closed braces, e.g.: if (a > b) { c = a - b; cout << “a is bigger than b by ” << c << endl; } else cout << “a is smaller than or equal to b.\n”; –A compound statement defines a new level of variable scope. You can declare local variables for the compound statement within the braces.

Northeastern University 15 –Local variables in the compound statement are only visible by the compound statement. However, local variables in the same function are also visible to the compound statement. Example: int x, y; ……… if (T > 37.0) { double fah; fah = T* ; cout << “Patient is on fever. The equivalent body temperature in Farenheit is ” << fah << endl; } else { cout << “Body temperature is fine.\n”; discharge(); }

Northeastern University 16 –x and y are visible by the whole function. fah is only visible to the compound statement in which it is declared. Memory space for fah is allocated when the compound statement is reached and returned to the OS when the compound statement is finished. –Use indentation for compound statements to enhance readability. Indentation is for human readers only. The compiler only recognizes the braces, not the indentation. –The indentation format used in the examples is the AT&T Bell Lab’s programming style.

Northeastern University 17 Alternative to compound statement –Use a comma separated list of expressions. –The comma operator basically does nothing. Expressions separated by comma evaluates from left to right. –Not as clear and readable as compound statement. Example: if (a > b) c = a - b, a *= 2 Empty statement A single semicolon “;”. No operation. Mostly used in for loops. Example: if (a > b) ;

Northeastern University 18 More on C++ syntax and common mistakes Since C++ treats Boolean variables as integers and allows mixing of operators, it is easy to make some mistakes. –Do not confuse == (equality) with = (assignment) if (a == 5) statement; is interpreted as : (1) a == 5 evaluates to 1 if condition is satisfied, 0 otherwise. (2) if (1 /* non-zero */), statement is executed. if (a = 5) statement; is interpreted as : (1) 5 is assigned to variable a first (2) if (5 /* non-zero */), statement is executed (ALWAYS) –if (a != 0) can be written as if (a)

Northeastern University 19 –if (0 <= x <= 4) is syntactically correct but not always logically correct. Use associativity and precedence rules, the sequence of operations in the parenthesis is: (0 4, the final result must be 1 (TRUE). Correct expression: if (0 = 4) –The ! (NOT) operator has higher precedent than relational operators, so ! 4 > 5 is interpreted as (!4) > 5 which is 0 instead of ! (4 > 5) which is 1. –To represent both x and y are greater than z, write (x > z) && (y > z), NOT x && y > z which is actually x && (y > z) –Although the parentheses in (x > z) && (y > z) are not required, the expression is more readable if the parentheses are included.

Northeastern University 20 Logical assignments The expression following the assignment operator represents logic ideas. As we said, the logic variable is nothing but an integer variable or bool variable. Examples: even = n%2 == 0; is_letter = (‘A’ <= ch && ch <= ‘Z’) || (‘a’ <= ch && ch <= ‘z’); in_range = n > -10 && n < 10

Northeastern University 21 Nested if and multiple alternative decisions Sometimes, we need to make more than two decisions. Syntax: if (condition1) statement1; else if (condition2) statement2; …… else if (conditionN) statementN; else default_statement; One and only one statement will be executed. The last else and the default statement are optional.

Northeastern University 22 Example: Increment the counters num_pos, num_new or num_zero depending on the sign of the input value x. Implementation 1: if (x > 0) num_pos += 1; else if (x < 0) num_neg += 1; else /* x == 0 */ num_zero += 1; Implementation 2: if (x > 0) num_pos += 1; if ( x < 0) num_neg += 1; if (x == 0) num_zero += 1;

Northeastern University 23 Both implementations give the same result. Implementation 1 is clearer and more efficient. The three if conditions in implementation 2 are examined for every x. However, if x is positive, the other two else conditions are not examined. So the program runs faster. Use indentation properly to enhance readability. In nested if-else structure, the else statement always matches the last incomplete if statement regardless of indentation. Order of conditions can be important in certain situations.

Northeastern University 24 Example: if (income <= 15000) cout << “Lower class.\n”; else if (income <= 55000) cout << “Middle class.\n”; else /* income > */ cout << “Upper class.\n”; A guy with annual income $10000 will be classified as lower class by the above code. If we reorder the conditions: if (income <= 55000) cout << “Middle class.\n”; else if (income <= 15000) cout << “Lower class.\n”; else cout << “Upper class.\n”;

Northeastern University 25 –The second if is never used in the reordered code. The condition income <= is included in the condition income <= Only mutually exclusive conditions can be placed in arbitrary order. Example: Use compound statement to overwrite the default if-else paring. Consider the following code: a = 4; b = 4; if (a == 4) if (b == 4) cout << “Both a and b are 4.\n”; else cout << “a is not 4.\n”;

Northeastern University 26 In spite of the indentation, the else statement is associated with the second if. Therefore: a == 4 and b == 2  output: “a is not 4” a == 2 and b == 2  output: “no text” Correction 1: if (a == 4) { if (b == 4) cout << “Both a and b are 4.\n”; } else cout << “a is not 4.\n”;

Northeastern University 27 Correction 2: if (a == 4 && b == 4) cout << “Both a and b are 4.\n”; else if (a != 4) cout << “a is not 4.\n”; –Multiple decisions using the switch statement Useful when the selection is based on the value of a single variable or of a simple expression called the control expression Syntax: switch (expression) { /* usually a variable */ case label1: statement1; statement2; … break;

Northeastern University 28 case label2: statement1; statement2; … break; … case labelN: statement1; statement2; … break; default: statement1; statement2; … break;/* optional here */ }

Northeastern University 29 –When a match between the value of the control expression and the case label is found, the statements following the case label are executed until a break statement is found. The break keyword skips the rest of the switch options. –Omission of the break keyword before the next case label will cause the execution of the statements following the next case label. This is called execution fall through. It is a useful feature in C++ programming. Example: In this example, the user types in a character input. Different functions are called according to the input character. Functions e_mail(), news(), quit(), re_input() are defined somewhere in the program.

Northeastern University 30 Switch (input) { case ‘e’: case ‘E’; (); break; case ‘n’: case ‘N’: news(); break; case ‘q’: case ‘Q’: quit(); break; default: re_input(); }

Northeastern University 31 –Limitations: labels can only be integers or characters (i.e. something that can be evaluated to an integer). –The statements in the default sections are executed when there is no match with all the labels. Although the default section is optional, it is recommended that a default section is always included whenever possible. –Remember to put the break statement at the end of each alternative to prevent fall through. Conditional Operator ?: –Ternary operator with syntax: expression1 ? expression2 : expression3

Northeastern University 32 –Evaluates expression1 first. If it is non-zero (true), expression2 is evaluated and the result of expression2 is the value of the conditional expression as a whole. –If expression1 evaluates to zero (false), expression3 is evaluated. The result of expression3 is then the value of the whole conditional expression. Example: if (y < z) x = y; else x = z; can be equivalently written as: x = (y < z) ? : y : z;

Northeastern University 33 Homework Homework #1 –Page 105, #1 –Page 106, #6 Finish reading chapters 1 and 2