J. P. Cohoon and J. W. Davidson 1999 McGraw-Hill, Inc. Control Constructs. Mechanisms for deciding when and how often an action should be taken

Similar documents
Iterative Constructs

If Control Construct

Boolean Algebra Boolean Algebra

CS101 PLEDGED SPRING 2001

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.

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

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

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

C++ Final Exam 2017/2018

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

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

Increment and the While. Class 15

Why Is Repetition Needed?

CS 101 Computer Programming and utilization. Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

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

CS 105 Lecture 5 Logical Operators; Switch Statement. Wed, Feb 16, 2011, 5:11 pm

Chapter 4 - Notes Control Structures I (Selection)

CSI33 Data Structures

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

REPETITION CONTROL STRUCTURE LOGO

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Chapter 2: Overview of C++

Computer Programming. Basic Control Flow - Decisions. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Introduction to Programming

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Review. Relational Operators. The if Statement. CS 151 Review #4

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

5. Control Statements

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

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

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

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

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

The C++ Language. Arizona State University 1

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

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Summary of basic C++-commands

C++ Programming Lecture 1 Software Engineering Group

REVIEW. The C++ Programming Language. CS 151 Review #2

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

Lab Instructor : Jean Lai

Introduction to Programming using C++

To become familiar with array manipulation, searching, and sorting.

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

CSCI 1061U Programming Workshop 2. C++ Basics

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics

2 nd Week Lecture Notes

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

CSCE 110 PROGRAMMING FUNDAMENTALS

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

LECTURE 02 INTRODUCTION TO C++

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

5. Selection: If and Switch Controls

CHAPTER 3 BASIC INSTRUCTION OF C++

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

CS242 COMPUTER PROGRAMMING

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

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

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Lab 10: Alternate Controls

Introduction to Programming

The following expression causes a divide by zero error:

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

C++ For Science and Engineering Lecture 12

Chapter 2: Introduction to C++

Computer Programming : C++

conditional statements

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

1 Unit 8 'for' Loops

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

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

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

Lecture 5. Review from last week. Selection Statements. cin and cout directives escape sequences

VARIABLES & ASSIGNMENTS

1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions.

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Programming for Engineers Iteration

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection)

Chapter 10 - Notes Applications of Arrays

BITG 1113: Array (Part 1) LECTURE 8

Input And Output of C++

Your first C++ program

Transcription:

J. P. Cohoon and J. W. Davidson 1999 McGraw-Hill, Inc. Control Constructs Mechanisms for deciding when and how often an action should be taken

Ch 4 / Foil 2 Boolean Algebra Logical expressions have the one of two values - true or false A rectangle has three sides. The instructor has a pleasant smile The branch of mathematics that deals with this type of logic is called Boolean algebra Developed by the British mathematician George Boole in the 19th century Three key logical operators And Or Not

Ch 4 / Foil 3 Boolean Algebra Truth tables Lists all combinations of operand values and the result of the operation for each combination Example P Q P and Q False False False False True False True False False True True True

Ch 4 / Foil 4 Boolean Algebra Truth table for or P Q P or Q False False False False True True True False True True True True

Ch 4 / Foil 5 Boolean Algebra Truth table for not P False True Not P True False

Ch 4 / Foil 6 Boolean Algebra Can create complex logical expressions by combining simple logical expressions Example not (P and Q) A truth table can be used to determine when a logical expression is true P Q P and Q not (P and Q) False False False True False True False True True False False True True True True False

Ch 4 / Foil 7 A Boolean Type C++ contains a type named bool Type bool has two symbolic constants true false Boolean operators The and operator is && The or operator is The not operator is! Warning & and are also operators

Ch 4 / Foil 8 A Boolean Type Example logical expressions bool P = true; bool Q = false; bool R = true; bool S = P && Q; bool T =!Q R; bool U =!(R &&!Q);

Ch 4 / Foil 9 Relational Operators Equality operators ==!= Examples int i = 32; int k = 45; bool q = i == k; bool r = i!= k;

Ch 4 / Foil 10 Relational Operators Ordering operators < > >= <= Examples int i = 5; int k = 12; bool p = i < 10; bool q = k > i; bool r = i >= k; bool s = k <= 12;

Ch 4 / Foil 11 Operator Precedence Revisited Precedence of operators (from highest to lowest) Parentheses Unary operators Multiplicative operators Additive operators Relational ordering Relational equality Logical and Logical or Assignment

Ch 4 / Foil 12 Operator Precedence Revisited Examples 5!= 6 7 <= 3 (5!=6) (7 <= 3) 5 * 15 + 4 == 13 && 12 < 19!false == 5 < 24

Ch 4 / Foil 13 Conditional Constructs Provide Ability to control whether a statement list is executed Two constructs If statement If If-else If-else-if Switch statement

