# 5. Control Statements

Size: px
Start display at page:

Transcription

1 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 are also used to specify the looping of an algorithm and the conditions upon which the loop should be ended. Readings: [Savitch99] Section 2.4 and Chapter Control Statements Basic Flow of Control The C++ If Statement Boolean Expressions and Operators Boolean Variables and Literals The C++ Switch Statement What Kind of Loop? While Loops Do Loops Loops With Mid-Body Exits For Loops Copyright 1998 by R. Tront 5-1 Copyright 1998 by R. Tront 5-2

2 5.1 Basic Flow of Control A computer program is like a recipe. It is a list of instructions which described the steps of an algorithm. Most useful or very interesting algorithms are composed of more than just a linear list of steps. Such algorithms may have alternative sub-algorithms, only one of which you want executed under any particular conditions (for instance, only on Wednesdays). Other algorithms may be iterative in nature, repeating the same basic steps over and over again until some final desired result is obtained. Most introductory computer courses will tell you that any computer program can be composed with just three basic types of flow. Sequence Alternation Iteration There is a very visual technique called flow charting that I will use to introduce these three different types of flow of control. Yes Statement1 Statement2 Statement3 Is it Wednesday? Sequence No Statement4 Alternation Note 1: The flow chart branch symbol is often just a diamond, but a flattened hexagon provides more room inside to write the branch condition. Note 2: There is a variation of Alternation where something is done on Wednesdays and nothing if it is not Wednesday. Copyright 1998 by R. Tront 5-3 Copyright 1998 by R. Tront 5-4

3 Finished Iterating Yet? No Statement 7; Statement 8; Statement 9; Yes Iteration Most computer languages provide a variety of control statements. Only three different ones are required. And providing too many different control statements makes a program hard to read. Most modern computer languages have about the right number of kinds of control statements. Copyright 1998 by R. Tront The C++ If Statement Sequence in C++ is simple provided by programming one statement after another, usually separated by a semi-colon ( ; ). Alternation in C++ is provided by the C++ if and switch statements. The condition used in deciding which branch of the alteratives to take must be a boolean expression, or convertible to a boolean expression. short int temperature = 25; if (temperature < 15) cout << Temperature is low ; else { cout << Temp is high, << endl; cout << so turn on computer fan. ; } //The next statement goes here, //so this is where the two //alternative paths rejoin. This example of a C++ if statement shows the decision being made on a boolean expression. Boolean expressions are often formed by comparing the size of two numbers with relational (also called comparison) operators like: < - which at execution time determines if its first operand is less than the second. The result is a boolean value, either true or false. This is used by the if to Copyright 1998 by R. Tront 5-6

4 determine whether the then or else alterative is taken. (Note that contrary to the PASCAL programming language, C++ never requires you, and in fact doesn t allow you to write the word then ). <= - is an relational operator which determines if the first operand is less than or equal to the second. == - This is two equal sign characters, one right after the other. It is used to compare whether two operands are equal. If they are, the resulting boolean value used by the if statement is a true, otherwise the result is false which causes the else alternative to be executed. A single = should NOT be used in this case as that is the assignment operator, not a comparison operator! The two alternatives of an if statement are called the then and else clauses. In their simplest form, each may only contain one statement. But like compound statements in Pascal, you can replace the one statement with multiple statements suitably delimited by opening and closing brace characters {}. This is similar to Pascal s BEGIN and END statements. I have illustrated this in the else clause in the above example. Generally you do not need to put a semi-colon after a closing brace, as the closing brace is interpreted by the compiler to mean the end of a compound statement. There is important exceptions to this rule which will be pointed out later. Copyright 1998 by R. Tront 5-7 Sometimes you want to do something if the value in the temperature variable is less than 15, and simply skip doing that something otherwise and carry on with the rest of the algorithm. In that case, you can leave the else and the else clause out of your program! Note that it is common to indent the then and else clauses to improve readability. I will insist on this in Cmpt 101/104. A fast way to consistently do this is to use the tab key. Generally, the body of a function and an iterative loop are also indented from their first line. Note that when a then or else clause itself contains another if statement, you will want to indent further this entire second if statement. If that one contains yet another if statement, you should probably abandon indenting and go to a form like the following. This is particularly true if the first few ifs involved have nothing in their else clause but the next if. if (condition1) statement1; else if (condition2) statement2; else if (condition3) statement3; else otherwisestatement; You would use actual statements and conditionals when programming rather than this skeleton. Copyright 1998 by R. Tront 5-8

