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

Size: px
Start display at page:

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

Transcription

1 EEE-117 COMPUTER PROGRAMMING Control Structures Conditional Statements Today s s Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean) expressions Discover how to use the selection control structures if, if...else, and switch in a program Learn to use loops (Chapter 5) Assistant Prof. Dr. Turgay IBRIKCI Thursday, October 14, Control Structures A computer can proceed: in sequence selectively (branch) - making a choice repetitively (iteratively) - performing a statement over and over, also called a loop Some statements are executed only if certain conditions are met A condition is represented by a logical (Boolean) expression that has a value of either true or false A condition is met if it evaluates to true 3 4 Relational Operators Relational Operators in C++ A relational operator allows you to make comparisons in a program Equality of real numbers is usually machine dependent so it is possible that on a particular machine == might evaluate to false Comparing values of different data types may produce unpredictable results For example, 8 < '5' should not be done C++ returns an integer value of 1 if the logical expression evaluates to true and the value of 0 otherwise In C++, any nonzero value is treated as true 5 6

2 Comparing string Types Relational operators can be applied to string variables They are compared character by character, starting with the first character, using the collating sequence This comparison continues until either a mismatch is found or the last characters have been compared and are equal If two strings of different lengths are compared and the comparison is equal to the last character of the shorter string, the shorter string is less than the larger string 7 8 string Comparison Example Suppose we have the following declarations: string str1 = "Hello"; string str2 = "Hi"; string str3 = "Air"; string str4 = "Bill"; Logical (Boolean) Operators Logical (Boolean) operators enable you to combine logical expressions There are three logical (Boolean) operators:! - not && and - or Logical operators take logical values as operands and yield logical values as results! is unary, so it has only one operand, while && and are binary operators Putting! in front of a logical expression reverses the value of that logical expression 9 10 Precedence of Operators Relational and logical operators are evaluated from left to right so the associativity is said to be from left to right Parentheses can be used to indicate an order of operation that is different than the order indicated by order of precedence Short-circuit evaluation (of a logical expression) - a process in which the computer evaluates a logical expression from left to right and stops as soon as the value of the expression is known Precedence of Operators Expression Evaluates To Comments (14 >= 5) && ( A < B ) True (24 >= 35) && ( A < B ) False Because (14 >= 5) is True, ( A < B ) is True and true && true is true, the expression evaluates to true. Because (24 >= 35) is false, ( A < B ) is true and false && true is false, the expression evaluates to false. Refer to page 150 for further explanation 11 12

3 Precedence of Operators Logical (Boolean) Assignments The int Data Type and Logical (Boolean) Expressions earlier versions of C++ had no built in data type that had logical (or Boolean) values, true and false since logical expressions are evaluated to either 1 or 0, the value of a logical expression is stored in a variable of the type int logical (Boolean) expressions were manipulated with the help of the int data type any nonzero value is treated as true Logical (Boolean) Assignments The bool Data Type and Logical (Boolean) Expressions recent versions of C++ contain a built in data type called bool the data type bool has logical (Boolean) values true and false in C++, bool, true, and false are reserved words the identifier true has the value 1 the identifier false has the value 0 Logical (Boolean) Assignments Logical expressions do not always behave as expected The following expression appears to represent a comparison of 0, num, and 10: 0 <= num <= 10 It will always evaluate to true because 0 <= num evaluates to either 0 or 1, and 0 <= 10 is true and 1 <= 10 is true The correct way to write this expression is: 0 <= num && num <= One-Way (if( if) ) Selection Two-Way (if( if else) ) Selection The syntax of one-way selection is: if(expression) statement If the value of the expression is true the statement is executed If the value is false the statement is not executed and the computer goes on to the next statement in the program The expression is usually a logical expression statement is any C++ statement if is a reserved word Two-way selection takes the form: if(expression) else statement1 statement2 If the value of the expression is true, statement1 is executed otherwise statement2 is executed statement1 and statement2 are any C++ statements else is a reserved word 17 18