Ch 4 / Foil 14 The Basic If Statement Syntax if (Expression) Action If the Expression is true then execute Action Action is either a single statement or a group of statements within braces Example if (Value < 0) { Value = -Value; Expression true Action false

Ch 4 / Foil 15 Sorting Two Numbers cout << "Enter two integers: "; int Value1; int Value2; cin >> Value1 >> Value2; if (Value1 > Value2) { int RememberValue1 = Value1; Value1 = Value2; Value2 = RememberValue1; cout << "The input in sorted order: " << Value1 << " " << Value2 << endl;

Ch 4 / Foil 16 The If-Else Statement Syntax if (Expression) Action 1 else Action 2 If Expression is true then execute Action 1 otherwise execute Action 2 if (v == 0) { cout << "v is 0"; else { cout << "v is not 0"; Expression true false Action 1 Action 2

Ch 4 / Foil 17 Finding the Larger of Two Values cout << "Enter two integers: "; int Value1; int Value2; cin >> Value1 >> Value2; int Larger; if (Value1 < Value2) { Larger = Value1; else { Larger = Value2; cout << "Larger of inputs is: " Larger << endl;

Ch 4 / Foil 18 Selection It is often the case that depending upon the value of an expression we want to perform a particular action Two major ways of accomplishing of this choice If-else-If statement If-else statements glued together Switch statement An advanced construct

Ch 4 / Foil 19 The If-Else-If Statement Example if ((ch == 'a') (ch == 'A")) cout << ch << " is a vowel" << endl; else if ((ch == 'e') (ch == 'E")) cout << " ch << " is a vowel" << endl; else if ((ch == 'i') (ch == 'I")) cout << ch << " is a vowel" << endl; else if ((ch == 'o') (ch == 'O")) cout << ch << " is a vowel" << endl; else if ((ch == 'u') (ch == 'U")) cout << ch << " is a vowel" << endl; else cout << ch << " is not a vowel" << endl;

Ch 4 / Foil 20 Switch Statement switch (ch) { case 'a': case 'A": case 'e': case 'E": case 'i': case 'I": case 'o': case 'O": case 'u': case 'U": cout << ch << " is a vowel" << endl; break; default: cout << ch << " is not a vowel" << endl;

cout << "Enter simple expression: "; int Left; int Right; char Operator; cin >> Left >> Operator >> Right; cout << Left << " " << Operator << " " << Right << " = "; switch (Operator) { case '+' : cout << Left + Right << endl; break; case '-' : cout << Left - Right << endl; break; case '*' : cout << Left * Right << endl; break; case '/' : cout << Left / Right << endl; break; default: cout << "Illegal operation" << endl;

Ch 4 / Foil 22 Iterative Constructs Provide Ability to control how many times a statement list is executed Three constructs while statement for statement do-while statement

Ch 4 / Foil 23 The While Statement Syntax while (Expression) Semantics Action If Expression is true then execute Action Repeat this process until Expression evaluates to false Action is either a single statement or a group of statements within braces Expression true Action false

Ch 4 / Foil 24 Power of Two Table const int TableSize = 20; int i = 0; long Value = 1; cout << "i" << "\t\t" << "2 ** i" << endl; while (i <= TableSize) { cout << i << "\t\t" << Value << endl; Value *= 2; ++i;

Ch 4 / Foil 25 Character Counting int NumberOfNonBlanks = 0; int NumberOfUpperCase = 0; char c; while (cin >> c) { ++NumberOfNonBlanks; if ((c >= 'A') && (c <= 'Z')) { ++NumberOfUpperCase;

Ch 4 / Foil 26 Counting Characters char c; int NumberOfCharacters = 0; int NumberOfLines = 0; while (cin.get(c)) { ++NumberOfCharacters; if (c == '\n') ++NumberOfLines cout << "Characters: " << NumberOfCharacters << endl; cout << "Lines: " << NumberOfLines << endl;

int main() { cout << "Provide a list of numbers" << endl; int ListSize = 0; float ValueSum = 0; int Value; while (cin >> Value) { ValueSum += Value; ++ListSize; if (ListSize > 0) { float Average = ValueSum / ListSize; cout << "Average: " << Average << endl; else { cout << "No list to average" << endl; return 0; Ch 4/ Foil 27 The value of the input operation corresponds to true only if a successful extraction was made

Ch 4 / Foil 28 The For Statement Syntax for (ForInit ; ForExpression; PostExpression) Action Semantics Execute ForInit statement While ForExpression is true Execute Action Execute PostExpression Example for (int i = 0; i < 20; ++i) { cout << "i is " << i << endl;

Ch 4 / Foil 29 Iteration Using the For Statement ForInit ForExpression true false Action PostExpression

Ch 4 / Foil 30 Table Revisiting const int TableSize = 20; long Value = 1; cout << "i" << "\t\t" << "2**i" << endl; for (int i = 0; i <= TableSize; ++i) { cout << i << "\t\t" << Value << endl; Value *= 2; The scope of i is limited to the loop!

Ch 4 / Foil 31 Displaying A Diagonal SimpleWindow W("One diagonal", 5.5, 2.25); W.Open(); for (int j = 1; j <= 3; ++j) { float x = j * 0.75 + 0.25; float y = j * 0.75-0.25; float Side = 0.4; RectangleShape S(W, x, y, Blue, Side, Side); S.Draw();

Ch 4 / Foil 32 Sample Display

Ch 4 / Foil 33 Displaying Three Diagonals SimpleWindow W("Three diagonals", 6.5, 2.25); W.Open(); for (int i = 1; i <= 3; ++i) { for (int j = 1; j <= 3; ++j) { float x = i - 1 + j * 0.75 + 0.25; float y = j * 0.75-0.25; float Side = 0.4; RectangleShape S(W, x, y, Blue, Side, Side); S.Draw(); The scope of i includes the inner loop. The scope of j is just the inner loop.

Ch 4 / Foil 34 Sample Display

int Counter1 = 0; int Counter2 = 0; int Counter3 = 0; int Counter4 = 0; int Counter5 = 0; ++Counter1; for (int i = 1; i <= 10; ++i) { ++Counter2; for (int j = 1; j <= 20; ++j) { ++Counter3; ++Counter4; ++Counter5; cout << Counter1 << " " << Counter2 << " " << Counter3 << " " Counter4 << " " Counter5 << endl; Ch 4/ Foil 35

Ch 4 / Foil 36 For Into While Observation The for statement is equivalent to { ForInit; while (ForExpression) { Action; PostExpression;

Ch 4 / Foil 37 Iteration Key Points Make sure there is a statement that will eventually nullify the iteration criterion (i.e., the loop must stop) Make sure that initialization of any loop counters or iterators is properly performed Have a clear purpose for the loop Document the purpose of the loop and how the body of the loop advances the purpose of the loop

Ch 4 / Foil 38 Riddle Four hobos traveling across the country in need of money Farmer offers 200 hours of work that could be done over the next couple of weeks The laziest hobo convinces the other three hobos to draw straws Each straw would be marked with an amount The amount would represent both the number of days and the numbers of hours per day that the hobo would work Example If the straw was marked three then the hobo who drew it would work for three hours per day for three days What are the best markings of the straws for a clever, lazy hobo?

Ch 4 / Foil 39 Observations Need to find sets of whole numbers a, b, c, and d such that a 2 +b 2 +c 2 +d 2 =200 Maximal legal number is 14 as 15 2 equals 225 which is greater than 200 Minimal legal number is 1 No advantage to listing the combinations more than once Implication Generate the solutions systematically We will make sure that a <= b <= c <= d

Ch 4 / Foil 40 Method Generate all possibilities for a where for each a possibility Generate all possibilities of b where for each b possibility Generate all possibilities for c where for each c possibility Generate all possibilities for d where for each d possibility Determine whether the current combination is a solution

Ch 4 / Foil 41 Nested For Loop Solution for (int a = 1; a <= 14; ++a) { for (int b = a; b <= 14; ++b) { for (int c = b; c <= 14; ++c) { for (int d = c; (d <= 14); ++d) { if (a*a + b*b + c*c + d*d == 200) { cout << a << " " << b << " " << c << " " << d << endl;

Ch 4 / Foil 42 Simple Visualization What statements can we make about the following data set? 4.90 2.41 0.82 0.77 2.60 5.10 7.52 9.45 9.65 7.81 5.04 2.51 0.95 0.80 2.62 Statistical analysis analysis indicates that observations come from interval 0 10 with an average value of 4.97 and a standard deviation of 2.95 Another approach is to detect whether the sequence of observations represents a patter Are the numbers arranged for example in Fibonacci order? If no patterns are recognized, try data visualization Plot the data set values in a two-dimensional manner y-axis correspond to data set values x-axis correspond to positions in the data set sequence

#include <iostream> // Program 4.12 #include <string> #include "rect.h" using namespace std; int ApiMain() { const float Unit = 0.25; cout << "Enter size of data set: "; int n; cin >> n; SimpleWindow W("Data set display", n+2, 10); W.Open(); for (float x = 1; x <= n; ++x) { cout << "Enter data value (n): "; float y; cin >> y; RectangleShape Point(W, x, y, Blue, Unit, Unit); Point.Draw(); return 0;

Ch 4 / Foil 44 Sample Run Data values do have structure

Ch 4 / Foil 45 The Do-While Statement Syntax do Action while (Expression) Semantics Execute Action if Expression is true then execute Action again Repeat this process until Expression evaluates to false Action is either a single statement or a group of statements within braces Action Expression false true

Ch 4 / Foil 46 Waiting for a Proper Reply char Reply; do { cout << "Decision (y, n): "; if (cin >> Reply) Reply = tolower(reply); else Reply = 'n'; while ((Reply!= 'y') && (Reply!= 'n'));