5 An (inner) if statement within an (outer) if statement is called a nested if. As discussed in the textbook readings for this course, there is a question of which if the final else applies to. You should know that it applies to the last if, unless you somehow use braces {} around one of the inner ifs to override this rule. Some other languages have an elsif or elseif keyword to make it very clear that the last else normally applies to the last if. Copyright 1998 by R. Tront Boolean Expressions and Operators Sometimes, you might nest ifs unnecessarily. It is sometimes possible to put the two ifs together with Boolean operators to form a compound boolean expression. e.g. if((temp < 15) && (speed > MACH1))... //instead of: if (temp < 15) if (speed > MACH1)... The && operator is the logical AND operator. This conditional can be read if temp is less than 15 and speed is greater than MACH1. The OR operator is written (i.e. one vertical bar immediately after another; you might have to search hard to find a vertical bar character on your keyboard). Boolean operators are used for more than just combining some special cases of single ifs; they are widely used for expressing and storing all kinds of logical conditions. Note that && is a boolean operator that works on boolean operands on both sides of it. i.e. bool boolvariable = true && false It is very important to examine the truth tables in your textbook to completely understand the operation of these operators. In the above case, boolvariable would be assigned the value false. In the if statement at the top of this section, the two boolean values being Copyright 1998 by R. Tront 5-10

6 ANDed together are the results of individual numerical comparisons. There is another boolean operator, in fact a unary boolean operator, called NOT. It is kind of like a unary negation - operator, but for boolean rather than numerical variables. It is! rather than the - used for arithmetic negation. Copyright 1998 by R. Tront Boolean Variables and Literals Boolean variables have just recently been added to C++, and many compilers more than a year old do not have this container type! An Appendix of [Savitch99] discusses how you might compensate for this. Boolean variables are containers to store boolean values. They usually only take up one byte of space, though in theory they could be reduced to one bit! Boolean variables are good if you need to store the result of a relational expression such as: bool b = (variable1 < variable2); b = (variable1 < PI); b = variable == PI; Notice that you should use lots of parentheses in boolean expressions and assignments. The bottom one just above has none and is very hard to read. In addition, it begs the question of which has the higher precedence and is thus done first: the assignment, or the comparison? If you use lots of parentheses, you will rarely have to concern yourself with the ugly details in your textbook regarding this. The only two literal values proper C++ boolean variables can have are false and true, spelled in Copyright 1998 by R. Tront 5-12

7 lower case with no quotes. But you can, for backward compatibility with C, assign a zero to a boolean and it will be automatically converted to a false and stored. Any non-zero value will be converted into and stored as a true. An aside: There are ways to convert a boolean to a number. This is part of an advanced topic called casting. To maintain some backward compatibility with old C, assigning a boolean to an integer will convert false into zero and true into a one. Sometimes this happens automatically and the results can surprise you. Also, cout << false annoyingly will print 0 rather than false. Copyright 1998 by R. Tront The C++ Switch Statement In the case of a long series of if, else if, else if,... there is often a better way to code this. It is called in Pascal a CASE statement and in C++ a switch statement. It works like this. int myint; const int FOUR = 4; cin >> myint; switch (myint * 2) { case 2: cout << first case ; cout << endl; break; case 4: cout << second case ; break; case 6: case 8: cout << third or fourth ; break; case 20/FOUR: cout << five ; break; default: cout << all others ; } //no semi-colon needed after }. A switch statement basically is a multi-way branch. The a variable or expression in parentheses controls which branch is taken. The flow of control jumps to Copyright 1998 by R. Tront 5-14