4 Two-Way (if( if else) ) Selection if(score >= 90) grade = A ; cout<< The grade is <<grade<<endl; What is is wrong with the above statement? If If incorrect, how would you re-write the logical statements? Compound Statement A compound statement (also called a block of statements) takes the form statement1; statement2;... statementn; A compound statement is considered a single statement Compound Statement Example if(age > 18) cout<<" Eligible to vote."<<endl; cout<<" No longer a minor."<<endl; else cout<<"not eligible to vote."<<endl; cout<<"still a minor."<<endl; Nested if When one control statement is within another, it is said to be nested An else is associated with the most recent if that has not been paired with an else For example: if(score >= 90) cout<<"the grade is A"<<endl; else if(score >= 80) else cout<<"the grade is B"<<endl; cout<<"the grade is F"<<endl; switch Structures In a switch structure, the expression is evaluated first Next, the value of the expression is used to perform the corresponding action The expression is usually an identifier It is sometimes called the selector The expression value can be only integral Its value determines which statement is selected for execution A particular case value should appear only once switch Structures One or more statements may follow a case label Braces are not needed to turn multiple statements into a single compound statement The break statement may or may not appear after each statement The break statement has a special meaning and may or may not appear after each statement switch, case, break, and default are reserved words 23 24

5 switch Statement Rules When the value of the expression is matched against a case value, the statements execute until a break statement is found or the end of the switch structure is reached If the value of the expression does not match any of the case values, the statements following the default label execute. If there is no default label, and if the value of the expression does not match any of the case values, the entire switch statement is skipped A break statement causes an immediate exit from the switch structure Control Structures - Repetition Chapter 5 25 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled Loops Flag Controlled Loops EOF Controlled Loops for Loops The do while Looping Structure Why Is Repetition Needed? Consider a task that the computer might automate Calculate and print paychecks Read invoices from a file and print monthly statements Read inputs from a sensor and adjust the air-fuel mixture of an engine In general The "Input process output" cycle Why Is Repetition Needed? 29 The Repetition Structure 30 The algorithm requires a set of actions to be done over and over again Same set of actions Number of times to be executed is unknown at design time We need a structure which allows Statement(s) to be repeated A method of testing to see whether the statements should be repeated The while loop provides the repetition structure Statement(s) to be repeated A means of checking whether the statement(s) will be repeated Syntax: while ( logicalexpression ) statement;

