SFU CMPT Topic: Control Statements

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

Introduction. C provides two styles of flow control:

LECTURE 5 Control Structures Part 2

CSI33 Data Structures

Chapter 5: Control Structures II (Repetition)

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

Add Subtract Multiply Divide

Why Is Repetition Needed?

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

The following expression causes a divide by zero error:

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

REPETITION CONTROL STRUCTURE LOGO

Chapter 4 - Notes Control Structures I (Selection)

Chapter 7. Additional Control Structures

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

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

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

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

5. Selection: If and Switch Controls

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

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

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

SFU CMPT Topic: Compound Types

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

Flow Control. CSC215 Lecture

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

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

In this chapter you will learn:

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

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

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

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

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

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

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

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17)

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Programming for Engineers Iteration

INTRODUCTION TO COMPUTER SCIENCE - LAB

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

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

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

Computer Programming : C++

DECISION CONTROL AND LOOPING STATEMENTS

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

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

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

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

Data Types and Variables in C language

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

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

Unit 7. 'while' Loops

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

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

DELHI PUBLIC SCHOOL TAPI

CHAPTER : 9 FLOW OF CONTROL

CSCE 206: Structured Programming in C++

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

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

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

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

Getting started with C++ (Part 2)

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

Lecture 3 Tao Wang 1

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

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

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

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

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

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

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake

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

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

204111: Computer and Programming

ENGR 1181 MATLAB 09: For Loops 2

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

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++.

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

Module 4: Decision-making and forming loops

Control Structures of C++ Programming (2)

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

5. Control Statements

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

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

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

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Test Results Schedule Miscellanea Control Structs. Add l Oper s Break Hands on Q & A Conclusion References Files

Introduction to Programming I COS1511 School of Computing Revision Notes

Technical Questions. Q 1) What are the key features in C programming language?

Complex data types Structures Defined types Structures and functions Structures and pointers (Very) brief introduction to the STL

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

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

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

Boolean Data-Type. Boolean Data Type (false, true) i.e. 3/6/2018. The type bool is also described as being an integer: bool bflag; bflag = true;

Introduction to Programming

Looping. Arizona State University 1

Transcription:

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 Control Statements control the flow of the program: which code parts of code are executed and how many times conditional (selection) statements: if... else switch repetition statements (loops) for while do... while

SFU CMPT-212 2008-1 3 Topic: Control Statements if 1 if ( condition ) 2 statement Example: 1 if ( grade >= 60 ) 2 cout <<"Passed"; Conditional Statements if... else 1 if ( condition ) 2 statement_true 3 else 4 statement_false Example: 1 if ( grade >= 60 ) 2 cout <<"Passed"; 3 else 4 cout <<"Failed";