8 whatever corresponding case clause matches. That clause is executed. Note that several statements are allowed in each clause without needing braces {} to join them into one compound statement. The break keyword encountered at the end of a case clause indicates that execution is to again jump, this time to the first statement following the closing } of the switch statement. Don t forget the break at the end of each clause as otherwise one clause will execute right into the next! If none of the cases match the switch expression, then the optional default clause is executed. It is always a good idea to provide a default clause at the end of any switch statement. Note the default clause does not need a break because it is already at the bottom. Question: What happens when there is no default clause, and no matching case? Why don t you write such a program and use the debugger to single step through and watch what happens! The switch expression must be a variable or expression of some type that can be converted to an integer (e.g. short, long, char, bool. Recall that characters are stored as 1 byte long integers!). Note that A (including the quotes) is a usable integer constant. The case values must be integral literals or constant expressions. Though you can probably use a constant variable in a switch case, you cannot put regular variables there. This is because the series of comparisons done against each case is constructed by the compiler at compile time. If you must compare some expression against a variety of values including against values that might change at run time because they are stored in variables, then instead of a switch you simply have to use a series of if statements instead. Finally note that I have shown that you may use two cases in front of one case clause. Copyright 1998 by R. Tront 5-15 Copyright 1998 by R. Tront 5-16

9 5.6 What Kind of Loop? There are three C++ statements commonly used for iterative calculations that require a sequence of steps to be repeated over and over again. They are the: while statement do statement for statement Before you decide which one to use, you should draw a flow chart. Of particular concern is whether the decision to break out of the loop is at the top, bottom, or middle of the loop. Finished Iterating Yet? No Statement 7; Statement 8; Statement 9; Yes Loop with exit at top Top exit loops are nice because you can check first whether to exit the loop body at all! It allows that some days when you run the program with some data, the body of the loop will be skipped. Generally the body of the loop modifies some variables that are used in the boolean exit condition so as to definitely cause you to eventually exit. Copyright 1998 by R. Tront 5-17 Copyright 1998 by R. Tront 5-18

11 but rather an English-like set of statements that describe the steps of the algorithm you want to implement (you can translate into C++ later; first and most importantly, get the algorithm laid out correct by using visual aids). When designing loops, you MUST consider very carefully: what you need to do in preparation for entering the loop (e.g. define some variables the loop might need, and/or set some variables to suitable starting values), what do you want to do within the loop, do you always want to execute the body of the loop at least once? Perhaps then the exit decision should be at the bottom. Or should it be in the middle? Or if sometimes you don t want to execute the body of the loop at all, perhaps the decision should be made at the top so as to, if appropriate, allow for sometimes not executing the body of the loop! on which iteration do you want to leave the loop (9th iteration, 10th, or when myvar becomes greater or equal to 25), lastly, make sure that your exit condition will ALWAYS eventually come true, otherwise your program could loop forever. This often soaks up the processor s entire attention and there is sometimes no way to stop the program except to turn off the computer (which may cause you to loose data or your most recent program changes). Copyright 1998 by R. Tront 5-21 Copyright 1998 by R. Tront 5-22

13 This will be extremely valuable to you. See the TAs if you need help with any of this. And yes some of you real C and C++ hackers, I know that you can replace the lines: runningtotal = runningtotal + n; n = n-1; with: runningtotal += n; n--; 5.8 Do Loops If you want your exit decision to be performed at the end of the loop body, you need a do... while(); style loop. Here is a familiar program changes to instead use a do loop: int n; cout << Type an integer: ; cin >> n; cout << endl << The sum of 1 to << n << is ; int runningtotal = 0; do{ runningtotal = runningtotal + n; n = n-1; }while (n >= 0); cout << runningtotal; Notice the structure of a do loop. There is only the keyword do at the beginning (plus a brace if there is more than one statement in the body of the loop). You indicate whether the loop will continue iterating by placing the while keyword and parenthesized boolean Copyright 1998 by R. Tront 5-25 Copyright 1998 by R. Tront 5-26

14 continuation expression after the loop body. Don t forget the semi-colon after the closing parenthesis. How does the compiler know that this while is not the beginning of some other while loop that comes next? Because it is placed after a do. After any do, the first while encountered by the compiler is not considered the start of a while style loop. This is what is meant by the term syntax analysis, which is done very carefully by the compiler. If I had written the continuation condition as n>=1 (like I did for the while style loop several pages back), 80% of you would not have noticed. In fact, many of you, if writing the do style version of the program, would have possibly used n>=1. But your program would have printed the wrong total! It is very easy to make such exit condition mistakes! I will say that again. It is very easy to make exit condition mistakes! Exercise: Would n > -1 be an acceptable exit condition? Note: There is usually a reason to prefer either while versus do style loops. But for this particular algorithm there is none. When an algorithm can be written either way, though, the exit condition is usually different for the two different styles! Copyright 1998 by R. Tront Loops With Mid-Body Exits In some languages like Modula-2, there are special loops for this. In C++ though, there is just a kludge that will break you out of the middle. char ch; while (true){ fin >> ch; if ( fin.eof() ) break; cout << ch; } What you do is purposely program an infinite loop! The while condition above is always true (it is the boolean literal true ). Then you use an if statement where desired in the middle of the loop to test an exit (not continuation) boolean expression; in the above case, to test whether your last read from a file encountered the end of file (abbreviated in computer science eof). The eof() function of the fin object returns a boolean value which is used by the if. Finally, the keyword break is used as the then clause of the if. You can put the break to the right of the if, but in this class I will insist that it be put right under the Copyright 1998 by R. Tront 5-28

