Lecture 2 Notes: Flow of Control



Similar documents
6. Control Structures

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Two-way selection. Branching and Looping

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Object Oriented Software Design

Chapter 8 Selection 8-1

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

PHP Tutorial From beginner to master

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Chapter 5. Selection 5-1

TIP: To access the WinRunner help system at any time, press the F1 key.

Moving from C++ to VBA

1.3 Conditionals and Loops

Object Oriented Software Design

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Statements and Control Flow

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

JavaScript: Control Statements I

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Example of a Java program

Sources: On the Web: Slides will be available on:

While Loop. 6. Iteration

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

PIC 10A. Lecture 7: Graphics II and intro to the if statement

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

Conditions & Boolean Expressions

Member Functions of the istream Class

Writing Control Structures

UEE1302 (1102) F10 Introduction to Computers and Programming

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

VB.NET Programming Fundamentals

Selection Statements

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Chapter One Introduction to Programming

J a v a Quiz (Unit 3, Test 0 Practice)

Introduction to Java

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

if and if-else: Part 1

Object oriented programming. Course Objectives. On completion of the class, a student should be able: Object Oriented Paradigm

Bash shell programming Part II Control statements

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Basics of I/O Streams and File I/O

Common Beginner C++ Programming Mistakes

Moving from CS 61A Scheme to CS 61B Java

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

The While Loop. Objectives. Textbook. WHILE Loops

C++ INTERVIEW QUESTIONS

Syllabus OBJECT ORIENTED PROGRAMMING C++

Informatica e Sistemi in Tempo Reale

ChE-1800 H-2: Flowchart Diagrams (last updated January 13, 2013)

The if Statement and Practice Problems

Chapter 5 Functions. Introducing Functions

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

A brief introduction to C++ and Interfacing with Excel

13 Classes & Objects with Constructors/Destructors

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Chapter 3 Operators and Control Flow

C++FA 5.1 PRACTICE MID-TERM EXAM

AP Computer Science Java Subset

COMS 4115 Programming Languages and Translators Fall 2013 Professor Edwards. Lullabyte

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Conditional Statements Summer 2010 Margaret Reid-Miller

«W3Schools Home Next Chapter» JavaScript is THE scripting language of the Web.

Learning Computer Programming using e-learning as a tool. A Thesis. Submitted to the Department of Computer Science and Engineering.

Introduction to Java Lecture Notes. Ryan Dougherty

Excel: Introduction to Formulas

Introduction to Python

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Programming Database lectures for mathema

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Shell Scripts (1) For example: #!/bin/sh If they do not, the user's current shell will be used. Any Unix command can go in a shell script

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

Unit 6. Loop statements

Iteration CHAPTER 6. Topic Summary

MATLAB Programming. Problem 1: Sequential

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

Tutorial on C Language Programming

Computer Programming C++ Classes and Objects 15 th Lecture

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Passing 1D arrays to functions.

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Chapter 2: Elements of Java

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

Appendix K Introduction to Microsoft Visual C++ 6.0

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

Transcription:

6.096 Introduction to C++ January, 2011 Massachusetts Institute of Technology John Marrero Lecture 2 Notes: Flow of Control 1 Motivation Normally, a program executes statements from first to last. The first statement is executed, then the second, then the third, and so on, until the program reaches its end and terminates. A computer program likely wouldn't be very useful if it ran the same sequence of statements every time it was run. It would be nice to be able to change which statements ran and when, depending on the circumstances. For example, if a program checks a file for the number of times a certain word appears, it should be able to give the correct count no matter what file and word are given to it. Or, a computer game should move the player's character around when the player wants. We need to be able to alter the order in which a program's statements are executed, the control flow. 2 Control Structures Control structures are portions of program code that contain statements within them and, depending on the circumstances, execute these statements in a certain way. There are typically two kinds: conditionals and loops. 2.1 Conditionals In order for a program to change its behavior depending on the input, there must a way to test that input. Conditionals allow the program to check the values of variables and to execute (or not execute) certain statements. C++ has if and switch-case conditional structures. 2.1.1 Operators Conditionals use two kinds of special operators: relational and logical. These are used to determine whether some condition is true or false. The relational operators are used to test a relation between two expressions: Operator Meaning > Greater than >= Greater than or equal to < Less than <= Less than or equal to == Equal to!= Not equal to They work the same as the arithmetic operators (e.g., a > b) but return a Boolean value of either true or false, indicating whether the relation tested for holds. (An expression that returns this kind of value is called a Boolean expression.) For example, if the variables x and y have been set to 6 and 2, respectively, then x > y returns true. Similarly, x < returns false. The logical operators are often used to combine relational expressions into more complicated Boolean expressions:

Operator Meaning && and or! not The operators return true or false, according to the rules of logic: a b a && b true true true true false false false true false false false false a b a b true true true true false true false true true false false false The! operator is a unary operator, taking only one argument and negating its value: a!a true false false true Examples using logical operators (assume x = 6 and y = 2):!(x > 2) false (x > y) && (y > 0) true (x < y) && (y > 0) false (x < y) (y > 0) true Of course, Boolean variables can be used directly in these expressions, since they hold true and false values. In fact, any kind of value can be used in a Boolean expression due to a quirk C++ has: false is represented by a value of 0 and anything that is not 0 is true. So, Hello, world! is true, 2 is true, and any int variable holding a non-zero value is true. This means!x returns false and x && y returns true! 2.1.2 if, if-else and else if The if conditional has the form: if(condition)