SFU CMPT-212 2008-1 4 Topic: Control Statements Compound Statements Blocks A compound statement or block is a sequence of statements enclosed in curly brackets ({...}). Example: 1 if ( grade >= 60 ) { 2 passing++; 3 cout <<"Pased"; 4 } Note: variables declared inside of a block, exist only inside of the block Example: 1 int x = 20; 2 { 3 cout << x << endl; // prints 20 4 int x = 100; 5 cout << x << endl; // prints 100 6 } 7 cout << x << endl; // prints 20

SFU CMPT-212 2008-1 5 Topic: Control Statements Nested if... else statements Question: what s wrong with the following code? 1 if ( x>5 ) 2 if ( y>5 ) 3 cout << "x and y are > 5"; 4 else 5 cout << "x is <= 5";

SFU CMPT-212 2008-1 6 Topic: Control Statements Nested if... else statements Answer: else is binding with the closest if, hence the correct formatting should be: 1 if ( x>5 ) 2 if ( y>5 ) 3 cout << "x and y are > 5"; 4 else 5 cout << "x is <= 5"; Question: How to fix the code so that it does what intended?

SFU CMPT-212 2008-1 7 Topic: Control Statements Nested if... else statements Answer: 1 if ( x>5 ) { 2 if ( y>5 ) 3 cout << "x and y are > 5"; 4 } else 5 cout << "x is <= 5";

SFU CMPT-212 2008-1 8 Topic: Control Statements the conditional operator?: 1 condition? expression_if_true : expression_if_false Example: 1 c = a>b? a : b; is equivalent to 1 if (a>b) 2 c = a; 3 else 4 c = b; Note:?: operator with three operands forms an expression More complicated example: 1 m = a>b? a>c? a : c : b>c? b : c;

SFU CMPT-212 2008-1 9 Topic: Control Statements Conditions any expressions which evaluates to a bool value (true or false); Remember: C++ can automatically convert any non-zero integer value to true and zero integer value to false relational expressions: <, <=, ==, >, >=,!= logical expressions: (logical OR), && (logical AND),! (logical NOT) Comments: do not mix the assignment operator = and the is-equal-to operator == the expression on the right of the operator is not evaluated if the expression on the left is true the expression on the right of the && operator is not evaluated if the expression on the left is false

SFU CMPT-212 2008-1 10 Topic: Control Statements Comparing strings Example: 1 char a[20]; 2 cin >> a; 3 4 if (a == "password") 5 cout <<"Access granted."<<endl; Doesn t work! What s wrong? Example: compstr.cpp Note: strcmp(str1,str2) returns ¼ if str1 precedes str2 in alphabetical order ¼ if strings str1 and str2 are identical ¼ if str2 precedes str1 in alphabetical order

SFU CMPT-212 2008-1 11 Topic: Control Statements switch 1 switch ( integer_expression ) { 2 case constant_1: 3 statements_1; 4 break; 5 case constant_2_1: 6 case constant_2_2: 7 statements_2; 8 break; 9... 10 default: 11 statements_default; 12 } Note. Not including break at the end of a case will cause the execution of all instructions until the next break or the end of the switch statement. Example: switch.cpp

SFU CMPT-212 2008-1 12 Topic: Control Statements Sample questions Assume that in the following statement a, b, c and m are integers: 1 m = a<b? b<c? b : a<c? c : a : a<c? a : b<c? c : b; What is the value of m (depending on values of a, b and c) after executing of the statement? Write a code performing the same task without using the?: operator.

SFU CMPT-212 2008-1 13 Topic: Control Statements What is the output of the following code? 1 int a, b=5; 2 cin >> a; 3 if ( (a==2) && (b=a) ) 4 cout <<"ok "; 5 cout <<a<<" "<<b; Rewrite the following code without using switch statement: 1 switch (val) 2 { 3 case 2: 4 cout << "case 2\n"; 5 case 3: 6 cout << "case 3\n"; 7 break; 8 case 4: 9 case 5: 10 cout << "case 4\n"; 11 break; 12 default: 13 cout << "switch default\n"; 14 }

SFU CMPT-212 2008-1 14 Topic: Control Statements where to find functions MSDN of MS Visual C++ References C++ language reference: http://www.cs.iastate.edu/ leavens/larchc++manual/lcpp toc.html standard libraries: http://www.cppreference.com/ standard libraries: http://www.cplusplus.com/ref/ (not complete) some other libraries (e.g., for working with directories, signals, etc) can be found here: http://www.informit.com/guides/guide.asp?g=cplusplus&rl=1

SFU CMPT-212 2008-1 15 Topic: Control Statements Repetition statements (loops) C++ accept three types of loops: for loop 1 for ( initialization; condition; update_statement ) 2 statement while loop 1 while ( loop_condition ) 2 statement do... while loop 1 do 2 statement 3 while ( loop_condition );

SFU CMPT-212 2008-1 16 Topic: Control Statements For loop 1 for ( initialization ; condition ; update_statement ) 2 statement Steps: 1. initialization (typically set up a loop variable) 2. test the loop condition; if false exit, otherwise continue with next step 3. execute the statement of the loop 4. update (typically increment (decrement or otherwise modify) the loop variable) 5. continue with step 2. Example: forloop.cpp [Prata]

SFU CMPT-212 2008-1 17 Topic: Control Statements Comments: the loop variable(s) can be initialized directly in the loop statement Example: 1 for (int i = 0; i < 5; i++) 2 cout << i <<" C++ knows loops.\n"; according to C++ standard, variable i exists only inside of the loop Example 1: two consecutive loops (can be compiled on standard compliant compiler) (forlooptwice.cpp) 1 for (int i = 0; i < 5; i++) 2 cout << i; 3 for (int i = 0; i < 5; i++) 4 cout << i; Example 2: incorrect code (however, only this version can be compiled with MS Visual C++ 6.0) 1 for (int i = 0; i < 5; i++) 2 cout << i; 3 for (i = 0; i < 5; i++) 4 cout << i;

SFU CMPT-212 2008-1 18 Topic: Control Statements For loop and the comma operator 1 for ( initialization ; condition ; update_statement ) 2 statement Note: each initialization, condition and update_statement has to be one single statement or expression (you cannot use a block). But you can use the comma operator, to use multiply statements: i++, j-- the expressions are evaluated from left to right the value of a comma expression is the value of the last expression Example: i=1, j=i+2, k=j+3 will set i to 1, j to 3 and k to 6, and the value of the expression will be 6 Example: comma.cpp, forstr2.cpp [Prata]

SFU CMPT-212 2008-1 19 Topic: Control Statements While loops 1 while (condition) 2 statement is equivalent to 1 for ( ; condition; ) 2 statement 1 do 2 statement 3 while (condition); is an exit-condition loop. The statement gets executed at least once (disregard whether condition is true or not). Steps: 1. execute statement 2. test the condition; if false exit, otherwise continue with step 1.

SFU CMPT-212 2008-1 20 Topic: Control Statements Break, continue Note. Alternately, loops can be terminated using the break keyword, which will end the nearest enclosing switch or loop statement. Example: 1 int number,sum=0; 2 for (;;) { 3 cin >>number; 4 if (number<0) 5 break; 6 sum=sum+number; 7 } Note. The remaining part of the body of the loop can be skipped by using the continue keyword. The control proceeds with the next iteration (with testing the condition in while loops and with the update statement in a for loop). Example: continue.cpp

SFU CMPT-212 2008-1 21 Topic: Control Statements Sample questions Simulate the for loop with a while loop. What are the values of i, j and k after executing the following code? 1 int i,j,k; 2 i=(i=1, j=2*i+1, k=j-i); What is the difference between the while and do...while loops? Write a code which prints the following output: * *** ***** where the number of rows is k. In the example k=3. Use only two loops! What does continue statement do?