15 w of the while, so you can quickly spot in a long loop body where the loop exit is and what condition caused the exit. Copyright 1998 by R. Tront For Loops All computer languages generally have a for style loops. They are mainly used to have a loop body executed several times with one variable linearly increasing (or decreasing) by one each iteration. C++ s for loop though is quite a bit more flexible than that. In fact, the so called control variable can increase or decrease by any amount. In fact there needn t even be a control variable as long as there is some kind of control expression. Here is an example of a for loop: int n; cout << Type an integer: ; cin >> n; cout << endl << The sum of 1 to << n << is ; int runningtotal = 0; for(int i = n; i>=1; i=i-1){ //note no ; just before the ) runningtotal = runningtotal + i; } cout << runningtotal; This says: for integer variable i starting at n, while i is still greater or equal to 1, execute the body of the loop, and decrement i before starting the loop again. Copyright 1998 by R. Tront 5-30

16 A for loop is a top exit loop. If the exit condition (which may be any boolean expression like x>y) is not satisfied when the for statement is first encountered, the loop body will not be executed even once. Also note the update action i=i-1 is NOT done before the first iteration. We are glad of this because we want the first value added to running total to be n, not one less! Given what I have just said you should be able to see that a for loop is just a different, slightly more compact way of saying the same thing as: int i = n; while (i>=1){ runningtotal = runningtotal + i; i = i-1; } The initializing action is placed before the while, the continuation expression is placed in the while condition, and the update action is put as the last statement of the while loop. Warning #1: In many languages it is forbidden to mess with the control variable in the body of the for loop. This is not the case in C++. But, nonetheless any for loop that messes with the control variable both within the update action and also in the loop body has a much higher likelihood of a mistake that causes the loop to exit at the wrong time or not at all! Warning #2: For all styles of loops, it is wiser to use an inequality in your continuation expression rather than an equality. This is because if you are iterating up your controlvariable from zero by two each time through the loop, and you want to keep going if controlvariable hasn t reached 13 yet (i.e. controlvariable!= 13) your loop will never end. Why? This problem is particularly common when comparing real numbers rather than integer numbers, because round off error can cause two numbers to not quite be the same. e.g. (1/3)*3 is not generally exactly equal to 1. The expression 1/3*3 is , not 1. Warning #4: Though it has always been legal C++ to define a variable right after the ( of while and for loops, only in the 1998 compilers is the scope of this variable just that of the loop body. In older compilers, the variable is also valid outside the loop and will conflict with another variable with the same name which is defined outside the loop. Copyright 1998 by R. Tront 5-31 Copyright 1998 by R. Tront 5-32

### 3. Simple Types, Variables, and Constants

3. Simple Types, Variables, and Constants This section of the lectures will look at simple containers in which you can storing single values in the programming language C++. You might find it interesting

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

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

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

Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style 3 2.1 Variables and Assignments Variables and

Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2

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

Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful

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

Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls

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

### Chapter 2. C++ Basics

Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-2 2.1 Variables and Assignments Variables

### Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

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

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

### School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

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

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

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

Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Copyright 2011 Pearson Addison-Wesley. All rights

CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 2 : C# Language Basics Lecture Contents 2 The C# language First program Variables and constants Input/output Expressions and casting

### Announcements. Homework 0: using cin with 10/3 is NOT the same as (directly)

Branching Announcements Homework 0: using cin with 10/3 is NOT the same as 3.3333 (directly) With cin, it will stop as soon as it reaches a type that does not match the variable (into which it is storing)

### PIC 10A Flow control. Ernest Ryu UCLA Mathematics

PIC 10A Flow control Ernest Ryu UCLA Mathematics If statement An if statement conditionally executes a block of code. # include < iostream > using namespace std ; int main () { double d1; cin >> d1; if

### Software Design & Programming I

Software Design & Programming I Starting Out with C++ (From Control Structures through Objects) 7th Edition Written by: Tony Gaddis Pearson - Addison Wesley ISBN: 13-978-0-132-57625-3 Chapter 4 Making

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

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

### 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,

### LESSON 3. In this lesson you will learn about the conditional and looping constructs that allow you to control the flow of a PHP script.

LESSON 3 Flow Control In this lesson you will learn about the conditional and looping constructs that allow you to control the flow of a PHP script. In this chapter we ll look at two types of flow control:

Chapter 2 Flow of Control Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Boolean Expressions Building, Evaluating & Precedence Rules Branching Mechanisms if-else switch Nesting if-else

### CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started Handout written by Julie Zelenski, Mehran Sahami, Robert Plummer, and Jerry Cain. After today s lecture, you should run home and read

### bool bool - either true or false

Strings & Branching bool bool - either true or false You have the common math comparisons: > (greater than), e.g. 7 > 2.5 is true == (equals), e.g. 5 == 4 is false

### 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.,

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

KEY CONCEPTS COMP 10 EXPLORING COMPUTER SCIENCE Lecture 2 Variables, Types, and Programs Problem Definition of task to be performed (by a computer) Algorithm A particular sequence of steps that will solve

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

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

### Announcements. HW0 is posted on schedule, due next Friday at 9pm (pretty easy)

Branching Announcements HW0 is posted on schedule, due next Friday at 9pm (pretty easy) Office hours (attempt problems before going): - HW only or Lab only (check calendar) - Write name on whiteboard if

### These are notes for the third lecture; if statements and loops.

These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern

### 8. Control statements

8. Control statements A simple C++ statement is each of the individual instructions of a program, like the variable declarations and expressions seen in previous sections. They always end with a semicolon

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

Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate

### LOOPS. Repetition using the while statement

1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

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

### 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;

### C++ Programming Lecture 1 Software Engineering Group

C++ Programming Lecture 1 Software Engineering Group Philipp D. Schubert Contents 1. More on data types 2. Expressions 3. Const & Constexpr 4. Statements 5. Control flow 6. Recap More on datatypes: build-in

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

Comp Sci 1570 Introduction to C++ Outline 1 Outline 1 Outline 1 switch ( e x p r e s s i o n ) { case c o n s t a n t 1 : group of statements 1; break ; case c o n s t a n t 2 : group of statements 2;

### Boolean Algebra Boolean Algebra

What is the result and type of the following expressions? Int x=2, y=15; float u=2.0, v=15.0; -x x+y x-y x*v y / x x/y y%x x%y u*v u/v v/u u%v x * u (x+y)*u u / (x-x) x++ u++ u = --x u = x -- u *= ++x

### 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)

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

### CSI33 Data Structures

Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2018 Outline Outline 1 Chapter 8: A C++ Introduction For Python Programmers Expressions and Operator Precedence

### Conditionals and Loops

Conditionals and Loops Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing steps in a loop Chapter 5 focuses on: boolean expressions conditional

### UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . \$, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

### Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

Numerical Computing in C and C++ Jamie Griffin Semester A 2017 Lecture 2 Visual Studio in QM PC rooms Microsoft Visual Studio Community 2015. Bancroft Building 1.15a; Queen s W207, EB7; Engineering W128.D.

### Chapter Goals. Contents LOOPS

CHAPTER 4 LOOPS Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30, 2011 Chapter Goals To implement while, for, and do loops To hand-trace the execution of a program To become familiar with common

### 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)

### 3 The L oop Control Structure

3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

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

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

### Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

### Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

### Relational Operators and if. Class 10

Relational Operators and if Class 10 Data Type a data type consists of two things: Data Type a data type consists of two things: a set of values Data Type a data type consists of two things: a set of values

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

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

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

### CHAPTER : 9 FLOW OF CONTROL

CHAPTER 9 FLOW OF CONTROL Statements-Statements are the instructions given to the Computer to perform any kind of action. Null Statement-A null statement is useful in those case where syntax of the language

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

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

### Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

First Program Compilation and Execution Simplifying Fractions Loops If Statements Variables Operations Using Functions Errors C++ programs consist of a series of instructions written in using the C++ syntax

### Computational Physics - Fortran February 1997

Fortran 90 Decision Structures IF commands 3 main possibilities IF (logical expression) IF (logical expression) THEN IF (logical expression) THEN IF (logical expression) THEN expression TRUE expression

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

Logical Operators and if/ statement 1 If Statement We may want to execute some code if an expression is true, and execute some other code when the expression is false. This can be done with two if statements

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

### Introduction to Programming using C++

Introduction to Programming using C++ Lecture One: Getting Started Carl Gwilliam gwilliam@hep.ph.liv.ac.uk http://hep.ph.liv.ac.uk/~gwilliam/cppcourse Course Prerequisites What you should already know

### (Refer Slide Time: 01:12)

Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #22 PERL Part II We continue with our discussion on the Perl

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

Computer Programming Basic Control Flow - Decisions Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To be able to implement decisions using if statements To learn

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

### DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA S o far all the programs we have created run straight through from start to finish, without making any decisions along the way. Many times, however, you

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

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

### Operators. Java operators are classified into three categories:

Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

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

### CSE 452: Programming Languages. Outline of Today s Lecture. Expressions. Expressions and Control Flow

CSE 452: Programming Languages Expressions and Control Flow Outline of Today s Lecture Expressions and Assignment Statements Arithmetic Expressions Overloaded Operators Type Conversions Relational and

### Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

Control Structures Code can be purely arithmetic assignments At some point we will need some kind of control or decision making process to occur C uses the if keyword as part of it s control structure

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

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

### Programming, numerics and optimization

Programming, numerics and optimization Lecture A-2: Programming basics II Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428 March

### Intro. Scheme Basics. scm> 5 5. scm>

Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

### Boolean Expressions. Is Equal and Is Not Equal

3 MAKING CHOICES Now that we ve covered how to create constants and variables, you re ready to learn how to tell your computer to make choices. This chapter is about controlling the flow of a computer

### Hardware versus software

Logic 1 Hardware versus software 2 In hardware such as chip design or architecture, designs are usually proven to be correct using proof tools In software, a program is very rarely proved correct Why?

### Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

CS 170 Java Programming 1 The Switch Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Menu-Style Code With ladder-style if-else else-if, you might sometimes find yourself writing menu-style

### Boolean Expressions. Is Equal and Is Not Equal

3 MAKING CHOICES ow that we ve covered how to create constants and variables, you re ready to learn how to tell your computer to make choices. This chapter is about controlling the flow of a computer program

### Chapter Four: Loops II

Chapter Four: Loops II Slides by Evan Gallagher & Nikolay Kirov Chapter Goals To understand nested loops To implement programs that read and process data sets To use a computer for simulations Processing

### Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Chapter 2 Control, Quick Overview Control Selection Selection Selection is how programs make choices, and it is the process of making choices that provides a lot of the power of computing 1 Python if statement

### B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

### Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Loops and Conditionals HORT 59000 Lecture 11 Instructor: Kranthi Varala Relational Operators These operators compare the value of two expressions and returns a Boolean value. Beware of comparing across

### If Control Construct

If Control Construct A mechanism for deciding whether an action should be taken JPC and JWD 2002 McGraw-Hill, Inc. 1 Boolean Algebra Logical expressions have the one of two values - true or false A rectangle

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

Chapter Four: Loops Slides by Evan Gallagher The Three Loops in C++ C++ has these three looping statements: while for do The while Loop while (condition) { statements } The condition is some kind of test

### More Programming Constructs -- Introduction

More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

### CPS122 Lecture: From Python to Java last revised January 4, Objectives:

Objectives: CPS122 Lecture: From Python to Java last revised January 4, 2017 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

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

C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

### CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

### Python for Informatics

Python for Informatics Exploring Information Version 0.0.6 Charles Severance Chapter 3 Conditional execution 3.1 Boolean expressions A boolean expression is an expression that is either true or false.

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

### C/C++ Programming Lecture 7 Name:

1. The increment (++) and decrement (--) operators increase or decrease a variable s value by one, respectively. They are great if all you want to do is increment (or decrement) a variable: i++;. HOWEVER,