6 Phases of Loop Execution 31 While Loop Illustration 32 Loop entry => flow of control reaches first statement inside loop Iteration => each pass thru the loop Loop test => condition tested before each iteration while (condition) false true Loop Iteration Loop Iteration Loop Test Loop Test Loop Exit Loop Exit Loop exit => when termination condition occurs statement 1 in while statement, loop is NOT executed another time statement 2 Loop Entry Loop Entry Counter Controlled Loops For when you know exactly how many times the loop should run There are 10 employees for which to print checks There are 60 sensor inputs per second The program needs a Loop Control Variable 33 Count Controlled Loop Uses a Loop Control Variable (LCV) x = 0; 0; while (x (x <= <= 10) cout << << count = << << x << << endl; x = x + 1; 1; 34 What gets printed? What gets printed? Count Controlled Loops 35 Count Controlled Loops 36 The LCV must be... Initialized I nitialized I ncremented I nspected YES x = 0; 0; while (x (x <= <= 10) 10) cout << << count = << << x << << endl; x = x + 1; 1; Inspected Incremented

7 Sentinel Controlled Loops Suppose you want to read some positive integers and average them You do not have a preset number of data items in mind. Suppose the number 999 marks the end of data. Then the -999 is your "sentinel" cin>>variable; 37 while(variable!= sentinel)... View sample program Flag Controlled Loops A flag controlled loop uses a Boolean variable to control the loop Example Let found be the Boolean variable found = false; while(!found)... if(expression) found = true; 38 The flag is set according to some condition cin>> variable; EOF Controlled Loops End of File Controlled 39 Testing the State of an I/O Stream The name of the input stream (used by itself) returns a value returns a 0 if it is NOT successful it returns a NON zero value if it IS successful 40 Do you need to to know how many items are in in the file? Why? Why not? Testing the State of an I/O Stream 41 EOF Controlled Loops 42 When reading a file (a named input stream) we wish to know when it reaches the end Since the name returns a 0 or non-0, this can be used as a Boolean value Used to control program sequencing, control a file reading loop Can also be used in keyboard entry situations cin>>variable; while(cin)... cin>>variable; // Ctrl-Z Z to signify eof Although a sentinel controlled loop might be more user friendly

8 EOF Controlled Loops 43 A Special Count Controlled Loop 44 In addition to checking the value of an input stream variable eof The function with an input stream variable can also be used to determine the end of file status. Syntax: istreamvar.eof() Example infile.get(ch); while(!infile.eof()) cout<<ch; infile.get(ch); The for ( ) statement for for ( initialization ; test expression ; update ) 0 or or more statements to to repeat Initialization : initializes the LCV Condition : usually a comparison, acts like a while ( ) Incrementing statement : LCV is incremented (or decremented) The for ( ) Loop 45 The for ( ) Loop 46 Example - what gets printed? x gets initialized How did it Happen? All three of the portions inside the parentheses can be multiple statements separated by commas Any or all of the three portions inside the parenthesis may be missing accomplish those tasks some other way the two semicolons MUST be there value of x inspected x gets incremented for Loops 47 A Different Looping Statement 48 Note the sequence of events in a for loop Recall that the while ( ) statement always checked the condition BEFORE the loop In certain situations we wish to check the condition at The END of the loop After the statement Is it possible that the initialization and condition could be set so that that the loop statement would never execute?

9 The Do-While Statement 49 The do-while Illustrated Condition tested at end/bottom of loop Guarantees loop body executes at least once Loop Entry Loop Entry Loop Iteration Loop Iteration Note: always at least one iteration Loop Exit Loop Exit Loop Trest Loop Trest 50 The Do-While Statement 51 The Do while Statement 52 Can be used for a counting loop This logic sometimes more suitable for some algorithms Example : trap for valid input do cout << Enter value (1-5) -> ; cin >> value; if (value < 1 value > 5) cout << Invalid input\a << endl; while (value < 1 value > 5); What gets printed?? How do you change it to go 10 times? What makes this this easier than than the the while while (( )) loop loop for for this this task? do-while Loop vs. while Loop 53 The break; Statement 54 POST-TEST loop (exitcondition) 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. We saw it in the switch statement Causes immediate exit from innermost block switch, while, do-while while, for Can be used to break out of purposely designed infinite loop not a good idea a lazy shortcut Use only as last resort to avoid baffling combinations of multiple Boolean flags and nested ifs

10 The continue; Statement Valid only in loops Terminates current loop iteration NOT entire loop Causes branch to bottom of loop skips rest of loop statements Loop then prepares for next iteration for ( )( would increment lcv all loops would check condition Guidelines for Choosing a Looping Statement Simple count-controlled use for ( )( loop Event controlled, body always executed at least once use do-while Event controlled and nothing known about first execution use while, possibly for When in doubt => use while Testing and Debugging For do-while loops, make sure to try data sets to make loop go exactly one time For data-dependant loop where expressions based on values other than constants make sure to test for proper number of iterations Make sure switch statements have every branch tested including default 57 Testing and Debugging Remember to use break at end of case alternatives in switch statements otherwise next case is also executed! Case labels in switch statement must be values or named constants -- no variables Both switch expression & case constant cannot be floating point Provide default for switch when possibility of case values not being matched 58 Testing and Debugging Make sure all needed switch cases are present Choose looping structure carefully 59 for( ; ; ) loop heading must have two semicolons -- even if portions omitted Break statement can exit only one level of nesting innermost switch or loop where break is located The assert Function Certain types of errors that are very difficult to catch can occur in a program For example, division by zero can be difficult to catch using any of the programming techniques we have examined so far The predefined function, assert, is useful in stopping program execution when certain elusive errors occur 60

11 The assert Function The syntax to use the assert function is: assert(expression); expression is any logical expression If expression evaluates to true, the next statement executes If the expression evaluates to false, the program terminates and indicates where in the program the error occurred The specification of the assert function is found in the header file cassert The assert Function The assert statement is very useful for enforcing programming constraints during program development After a program has been developed and put into use, if an assert statement fails for some reason, an end user would have no idea what the error means After developing and testing a program, remove or disable assert statements The preprocessor directive #define NDEBUG must be placed before the directive #include <cassert> to disable the assert statement Quick Quiz Given the following values for Boolean variables X, Y, and Z, evaluate the logical expressions and answer T if the result is True and F if the result is False. X = True, Y = False, Z = False!(Y!(Y Z) Z) X Z && && X && && Y!Y!Y (Z (Z!X)!X) Z (X (X && && (Y (Y Z) Z) )) 5!X!X && && Z Quick Quiz What is the output of the following code segment? int hours = 12; If (hours > 40) cout << "Overtime Hours\n"; What is the output of the following code segment? int num1 = 3, num2 = 2, temp = 0; if (num1 > num2) temp = num1; num1 = num2; num2 = temp; cout << num1 << endl; else cout << "No change\n"; Quick Quiz What occurs if a program statement includes a divide by zero? What occurs if a program statement includes a divide by zero and the assert function is used? 65 66

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

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators Objectives Chapter 4: Control Structures I (Selection) In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

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

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d. Chapter 4: Control Structures I (Selection) In this chapter, you will: Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

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

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection) Control Structures A computer can proceed: In sequence Selectively (branch) - making

More information

Chapter 4: Control Structures I (Selection)

Chapter 4: Control Structures I (Selection) Chapter 4: Control Structures I (Selection) 1 Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean) expressions Discover

More information

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

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures Objectives Chapter 4: Control Structures I (Selection) In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

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

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection) C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection) Objectives In this chapter, you will: Learn about control structures Examine relational

