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

Similar documents
Introduction to C Programming

Chapter 2 - Control Structures

Chapter 2 - Control Structures

Chapter 2 - Control Structures

2.11 Assignment Operators. Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator

Introduction to Programming

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

Chapter 2 - Control Structures

Control Statements: Part Pearson Education, Inc. All rights reserved.

Chapter 3 Structured Program Development

Chapter 4 C Program Control

C Program Control. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

C++ PROGRAMMING SKILLS Part 2 Programming Structures

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

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

Chapter 4 C Program Control

If Control Construct

Control Statements: Part Pearson Education, Inc. All rights reserved.

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Structured Program Development

In this chapter you will learn:

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

BIL101E: Introduction to Computers and Information systems Lecture 8

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

BRANCHING if-else statements

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

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

Chapter 1 Introduction to Computers and C++ Programming

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

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

CS242 COMPUTER PROGRAMMING

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

IS 0020 Program Design and Software Tools

Fundamentals of Programming. Lecture 6: Structured Development (part one)

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

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

What we have learned so far

Exception Handling Pearson Education, Inc. All rights reserved.

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Exercise 1.1 Hello world

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

Score score < score < score < 65 Score < 50

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

Lecture 5 Tao Wang 1

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Why Is Repetition Needed?

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Chapter 15 - C++ As A "Better C"

Introduction to Programming

The following expression causes a divide by zero error:

REPETITION CONTROL STRUCTURE LOGO

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

1.4 Control Structures: Selection. Department of CSE

Chapter 4 - Notes Control Structures I (Selection)

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

C Pointers. 7.2 Pointer Variable Definitions and Initialization

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

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

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.5. for loop and do-while loop

DELHI PUBLIC SCHOOL TAPI

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

Chapter 4: Making Decisions

Functions and Recursion

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

Chapter 4: Making Decisions

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

Chapter 3 - Functions

C++ Programming Lecture 11 Functions Part I

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

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

C++ For Science and Engineering Lecture 12

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

CS110D: PROGRAMMING LANGUAGE I

Reviewing all Topics this term

Pointers and Strings Prentice Hall, Inc. All rights reserved.

Statements execute in sequence, one after the other, such as the following solution for a quadratic equation:

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Chapter 4: Control Structures I (Selection)

Lab 3: Control Flow / Conditional Statements. Based on the presentation made by Graham Northup

Exception Handling in C++

Computer Programming C++ Classes and Objects 6 th Lecture

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

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

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Boolean Algebra Boolean Algebra

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

LECTURE 04 MAKING DECISIONS

CSCI 6610: Review. Chapter 7: Numbers Chapter 8: Characters Chapter 11 Pointers

IS 0020 Program Design and Software Tools

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

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

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

Introduction to C++ Systems Programming

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

More Complex Versions of the if Statement. Class 13

Transcription:

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

Outline 1. The if Selection Structure 2. The if/else Selection Structure 3. The switch Multiple-Selection Structure

1. The if Selection Structure used to choose among alternative courses of action. 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. Expression true Action false

1. The if Selection Structure Example Is our number negative? If Value is less than zero then we need to update its value to that of its additive inverse Value < 0 true Value = -Value false If Value is not less than zero then our number is fine as is Our number is now definitely nonnegative

1. The if Selection Structure Pseudocode example: If student s grade is greater than or equal to 60 Print Passed If the condition is true print statement executed and program goes on to next statement If the condition is false print statement is ignored and the program goes onto the next statement Indenting makes programs easier to read C++ ignores whitespace characters

1. The if Selection Structure Translation of pseudocode statement into C++: if ( grade >= 60 ) cout << "Passed ; Diamond symbol (decision symbol) indicates decision is to be made Contains an expression that can be true or false. - Test the condition, follow appropriate path if structure is a single-entry/single-exit structure

1. The if Selection Structure Flowchart of pseudocode statement

1. The if Selection Structure int x = 5; int y = 10; What is the Output? if (x < y) ++x; ++y; cout << " x = " << x << y = << y << endl;

