Chapter 7 Additional Control Structures. Chapter 7 Topics l Switch Statement for Multi-Way Branching l Do-While Statement for Looping l For Statement.

Slides:



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

Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Chapter 5: Loops and Files.
1 Chapter 7 Additional Control Structures. 2 Knowledge Goals Understand the role of the switch statement Understand the purpose of the break statement.
1 Lecture 14 Chapter 6 Looping Dale/Weems/Headington.
Multi-alternative Selection Both the if clause and the else clause of an if...else statement can contain any kind of statement, including another selection.
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
The switch Statement, DecimalFormat, and Introduction to Looping
Basic Elements of C++ Chapter 2.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Introduction to Java and Software Design Dale Weems Headington Chapter 10 Additional Control Structures and Exceptions Slides by Sylvia Sorkin, The Community.
1 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Switch Statement Is a selection control structure for multi-way branching. SYNTAX switch ( IntegralExpression ) { case Constant1 : Statement(s); // optional.
1 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX do { Statement } while.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Chapter 05 (Part III) Control Statements: Part II.
Control Structures Repetition or Iteration or Looping Part II.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
Additional C++ Operators ROBERT REAVES. Choosing a Looping Statement  Count-controlled loop, use for loop.  Event-controlled loop whose body should.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
1 do-while Statement 2 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
1 1 Additional Control Structures Chapter 9 2 New and Improved... Ways to branch Ways to write loops Understanding the break and continue statements.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 4 – C Program Control
The switch Statement, and Introduction to Looping
Control Structures - Repetition
Chapter 8 JavaScript: Control Statements, Part 2
Additional Control Structures
Chapter 7 Additional Control Structures
Chapter 4: Control Structures I (Selection)
Control Statements Paritosh Srivastava.
Chap 7. Advanced Control Statements in Java
Presentation transcript:

Chapter 7 Additional Control Structures

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

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

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

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

Example of Switch Statement, continued break; case ‘G’ : case ‘g’ : cout << * weightInPounds << “ grams “ << endl; break; default : cout << “That unit is not handled! “ << endl; break; }

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

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

Control in Switch Statement l If no case label matches the value of IntegralExpression, control branches to the default label, if present l Otherwise control passes to the statement following the entire switch statement l 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

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

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’)) cout << “Please type y or n : “; } while ((response != ‘y’) && (response != ‘n’)); } Example of Do-While

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

Do-While Loop 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 Statement Expression DO WHILE FALSE TRUE

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 false int num; for (num = 1; num <= 3; num++) cout << num << “Potato” << endl; Example of Repetition num 4

Output The output was 1Potato 2Potato 3Potato

int count; for (count = 4; count > 0; count--) { cout << count << endl; } cout << “Done” << endl; OUTPUT: Done Count-controlled Loop

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

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

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

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

l In general, the body of the For loop is whatever statement immediately follows the () l 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

Several Statements in Body Block const int MONTHS = 12; int count; float 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;

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

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

Continue Statement l The Continue statement is valid only within loops l It terminates the current loop iteration, but not the entire loop l 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 l In a Do-While, the exit condition is tested, and if true, the next loop iteration is begun

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

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

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

Assignment Operators and Assignment Expressions l (=) is the basic assignment operator l 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

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

Increment and Decrement Operators l 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

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

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

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

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)

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

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

Type Coercion in Arithmetic and Relational Expressions l If two operands are of different types, one of them is temporarily promoted (or widened) to match the data type of the other l 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.

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

Type Coercion in Arithmetic and Relational Expressions Example: expression someFloat+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

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