More information

Chapter 4 - Notes Control Structures I (Selection)

Chapter 4 - Notes Control Structures I (Selection) Chapter 4 - Notes Control Structures I (Selection) I. Control Structures A. Three Ways to Process a Program 1. In Sequence: Starts at the beginning and follows the statements in order 2. Selectively (by

More information

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

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 5: Control Structures II (Repetition) Why Is Repetition Needed? Repetition allows you to efficiently use variables Can input,

More information

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

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed? Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct and use countercontrolled, sentinel-controlled,

More information

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

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

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

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition) C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

More information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

Why Is Repetition Needed?

Why Is Repetition Needed? Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable

More information

Control Structures: The IF statement!

Control Structures: The IF statement! Control Structures: The IF statement! 1E3! Topic 5! 5 IF 1 Objectives! n To learn when and how to use an IF statement.! n To be able to form Boolean (logical) expressions using relational operators! n

More information

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

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points) Name Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Relational Expression Iteration Counter Count-controlled loop Loop Flow

More information

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

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017 Loops! Loops! Loops! Lecture 5 COP 3014 Fall 2017 September 25, 2017 Repetition Statements Repetition statements are called loops, and are used to repeat the same code mulitple times in succession. The

More information

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

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++ Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

More information

Chapter 5: Control Structures II (Repetition)

Chapter 5: Control Structures II (Repetition) Chapter 5: Control Structures II (Repetition) 1 Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled, sentinel-controlled, flag-controlled, and

More information

Lecture 3 Tao Wang 1

Lecture 3 Tao Wang 1 Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers

More information

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

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Copyright 2011 Pearson Addison-Wesley. All rights reserved.

More information

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

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester Programming Language Control Structures: Repetition (while) Eng. Anis Nazer Second Semester 2017-2018 Repetition statements Control statements change the order which statements are executed Selection :

More information

Chapter 7. Additional Control Structures

Chapter 7. Additional Control Structures 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

