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

Similar documents
while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

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

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

Looping. Arizona State University 1

REPETITION CONTROL STRUCTURE LOGO

Chapter 5: Loops and Files

Programming for Engineers Iteration

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Lecture 7 Tao Wang 1

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

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

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

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

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

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

Increment and the While. Class 15

Repetition Structures

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

Repetition and Loop Statements Chapter 5

5. Selection: If and Switch Controls

Chapter 4: Control structures. Repetition

LECTURE 5 Control Structures Part 2

C++ Final Exam 2017/2018

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

Chapter 4: Control structures

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Logical Operators and if/else statement. If Statement. If/Else (4.3)

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

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

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

Why Is Repetition Needed?

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

C/C++ Programming Lecture 7 Name:

Quiz Determine the output of the following program:

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

LECTURE 04 MAKING DECISIONS

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

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

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

Loops and Files. of do-while loop

Add Subtract Multiply Divide

Dept. of CSE, IIT KGP

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.

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

CHAPTER : 9 FLOW OF CONTROL

Chapter 2 - Control Structures

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

Chapter 2 - Control Structures

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

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

Chapter 4: Making Decisions

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

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Score score < score < score < 65 Score < 50

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

Chapter 4: Making Decisions

Control Structures. Repetition (Loop) Structure. Repetition (Loop) Structure. Repetition (Loop) Structure. CS225: Slide Set 8: C++ Loop Structure

Chapter 2 - Control Structures

Chapter 5: Control Structures II (Repetition)

n Group of statements that are executed repeatedly while some condition remains true

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

Chapter 4 - Notes Control Structures I (Selection)

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

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

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

Computer Programming

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

CS110D: PROGRAMMING LANGUAGE I

CSI33 Data Structures

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

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

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

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Chapter 5 : Repetition (pp )

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

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

A Look Back at Arithmetic Operators: the Increment and Decrement

Iteration. CSE / ENGR 142 Programming I. while loops. Chapter 5. Motivating Loops. Loop to Add 5 Numbers 1996 UW CSE H - 1

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

Chapter 3 Problem Solving and the Computer

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

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

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

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

do { statements } while (condition);

Name Section: M/W T/TH Number Definition Matching (8 Points)

CSCE 206: Structured Programming in C++

204111: Computer and Programming

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

Introduction. C provides two styles of flow control:

Chapter 7. Additional Control Structures

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

بسم اهلل الرمحن الرحيم

Example. CS 201 Selection Structures (2) and Repetition. Nested if Statements with More Than One Variable

Repetition CSC 121 Fall 2014 Howard Rosenthal

Transcription:

Week 2 Branching & Looping Gaddis: Chapters 4 & 5 CS 5301 Spring 2018 Jill Seaman 1 Relational Operators l relational operators (result is bool): == Equal to (do not use =)!= Not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to l operator precedence: * / % + - < > <= >= ==!= = int x, y;... x < y -10...... x * 5 >= y + 10 int x=90; int n=6; 7 < 25 89 == x x % 2!= 0 8 + 5 * 10 <=10 * n Which operation happens first? next? bool t1 = x > 7; bool t2 = x * 5 >= y + 10; 2 l if and l l if/ if expression is true, 1 is executed if expression is false, 2 is executed l the is optional: l if (expression) 1 2 double rate, monthlysales;... if (monthlysales > 3000) rate =.025; rate =.029; if (expression) if expression is true, is executed, 3 otherwise is skipped Block or compound l a set of s inside braces: int x; cout << Enter a value for x: << endl; cin >> x; l This allows us to use multiple s when by rule only one is allowed. int number; cout << Enter a number << endl; cin >> number; if (number % 2 == 0) number = number / 2; cout << 0 ; number = (number + 1) / 2; cout << 1 ; 4

Nested if/ l if- is a. It can occur as a inside of another if-. Nested if/ l if- is a. It can occur as a inside of another if-. if (score >= 80) if (score >= 70) if (score >= 60) l The braces are optional on this side This is equivalent to the code on the left. It is just formatted differently if (score >= 80) if (score >= 70) if (score >= 60) 5 if (score >= 80) if (score >= 70) if (score >= 60) If we are in this branch, what do we know about the value of score? This is equivalent to the code on the left. It is just formatted differently if (score >= 80) if (score >= 70) if (score >= 60) 6 Nested if/ l Here is a flowchart indicating the flow of control during execution of the nested if on the previous slide: Notice you don t need to add && score < 90 here. Logical Operators l logical operators (values and results are bool):! not && and or!a a && b a b is true when a is false is true when both a and b are true is true when either a or b is true 7 l operator precedence: l examples T/F?: int x=6; int y=10; a. x == 5 && y <= 3 b. x > 0 && x < 10 c. x == 10 y == 10 d. x == 10 x == 11 e.!(x > 0) f.!(x > 6 y == 10)! * / % + - < > <= >= ==!= && 8

