Chapter 7. Additional Control Structures

Similar documents
Test Results Schedule Miscellanea Control Structs. Add l Oper s Break Hands on Q & A Conclusion References Files

CHAPTER 3 Expressions, Functions, Output

Chapter 2: Basic Elements of C++

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

UNIT- 3 Introduction to C++

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Chapter 2 Basic Elements of C++

Lecture 3 Tao Wang 1

C++ Programming: From Problem Analysis to Program Design, Third Edition

1. In C++, reserved words are the same as predefined identifiers. a. True

Review of the C Programming Language for Principles of Operating Systems

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Definition: Data Type A data type is a collection of values and the definition of one or more operations on those values.

C Programming Language (Chapter 2 of K&R) Variables and Constants

Data Types and Variables in C language

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Objectives. In this chapter, you will:

Introduction to Programming

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

Chapter 3. Numeric Types, Expressions, and Output

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Review of the C Programming Language

Assignment: 1. (Unit-1 Flowchart and Algorithm)

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Reserved Words and Identifiers

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Full file at

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Operators and Expressions:

CS2141 Software Development using C/C++ C++ Basics

Arithmetic Operators. Portability: Printing Numbers

Operators in java Operator operands.

A flow chart is a graphical or symbolic representation of a process.

Internet & World Wide Web How to Program, 5/e by Pearson Education, Inc. All Rights Reserved.

CS313D: ADVANCED PROGRAMMING LANGUAGE

CSCI 1061U Programming Workshop 2. C++ Basics

Introduction to Programming EC-105. Lecture 2

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

BITG 1233: Introduction to C++

Java Notes. 10th ICSE. Saravanan Ganesh

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

3. Java - Language Constructs I

CSI33 Data Structures

The C++ Language. Arizona State University 1

C++ Final Exam 2017/2018

Increment and the While. Class 15

Introduction. C provides two styles of flow control:

CSc 10200! Introduction to Computing. Lecture 4-5 Edgardo Molina Fall 2013 City College of New York

.Net Technologies. Components of.net Framework

More Programming Constructs -- Introduction

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Informatics Ingeniería en Electrónica y Automática Industrial

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

C++ Programming: From Problem Analysis to Program Design, Third Edition

Operators in C. Staff Incharge: S.Sasirekha

Declaration and Memory

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Example of Objective Test Questions for Test 4

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

CHAPTER 3 BASIC INSTRUCTION OF C++

Chapter 3: Operators, Expressions and Type Conversion

Programming for Engineers Iteration

LECTURE 3 C++ Basics Part 2

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

I Internal Examination Sept Class: - BCA I Subject: - Principles of Programming Lang. (BCA 104) MM: 40 Set: A Time: 1 ½ Hrs.

REPETITION CONTROL STRUCTURE LOGO

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Programming with C++ as a Second Language

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Java enum, casts, and others (Select portions of Chapters 4 & 5)

Operators and Type Conversion. By Avani M. Sakhapara Assistant Professor, IT Dept, KJSCE

Fundamentals of Programming CS-110. Lecture 2

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Engineering Computing I

Chapter 2: Introduction to C++

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Programming. C++ Basics

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

CSE 452: Programming Languages. Outline of Today s Lecture. Expressions. Expressions and Control Flow

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Type Conversion. and. Statements

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS242 COMPUTER PROGRAMMING

C: How to Program. Week /Mar/05

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

Transcription:

Chapter 7 Additional Control Structures 1

Chapter 7 Topics Switch Statement for Multi-Way Branching Do-While Statement for Looping For Statement for Looping Using break and continue Statements 2

Chapter 7 Topics Additional C++ Operators Operator Precedence Type Coercion in Arithmetic and Relational Precedence 3

Switch Statement The Switch statement is a selection control structure for multi-way branching switch (IntegralExpression) { case Constant1 : Statement(s); case Constant2 : }... Statement(s); default : Statement(s); // optional // optional // optional // optional 4

Example of Switch Statement float weightinpounds = 165.8; char weightunit;... // User enters letter for desired weightunit switch (weightunit) { case P : case p : << endl; break; case O : case o : cout << weightinpounds << pounds cout << 16.0 * weightinpounds << 5 ounces << endl;

Example of Switch Statement, continued break; case G : case g : cout << 454.0 * weightinpounds << grams << endl; break; default : cout << That unit is not handled! << endl; break; } 6

Switch Statement The value of IntegralExpression (of char, short, int, long or enum type) determines which branch is executed Case labels are constant (possibly named) integral expressions Several case labels can precede a statement 7

Control in Switch Statement Control branches to the statement following the case label that matches the value of IntegralExpression Control proceeds through all remaining statements, including the default, unless redirected with break 8