More information

LESSON 3 CONTROL STRUCTURES

LESSON 3 CONTROL STRUCTURES LESSON CONTROL STRUCTURES PROF. JOHN P. BAUGH PROFJPBAUGH@GMAIL.COM PROFJPBAUGH.COM CONTENTS INTRODUCTION... Assumptions.... Logic, Logical Operators, AND Relational Operators..... - Logical AND (&&) Truth

More information

Chapter 4: Control Structures I

Chapter 4: Control Structures I Chapter 4: Control Structures I Java Programming: From Problem Analysis to Program Design, Second Edition Chapter Objectives Learn about control structures. Examine relational and logical operators. Explore

More information

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029 Programming Basics and Practice GEDB029 Decision Making, Branching and Looping Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029 Decision Making and Branching C language possesses such decision-making capabilities

More information

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

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator. Chapter 5: Looping 5.1 The Increment and Decrement Operators Copyright 2009 Pearson Education, Inc. Copyright Publishing as Pearson 2009 Addison-Wesley Pearson Education, Inc. Publishing as Pearson Addison-Wesley

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved. Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

CSCI 1061U Programming Workshop 2. C++ Basics

CSCI 1061U Programming Workshop 2. C++ Basics CSCI 1061U Programming Workshop 2 C++ Basics 1 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output

More information

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures Chapter 5: Control Structures II Java Programming: Program Design Including Data Structures Chapter Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled,

More information

LECTURE 5 Control Structures Part 2

LECTURE 5 Control Structures Part 2 LECTURE 5 Control Structures Part 2 REPETITION STATEMENTS Repetition statements are called loops, and are used to repeat the same code multiple times in succession. The number of repetitions is based on

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

Chapter 4: Making Decisions

Chapter 4: Making Decisions Chapter 4: Making Decisions 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than or equal to

More information

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

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement Last Time Let s all Repeat Together 10/3/05 CS150 Introduction to Computer Science 1 1 We covered o Counter and sentinel controlled loops o Formatting output Today we will o Type casting o Top-down, stepwise

More information

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

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

More information

Chapter 4: Making Decisions

Chapter 4: Making Decisions Chapter 4: Making Decisions CSE 142 - Computer Programming I 1 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >=

More information

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

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018. 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

More information

Programming for Engineers Iteration

Programming for Engineers Iteration Programming for Engineers Iteration ICEN 200 Spring 2018 Prof. Dola Saha 1 Data type conversions Grade average example,-./0 class average = 23450-67 893/0298 Grade and number of students can be integers

More information

5. Selection: If and Switch Controls

5. Selection: If and Switch Controls Computer Science I CS 135 5. Selection: If and Switch Controls René Doursat Department of Computer Science & Engineering University of Nevada, Reno Fall 2005 Computer Science I CS 135 0. Course Presentation

More information

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage: Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;

More information

Chapter 3. More Flow of Control

Chapter 3. More Flow of Control Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-2 Flow Of Control Flow of control refers to the

More information

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

Flow of Control. Flow of control The order in which statements are executed. Transfer of control 1 Programming in C Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control

More information

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

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed Programming in C 1 Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control

More information

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

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

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

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

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

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

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

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All for repetition statement do while repetition statement switch multiple-selection statement break statement continue statement Logical

More information

Add Subtract Multiply Divide

Add Subtract Multiply Divide ARITHMETIC OPERATORS if AND if/else AND while LOOP Order of Operation (Precedence Part 1) Copyright 2014 Dan McElroy Add Subtract Multiply Divide + Add - Subtract * Multiply / Divide = gives the quotient

More information

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

C++ Programming Lecture 7 Control Structure I (Repetition) Part I C++ Programming Lecture 7 Control Structure I (Repetition) Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department while Repetition Structure I Repetition structure Programmer

More information

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

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3 Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions

More information

The following expression causes a divide by zero error:

The following expression causes a divide by zero error: Chapter 2 - Test Questions These test questions are true-false, fill in the blank, multiple choice, and free form questions that may require code. The multiple choice questions may have more than one correct