1. The if Selection Structure Example: Guess a secret number # include <iostream.h> # define secret 10 void main ( ) { int n; cout << Enter a number: ; cin >> n ; if ( n = = secret ) cout << You guessed right. ; else cout<< Try again, your guess is wrong. ; }

1. The if Selection Structure Example: Print a number squared if it is less than 100 # include <iostream.h> void main ( ) { int n, squared; cout << Enter a number: << endl ; cin >> n ; if ( n < 100 ) { squared = n * n ; cout << squared ; } else cout<< Your number is greater than 100 ; }

1. The if Selection Structure Example: 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;

1. The if Selection Structure Example: Sorting Two Numbers - Semantics Rearrange value1 and value2 to put their values in the proper order value2 < value1 true Are the numbers out of order false int remembervalue1 = value1 value1 = value2 value2 = remembervalue1 The numbers were rearranged into the proper order The numbers are in order The numbers were initially in order

2. The if/else Selection Structure if Only performs an action if the condition is true if/else A different action is performed when condition is true and when condition is false

2. The if/else Selection Structure Syntax if (Expression) Action 1 else Action 2 Expression If Expression is true then execute Action 1 otherwise execute Action 2 true false if (v == 0) { cout << "v is 0"; } else { cout << "v is not 0"; } Action 1 Action 2

2. The if/else Selection Structure Psuedocode if student s grade is greater than or equal to 60 print Passed else print Failed C++ code if ( grade >= 60 ) cout << "Passed"; else cout << "Failed";

2. The if/else Selection Structure false grade >= 60 true print Failed print Passed Ternary conditional operator (?:) Takes three arguments (condition, value if true, value if false) Our pseudocode could be written: cout << ( grade >= 60? Passed : Failed );

2. The if/else Selection Structure Example: Finding the Maximum cout << "Enter two integers: "; int Value1; int Value2; cin >> Value1 >> Value2; int Max; if (Value1 < Value2) { } else { } Max = Value2; Max = Value1; cout << "Maximum of inputs is: " << Max << endl;

2. The if/else Selection Structure Example: Finding the Maximum - Semantics Is Value2 larger than Value1 Yes, it is. So Value2 is larger than Value1. In this case, Max is set to Value2 true Value1 < Value2 false No, its not. So Value1 is at least as large as Value2. In this case, Max is set to Value1 Max = Value2 Max = Value1 Either case, Max is set correctly

2. The if/else Selection Structure Nested if/else structures Test for multiple cases by placing if/else selection structures inside if/else selection structures. if student s grade is greater than or equal to 90 Print A else if student s grade is greater than or equal to 80 Print B else if student s grade is greater than or equal to 70 Print C else if student s grade is greater than or equal to 60 Print D else Print F Once a condition is met, the rest of the statements are skipped

2. The if/else Selection Structure Compound statement: Block Set of statements within a pair of braces Example: if ( grade >= 60 ) cout << "Passed.\n"; else { cout << "Failed.\n"; cout << "You must take this course again.\n"; } Without the braces, cout << "You must take this course again.\n"; would be automatically executed Compound statements with declarations

2. The if/else Selection Structure Example: Convert a student degree to a grade # include <iostream.h> void main ( ) { int degree ; cout << Please enter your degree, it should be in the range from 0 to 100 ; cin >> degree ; if ( degree > = 0 && degree < = 100 ) { else if ( degree > = 90) cout << Excellent.Your grade is A ; else if ( degree > = 80) cout << Very Good.Your grade is B ; else if ( degree > = 70 ) cout << Good Your grade is C ; else cout << You Fail ; } cout << You enter a wrong degree, you should enter a number between 0 and 100 ; } Grad e A B C Fail Condition Degree is greater than or equal to 90 Degree is greater than or equal to 80 Degree is greater than or equal to 70 Degree is less than 70

2. The if/else Selection Structure Syntax errors Errors caught by compiler Logic errors Errors which have their effect at execution time - Non-fatal logic errors program runs, but has incorrect output - Fatal logic errors program exits prematurely