Control in Switch Statement If no case label matches the value of IntegralExpression, control branches to the default label, if present Otherwise control passes to the statement following the entire switch statement Forgetting to use break can cause logical errors because after a branch is taken, control proceeds sequentially until either break or the end of the switch statement occurs 9

Do-While Statement Do-While is a looping control structure in which the loop condition is tested after each iteration of the loop SYNTAX do { Statement } while (Expression); Loop body statement can be a single statement or a block 10

Example of Do-While void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response has been input // && response == y or n { do { cin >> response; // Skips leading whitespace if ((response!= y ) && (response!= n )) 11

Do-While Loop vs. While Loop POST-TEST loop (exit-condition) The looping condition is tested after executing the loop body Loop body is always executed at least once PRE-TEST loop (entry-condition) The looping condition is tested before executing the loop body Loop body may not be executed at all 12

Do-While Loop DO Statement WHILE Expression FALSE TRUE When the expression is tested and found to be false, the loop is exited and control passes to the statement that follows the Do-while statement 13

For Loop SYNTAX for (initialization; test expression; update) { Zero or more statements to repeat } 14

For Loop For loop contains An initialization An expression to test for continuing An update to execute after each iteration of the body 15

Example of For Loop int num; for (num = 1; num <= 3; num++) { cout << num << Potato << endl; } 16

num? Example of Repetition int num; for (num = 1; num <= 3; num++) cout << num << Potato << endl; OUTPUT 17

num 1 Example of Repetition int num; for (num = 1; num <= 3; num++) cout << num << Potato << endl; OUTPUT 18

num 1 int num; Example of Repetition true for(num = 1; num <= 3; num++) cout << num << Potato << endl; OUTPUT 19

num 1 Example of Repetition int num; for (num = 1; num <= 3; num++) cout << num << Potato << endl; 1Potato OUTPUT 20

num 2 Example of Repetition int num; for (num = 1; num <= 3; num++) cout << num << Potato << endl; 1Potato OUTPUT 21

num 2 Example of Repetition int num; true for(num = 1; num <= 3; num++) cout << num << Potato << endl; 1Potato OUTPUT 22

2 Example of Repetition num int num; for (num = 1; num <= 3; num++) cout << num << Potato << endl; OUTPUT 1Potato 2Potato 23

num 3 Example of Repetition int num; for (num = 1; num <= 3; num++) cout << num << Potato << endl; 1Potato 2Potato OUTPUT 24

num 3 int num; Example of Repetition true for(num = 1; num <= 3; num++) cout << num << Potato << endl; 1Potato 2Potato OUTPUT 25

num 3 Example of Repetition int num; for(num = 1; num <= 3; num++) cout << num << Potato << endl; 1Potato 2Potato OUTPUT 3Potato 26

num 4 Example of Repetition int num; for (num = 1; num <= 3; num++) cout << num << Potato << endl; 1Potato 2Potato OUTPUT 3Potato 27

num 4 int num; Example of Repetition false for(num = 1; num <= 3; num++) cout << num << Potato << endl; 1Potato 2Potato OUTPUT 3Potato 28

num 4 Example of Repetition int num; false for(num = 1; num <= 3; num++) cout << num << Potato << endl; When the loop control condition is evaluated and has value false, the loop is said to be satisfied and control passes to the statement following the For statement 29

Output The output was 1Potato 2Potato 3Potato 30

int count; Count-controlled Loop for (count = 4; count > 0; count--) { cout << count << endl; } cout << Done << endl; OUTPUT: 4 3 2 1 Done 31

What is output? int count; for (count = 0; count < 10; count++) { cout << * ; } 32

Answer ********** The 10 asterisks are all on one line. Why? 33

What output from this loop? int count; for (count = 0; count < 10; count+ +); { } cout << * ; 34

Answer No output from the for loop! Why? The semicolon after the () means that the body statement is a null statement 35

Answer In general, the body of the For loop is whatever statement immediately follows the () That statement can be a single statement, a block, or a null statement Actually, the code outputs one * after the loop completes counting to 10 36

Several Statements in Body Block const int MONTHS = 12; int float count; bill; float sum = 0.0; for (count = 1; count <= MONTHS; count++) { } cout << Enter bill: ; cin >> bill; sum = sum + bill; cout << Your total bill is : << sum << endl; 37

Break Statement The Break statement can be used with Switch or any of the 3 looping structures It causes an immediate exit from the Switch, While, Do-While, or For statement in which it appears If the Break statement is inside nested structures, control exits only the innermost structure containing it 38

Guidelines for Choosing Looping Statement For a simple count-controlled loop, use the For statement For an event-controlled loop whose body always executes once, use of Do-While statement For an event-controlled loop about which nothing is known, use a While statement When in doubt, use a While statement 39