The condition is some expression whose value is being tested. If the condition resolves to a value of true, then the statements are executed before the program continues on. Otherwise, the statements are ignored. If there is only one statement, the curly braces may be omitted, giving the form: if(condition) statement The if-else form is used to decide between two sequences of statements referred to as blocks: if(condition) statementa1 statementa2 else statementb1 statementb2 If the condition is met, the block corresponding to the if is executed. Otherwise, the block corresponding to the else is executed. Because the condition is either satisfied or not, one of the blocks in an if-else must execute. If there is only one statement for any of the blocks, the curly braces for that block may be omitted: if(condition) statementa1 else statementb1 The else if is used to decide between two or more blocks based on multiple conditions: if(condition1) statementa1 statementa2 else if(condition2) statementb1 statementb2 If condition1 is met, the block corresponding to the if is executed. If not, then only if condition2 is met is the block corresponding to the else if executed. There may be more than one else if, each with its own condition. Once a block whose condition was met is executed, any else ifs after it are ignored. Therefore, in an if-else-if structure, either one or no block is executed. An else may be added to the end of an if-else-if. If none of the previous conditions are met, the else block is executed. In this structure, one of the blocks must execute, as in a normal ifelse. Here is an example using these control structures:

4 int main() int x = 6; 6 int y = 2; 7 if(x > y) 9 cout << x is greater than y\n ; 10 else if(y > x) 11 cout << y is greater than x\n ; 12 else 1 cout << x and y are equal\n ; 14 1 return 0; 16 The output of this program is x is greater than y. If we replace lines and 6 with int x = 2; int y = 6; then the output is y is greater than x. If we replace the lines with int x = 2; int y = 2; then the output is x and y are equal. 2.1. switch-case The switch-case is another conditional structure that may or may not execute certain statements. However, the switch-case has peculiar syntax and behavior: switch(expression) case constant1: statementa1 statementa2... break; case constant2: statementb1 statementb2... break;... default: statementz1 statementz2... The switch evaluates expression and, if expression is equal to constant1, then the statements beneath case constant 1: are executed until a break is encountered. If expression is not equal to constant1, then it is compared to constant2. If these are equal, then the statements beneath case constant 2: are executed until a break is encountered. If not, then the same process repeats for each of the constants, in turn. If none of the constants match, then the statements beneath default: are executed. Due to the peculiar behavior of switch-cases, curly braces are not necessary for cases where

there is more than one statement (but they are necessary to enclose the entire switch-case). switch-cases generally have if-else equivalents but can often be a cleaner way of expressing the same behavior. Here is an example using switch-case: 4 int main() int x = 6; 6 7 switch(x) 9 10 11 12 case : 1 14 1 default: 16 17 1 19 20 return 0; case 1: cout << x is 1\n ; break; case 2: cout << "x is 2 or "; break; cout << "x is not 1, 2, or "; This program will print x is not 1, 2, or. If we replace line with int x = 2; then the program will print x is 2 or. 2.2 Loops Conditionals execute certain statements if certain conditions are met; loops execute certain statements while certain conditions are met. C++ has three kinds of loops: while, do-while, and for. 2.2.1 while and do-while The while loop has a form similar to the if conditional: while(condition) As long as condition holds, the block of statements will be repeatedly executed. If there is only one statement, the curly braces may be omitted. Here is an example: 1 2 4 6 7 #include <iostream> using namespace std; int main() int x = 0; while(x < 10) x = x + 1;

9 10 11 12 1 cout << x is << x << \n ; return 0; This program will print x is 10. The do-while loop is a variation that guarantees the block of statements will be executed at least once: do while(condition); The block of statements is executed and then, if the condition holds, the program returns to the top of the block. Curly braces are always required. Also note the semicolon after the while condition. 2.2.2 for The for loop works like the while loop but with some change in syntax: for(initialization; condition; incrementation) The for loop is designed to allow a counter variable that is initialized at the beginning of the loop and incremented (or decremented) on each iteration of the loop. Curly braces may be omitted if there is only one statement. Here is an example: 4 int main() 6 for(int x = 0; x < 10; x = x + 1) 7 cout << x << \n ; 9 return 0; 10 This program will print out the values 0 through 9, each on its own line. If the counter variable is already defined, there is no need to define a new one in the initialization portion of the for loop. Therefore, it is valid to have the following:

4 int main() 6 int x = 0; 7 for(; x < 10; x = x + 1) cout << x << \n ; 9 10 return 0; 11 Note that the first semicolon inside the for loop's parentheses is still required. A for loop can be expressed as a while loop and vice-versa. Recalling that a for loop has the form for(initialization; condition; incrementation) we can write an equivalent while loop as initialization while(condition) incrementation Using our example above, 4 int main() 6 for(int x = 0; x < 10; x = x + 1) 7 cout << x << \n ; 9 return 0; 10 is converted to 1 2 4 6 7 9 10 11 12 1 #include <iostream> using namespace std; int main() int x = 0; while(x < 10) cout << x << \n ; x = x + 1; return 0;

The incrementation step can technically be anywhere inside the statement block, but it is good practice to place it as the last step, particularly if the previous statements use the current value of the counter variable. 2. Nested Control Structures It is possible to place ifs inside of ifs and loops inside of loops by simply placing these structures inside the statement blocks. This allows for more complicated program behavior. Here is an example using nesting if conditionals: 4 int main() int x = 6; 6 int y = 0; 7 if(x > y) 9 cout << x is greater than y\n ; 10 if(x == 6) 11 cout << x is equal to 6\n ; 12 else 1 cout << x is not equalt to 6\n ; 14 else 1 cout << x is not greater than y\n ; 16 17 return 0; 1 This program will print x is greater than y on one line and then x is equal to 6 on the next line. Here is an example using nested loops: 4 int main() for(int x = 0; x < 4; x = x + 1) 6 for(int y = 0; y < 4; y = y + 1) 7 cout << y; cout << \n ; 9 10 11 return 0; 12 This program will print four lines of 012.

MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2011 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.