3. The Switch Multiple-Selection Structure switch Useful when variable or expression is tested for multiple values Consists of a series of case labels and an optional default case true case a case a action(s) break false true case b case b action(s) break false... true case z case z action(s) break false default action(s)

3. The Switch Multiple-Selection Structure Example: Decide a letter is vowel or not 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; }

1 // Fig. 2.22: fig02_22.cpp 2 // Counting letter grades 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 int main() 10 { 11 int grade, // one grade 12 acount = 0, // number of A's 13 bcount = 0, // number of B's 14 ccount = 0, // number of C's 15 dcount = 0, // number of D's 16 fcount = 0; // number of F's 17 18 cout << "Enter the letter grades." << endl 19 << "Enter the EOF character to end input." << endl; 20 21 while ( ( grade = cin.get() )!= EOF ) { 22 23 switch ( grade ) { // switch nested in while 24 25 case 'A': // grade was uppercase A 26 case 'a': // or lowercase a 27 ++acount; 28 break; // necessary to exit switch 29 30 case 'B': // grade was uppercase B 31 case 'b': // or lowercase b 32 ++bcount; 33 break; 34 2000 Prentice Hall, Inc. All rights Notice how the case statement is used 25 Outline 1. Initialize variables 2. Input data 2.1 Use switch loop to update count

35 case 'C': // grade was uppercase C 36 case 'c': // or lowercase c 37 ++ccount; 38 break; 39 40 case 'D': // grade was uppercase D 41 case 'd': // or lowercase d 42 ++dcount; 43 break; 44 45 case 'F': // grade was uppercase F 46 case 'f': // or lowercase f 47 ++fcount; 48 break; 49 50 case '\n': // ignore newlines, 51 case '\t': // tabs, 52 case ' ': // and spaces in input 53 break; 54 55 default: // catch all other characters 56 cout << "Incorrect letter grade entered." 57 << " Enter a new grade." << endl; 58 break; // optional 59 } 60 } 61 62 cout << "\n\ntotals for each letter grade are:" 63 << "\na: " << acount 64 << "\nb: " << bcount 65 << "\nc: " << ccount 66 << "\nd: " << dcount 67 << "\nf: " << fcount << endl; 68 69 return 0; 70 } 2000 Prentice Hall, Inc. All rights break causes switch to end and the program continues with the first statement after the switch structure. Notice the default statement. 26 Outline 2.1 Use switch loop to update count 3. Print results

Enter the letter grades. Enter the EOF character to end input. a B c C A d f C E Incorrect letter grade entered. Enter a new grade. D A b Outline Program Output Totals for each letter grade are: A: 3 B: 2 C: 3 D: 2 F: 1 2000 Prentice Hall, Inc. All rights 27

3. The Switch Multiple-Selection Structure Example: Convert a student degree to a grade # include <iostream.h> void main ( ) { int degree, temp ; cout << Please enter your degree, it should be in the range from 0 to 100 ; cin >> degree ; temp = degree / 10; switch ( temp) { case 10 : case 9 : cout << Excellent.Your grade is A ; break ; case 8 : cout << Very Good.Your grade is B ; break ; case 7 : cout << Good Your grade is C ; break ; case 6 : case 5: case 4: case 3: case 2: case 1: case 0: cout << You Fail ; break; default : cout << You enter a wrong degree, you should enter a number between 0 and 100 ; } } Grade A B C Fail Condition Degree is greater than or equal to 90 Degree is greater than or equal to 80 Degree is greater than or equal to 70 Degree is less than 70

3. The Switch Multiple-Selection Structure Example: Determine the number of days in a month # include <iostream.h> void main ( ) { int month, year ; cout << Please enter the number of the month ; cin >> month ; switch ( month ) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: cout << The number of days in this month is 31 days << endl ; break ; case 4: case 6: case 9: case 11: cout << The number of days in this month is 30 days << endl ; break ; case 2: cout << Please enter the year: ; cin >> year ; if ( year % 400 = = 0 ) cout << The number of days in this month is 29 days << endl ; else cout << The number of days in this month is 28 days << endl ; break ; default : cout << The month number should be in the range from 1 to 12 ; } }