Continue Statement The Continue statement is valid only within loops It terminates the current loop iteration, but not the entire loop In a For or While, Continue causes the rest of the body of the statement to be skipped; in a For statement, the update is done In a Do-While, the exit condition is tested, and if true, the next loop iteration is begun 40

Problem Given a character, a length, and a width, draw a box For example, given the values &, 4, and 6, you would display &&&&&& &&&&&& &&&&&& &&&&&& 41

Additional C++ Operators Previously discussed C++ Operators include: the assignment operator (=) the arithmetic operators (+, -, *, /, %) relational operators (==,!=,,<=, >, >=) logical operators (!, &&, ) C++ has many specialized other operators seldom found in other programming languages 42

Additional C++ Operators See Table in 7.6 in Text for Additional C++ Operators for a full list of: Combined Assignment Operators Increment and Decrement Operators Bitwise Operators More Combined Assignment Operators Other Operators 43

Assignment Operators and Assignment Expressions (=) is the basic assignment operator Every assignment expression has a value and a side effect, the value that is stored into the object denoted by the left-hand side For example, delta = 2 * 12 has the value 24 and side effect of storing 24 into delta 44

Assignment Expressions In C ++, any expression become an expression statement when terminated by a semicolon The following are all valid C++ statements, first 2 have no effect at run time: 23; 2 * (alpha + beta); delta = 2 * 12; 45

Increment and Decrement Operators The increment and decrement operators (+ + and --) operate only on variables, not on constants or arbitrary expressions 1) Example of pre-incrementation int1 = 14; int2 = ++int1; // int1 == 15 && int2 == 15 2) Example of post-incrementation int1 = 14; int2 = int1++; // int1 == 15 && int2 == 14 46

Bitwise Operators Bitwise operators (e.g., <<, >>, and ) are used for manipulating individual bits within a memory cell << and >> are left and right shift operators, respectively that take bits within a memory cell and shift them to the left or the right Do not confuse relational && and operators used in logical expressions with & and bitwise operators 47

The Cast Operation Explicit type cast used to show that the type conversion is intentional In C++, the cast operation comes in three forms: intvar = int(floatvar); // Functional notation intvar = (int)floatvar; // Prefix notation intvar = static_cast<int>(floatvar); // Keyword notation 48

The Cast Operation Restriction on use of functional notation: Data type name must be a single identifier If type name consists of more than one identifier, prefix notation or keyword notation must be used Most software engineers now recommend use of keyword cast because it is easier to find these keywords in a large program 49

The sizeof Operator The sizeof operator --a unary operator that yields the size, in bytes, of its operand The operand can be a variable name, as in sizeof someint Alternatively, the operand can be the name of a data type enclosed in parentheses: (sizeof float) 50

The? Operator? : operator, also called the conditional operator is a three-operand operator Example of its use: set a variable m ax equal to the larger of two variables a and b. With the?:operator, you can use the following assignment statement: m ax = (a>b)? a :b; 51

Operator Precedence Following Table on slide 53 and slide 54 groups discussed operators by precedence levels for C++ Horizontal line separates each precedence level from the next-lower level Column level Associativity describes grouping order. Within a precedence level, operators group Left to right or, Right to left 52

Operator Associativity Remarks Function call and functionstyle cast () ++ Left to right -- Right to left ++and - as postfix operators ++ --! Unary +Unary (cast) sizeof Right to left Right to left * / % Left to right + - Left to right ++and - as prefix operators 53

Operator Associativity Remarks < <= > >= ==!= &&?: = += -= *= /= Left to right Left to right Left to right Left to right Right to left Right to left 54

Type Coercion in Arithmetic and Relational Expressions If two operands are of different types, one of them is temporarily promoted (or widened) to match the data type of the other Rule of type coercion in an arithmetic coercion: Step 1: Each char, short, bool, or enumeration value is promoted (widened) to int. If both operands are now int, the result is an int expression. 55

Type Coercion in Arithmetic and Relational Expressions Step 2: If Step 1 still leaves a mixed type expression, the following precedence of types is used: int, unsigned int, long, float, double,long double 56

Type Coercion in Arithmetic and Relational Expressions Example: expression som efloat+2 Step 1 leaves a mixed type expression In Step 2, int is a lower type than the float value---for example, 2.0 Then the addition takes place, and the type of the entire expression is float 57

Type Coercion in Arithmetic and Relational Expressions This description also holds for relational expressions such as som eint <= som efloat Value of som eint temporarily coerced to floatingpoint representation before the comparison occurs Only difference between arithmetic and relational expressions: Resulting type of relational expression is always bool---the value true or false 58