l switch stmt: switch switch (expression) case constant: s... case constant: s default: s - execution starts at the case labeled with the value of the expression. - if no match, start at default - use break to exit switch (usually at end of s) l example: switch (ch) case a : case A : cout << Option A ; break; case b : case B : cout << Option B ; break; default: cout << Invalid choice ; 9 Input Validation l Input validation: inspecting input data to determine whether it is acceptable l Invalid input is an error that should be treated as an exceptional case. The program can ask the user to re-enter the data The program can exit with an error message cout << Enter a score between 0 and 100: ; cin >> score; if (score < 0 score > 100) cout << "That is an invalid score. << endl; //do something with score here 10 More assignment s l Compound assignment operator usage equivalent syntax: += x += e; x = x + e; -= x -= e; x = x - e; *= x *= e; x = x * e; /= x /= e; x = x / e; l increment, decrement operator usage equivalent syntax: ++ x++; ++x; x = x + 1; -- x--; --x; x = x - 1; 11 l while while loops if expression is true, is executed, repeat l Example: l output: while (expression) may be a compound (a block: s) int number; cout << Enter a number, 0 when finished: ; cin << number; while (number!= 0) cout << You entered << number << endl; cout << Enter the next number: ; cin >> number; cout << Done << endl; Enter a number, 0 when finished: 22 You entered 22 Enter the next number: 5 You entered 5 Enter the next number: 0 Done 12

two kinds of loops l conditional loop execute as long as a certain condition is true l count-controlled loop: executes a specific number of times - initialize counter to zero (or other start value). - test counter to make sure it is less than count. - update counter during each iteration. l for: for loops for (expr1; expr2; expr3) equivalent to: l Good for implementing count-controlled loops: pattern: for (initialize; test; update) expr1; while (expr2) expr3; may be a compound (a block: s) int number = 1; while (number <= 3) cout << Student << number << endl; number = number + 1; // or use number++ cout << Done << endl; number is a counter, it keeps track of the number of times the loop has executed. 13 for (int number = 1; number <= 3; number++) cout << Student << number << endl; cout << Done << endl; 14 l do while: do-while loops do while (expression); is executed. if expression is true, then repeat may be a compound (a block: s) l The test is at the end, ALWAYS executes at least once. int number; do cout << Enter a number, 0 when finished: ; cin << number; cout << You entered << number << endl; while (number!= 0); Keeping a running total (summing) l Example: int days; float total = 0.0; //Accumulator cout << How many days did you ride your bike? ; cin >> days; for (int i = 1; i <= days; i++) float miles; cout << Enter the miles for day << i << : ; cin >> miles; total = total + miles; cout << Total miles ridden: << total << endl; 15 16

Sentinel controlled loop l A sentinel controlled loop continues to process data until reaching a special value (called the sentinel) that signals the end. get the first data item while item is not the sentinel process the item get the next data item l The first item is retrieved before the loop starts. This is called the priming read, since it gets the process started. l If the first item is the sentinel, the loop terminates and no data is processed. 17 Sentinel controlled loop l Example: summing using a sentinel float total = 0.0; //Accumulator float miles; cout << "Enter the miles you rode (-1 to quit): "; cin >> miles; while (miles!= -1) total = total + miles; cout << "Enter the miles you rode (-1 to quit): "; cin >> miles; cout << "Total miles ridden: " << total << endl; 18 Nested loops l When one loop appears in the body of another l For every iteration of the outer loop, we do all the iterations of the inner loop for (row=1; row<=3; row++) //outer for (col=1; col<=3; col++) //inner cout << row * col << ; cout << endl; Output: 1 2 3 2 4 6 3 6 9 19 continue and break Statements l Use break to terminate execution of a loop l When used in a nested loop, terminates the inner loop only. l Use continue to go to end of current loop and prepare for next repetition l while, do-while loops: go immediately to the test, repeat loop if test passes l for loop: immediately perform update step, then test, then repeat loop if test passes 20

Example problem: Future Value l Money deposited in a bank account earns interest annually. How much will the account be worth 10 years from now? l Inputs: the principal, annual interest rate l Output: value of the investment in 10 years l Relationship between Inputs and Outputs: Value after one year is given by this formula: principal * (1 + apr). This needs to be done 10 times. Example problem: Future Value l Design: Print an introduction Input the amount of the principal (principal) Input the annual percentage rate (apr) Repeat 10 times: principal = principal * (1 + apr) Output the value of principal 21 22 Example problem: Future Value l Code: int main() cout << fixed << setprecision(2); double principal, apr; //Print an introduction cout <<"This program calculates the future "; cout <<"value of a 10-year investment." << endl; //Input the amount of the principal (principal) cout << "Enter the initial principal: "; cin >> principal; //Input the annual percentage rate (apr) cout << "Enter the annual interest rate: "; cin >> apr; //Repeat 10 times: for (int i=1; i<=10; i++) //principal = principal * (1 + apr) principal = principal * (1 + apr); //Output the value of principal cout << "The value in 10 years is: " << principal << endl; 23