More information

(Refer Slide Time: 00:26)

(Refer Slide Time: 00:26) Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute Technology, Madras Module 07 Lecture 07 Contents Repetitive statements

More information

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures Chapter 4: Control Structures I Java Programming: Program Design Including Data Structures Chapter Objectives Learn about control structures Examine relational and logical operators Explore how to form

More information

In this chapter you will learn:

In this chapter you will learn: 1 In this chapter you will learn: Essentials of counter-controlled repetition. Use for, while and do while to execute statements in program repeatedly. Use nested control statements in your program. 2

More information

Chapter 5: Loops and Files

Chapter 5: Loops and Files Chapter 5: Loops and Files 5.1 The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1;

More information

Loops and Files. of do-while loop

Loops and Files. of do-while loop L E S S O N S E T 5 Loops and Files PURPOSE PROCEDURE 1. To introduce counter and event controlled loops 2. To work with the while loop 3. To introduce the do-while loop 4. To work with the for loop 5.

More information

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

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A. Islamic University of Gaza Computer Engineering Dept. C++ Programming For Industrial And Electrical Engineering By Instructor: Ruba A. Salamh Chapter Four: Loops 2 Chapter Goals To implement while, for

More information

LECTURE 04 MAKING DECISIONS

LECTURE 04 MAKING DECISIONS PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 04 MAKING DECISIONS

More information

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

Increment and the While. Class 15

Increment and the While. Class 15 Increment and the While Class 15 Increment and Decrement Operators Increment and Decrement Increase or decrease a value by one, respectively. the most common operation in all of programming is to increment

More information

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

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1 Chapter 5: Loops and Files The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1; ++ can be used before (prefix) or after (postfix)

More information

Lecture 7 Tao Wang 1

Lecture 7 Tao Wang 1 Lecture 7 Tao Wang 1 Objectives In this chapter, you will learn about: Interactive loop break and continue do-while for loop Common programming errors Scientists, Third Edition 2 while Loops while statement

More information

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

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode STUDENT OUTLINE Lesson 8: Structured Programming, Control Structures, if- Statements, Pseudocode INTRODUCTION: This lesson is the first of four covering the standard control structures of a high-level

More information

Chapter 5 Selection Statements. Mr. Dave Clausen La Cañada High School

Chapter 5 Selection Statements. Mr. Dave Clausen La Cañada High School Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School Objectives Construct and evaluate Boolean expressions Understand how to use selection statements to make decisions Design and test

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

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

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++ CHAPTER 9 C++ 1. WRITE ABOUT THE BINARY OPERATORS USED IN C++? ARITHMETIC OPERATORS: Arithmetic operators perform simple arithmetic operations like addition, subtraction, multiplication, division etc.,

More information

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition 5.2 Q1: Counter-controlled repetition requires a. A control variable and initial value. b. A control variable

More information

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false. CS101, Mock Boolean Conditions, If-Then Boolean Expressions and Conditions The physical order of a program is the order in which the statements are listed. The logical order of a program is the order in

More information

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

COP 2000 Introduction to Computer Programming Mid-Term Exam Review he exam format will be different from the online quizzes. It will be written on the test paper with questions similar to those shown on the following pages. he exam will be closed book, but students can

More information

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

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme Chapter 4: 4.1 Making Decisions Relational Operators Simple Program Scheme Simple Program Scheme So far our programs follow a simple scheme Gather input from the user Perform one or more calculations Display

More information

Introduction to C Programming

Introduction to C Programming 1 2 Introduction to C Programming 2.6 Decision Making: Equality and Relational Operators 2 Executable statements Perform actions (calculations, input/output of data) Perform decisions - May want to print

More information

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do..

More information

Checking Multiple Conditions

Checking Multiple Conditions Checking Multiple Conditions Conditional code often relies on a value being between two other values Consider these conditions: Free shipping for orders over $25 10 items or less Children ages 3 to 11

More information

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

More information

DELHI PUBLIC SCHOOL TAPI

DELHI PUBLIC SCHOOL TAPI Loops Chapter-1 There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed

More information

Control Structures. A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping

Control Structures. A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping Control Structures A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping Conditional Execution if is a reserved word The most basic syntax for

More information

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

Using Boolean Expressions. Multiway Branches. More about C++ Loop Statements. Designing Loops. In this chapter, you will learn about:

Using Boolean Expressions. Multiway Branches. More about C++ Loop Statements. Designing Loops. In this chapter, you will learn about: Chapter 3 In this chapter, you will learn about: Using Boolean Expressions Multiway Branches More about C++ Loop Statements Designing Loops Boolean Expressions Take the Value true or false Boolean Value

More information

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

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure Learning Objectives At the end of this chapter, student should be able to: Understand the requirement of a loop Understand the Loop Control Variable () Use increment (++) and decrement ( ) operators Program

More information

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

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols. EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic

More information

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

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator 1 A Closer Look at the / Operator Used for performing numeric calculations C++ has unary, binary, and ternary s: unary (1 operand) - binary ( operands) 13-7 ternary (3 operands) exp1? exp : exp3 / (division)

More information

C++ Programming: From Problem Analysis to Program. Design, Fifth Edition. Chapter 1: An Overview of Computers and Programming Languages

C++ Programming: From Problem Analysis to Program. Design, Fifth Edition. Chapter 1: An Overview of Computers and Programming Languages C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 1: An Overview of Computers and Programming Languages Updated by: Malak Abdullah The Evolution of Programming Languages (cont'd.)

More information

C++ Final Exam 2017/2018

C++ Final Exam 2017/2018 1) All of the following are examples of integral data types EXCEPT. o A Double o B Char o C Short o D Int 2) After the execution of the following code, what will be the value of numb if the input value

More information

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

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 1 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 variables. Apply C++ syntax rules to declare variables, initialize

More information

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

More information

Chapter 5: Control Structures

Chapter 5: Control Structures Chapter 5: Control Structures In this chapter you will learn about: Sequential structure Selection structure if if else switch Repetition Structure while do while for Continue and break statements S1 2017/18

More information

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

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration) Week 7: Advanced Loops while Loops in C++ (review) while (expression) may be a compound (a block: {s) Gaddis: 5.7-12 CS 1428 Fall 2015 Jill Seaman 1 for if expression is true, is executed, repeat equivalent

More information

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

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators Chapter 5: 5.1 Looping The Increment and Decrement Operators The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++;

More information

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

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping). 1 causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping). Before considering specifics we define some general terms that

More information

SFU CMPT Topic: Control Statements

SFU CMPT Topic: Control Statements SFU CMPT-212 2008-1 1 Topic: Control Statements SFU CMPT-212 2008-1 Topic: Control Statements Ján Maňuch E-mail: jmanuch@sfu.ca Wednesday 23 rd January, 2008 SFU CMPT-212 2008-1 2 Topic: Control Statements

More information

Chapter 3 Structured Program Development

Chapter 3 Structured Program Development 1 Chapter 3 Structured Program Development Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 3 - Structured Program Development Outline 3.1 Introduction

More information

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

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS Objectives By the end of this section you should be able to:

More information

G. Tardiani RoboCup Rescue. EV3 Workshop Part 1 Introduction to RobotC

G. Tardiani RoboCup Rescue. EV3 Workshop Part 1 Introduction to RobotC RoboCup Rescue EV3 Workshop Part 1 Introduction to RobotC Why use RobotC? RobotC is a more traditional text based programming language The more compact coding editor allows for large programs to be easily

More information

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

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14 Chapter 4: Making Decisions 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than or equal to

More information

CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 5&6: Loops Lecture Contents Why loops?? While loops for loops do while loops Nested control structures Motivation Suppose that you need

More information

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision Lesson Outcomes At the end of this chapter, student should be able to: Use the relational operator (>, >=,

More information