Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering

Slides:



Advertisements
Similar presentations
A number of MATLAB statements that allow us to control the order in which statements are executed in a program. There are two broad categories of control.
Advertisements

MATLAB Examples. CS 1112 MATLAB Examples Find the number of positive numbers in a vector x = input( 'Enter a vector: ' ); count = 0; for ii = 1:length(x),
Programming Logic and Design Eighth Edition
CS0004: Introduction to Programming Repetition – Do Loops.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Arrays Revisited Selim Aksoy Bilkent University Department of Computer Engineering
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
MATLAB Review Selim Aksoy Bilkent University Department of Computer Engineering
Loops – While, Do, For Repetition Statements Introduction to Arrays
Week 7 - Programming I Relational Operators A > B Logical Operators A | B For Loops for n = 1:10 –commands end.
Top-down Program Design, Relational and Logical Operators
Making Decisions In Python
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Chapter 4 MATLAB Programming Logical Structures Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
Week 7 - Programming II Today – more features: – Loop control – Extending if/else – Nesting of loops Debugging tools Textbook chapter 7, pages
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
The switch Statement, DecimalFormat, and Introduction to Looping
Loops are MATLAB constructs that permit us to execute a sequence of statements more than once. There are two basic forms of loop constructs: i. while.
Implementing Control Logic in C# Svetlin Nakov Telerik Corporation
Fundamentals of Python: From First Programs Through Data Structures
Fundamentals of Python: First Programs
Essential MATLAB® for Engineers and Scientists
Spring 2005, Gülcihan Özdemir Dağ Lecture 3, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 3 Outline 3.1 Introduction.
Slide deck by Dr. Greg Reese Miami University MATLAB An Introduction With Applications, 5 th Edition Dr. Amos Gilat The Ohio State University Chapter 6.
Selection Programming EE 100. Outline introduction Relational and Logical Operators Flow Control Loops Update Processes.
COIT29222 Structured Programming Slide 1 COIT29222-Structured Programming Lecture Week 06  Reading: Study Guide Book 2, Modules 9 & 10 Textbook (4 th.
MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Flow of Control Part 1: Selection
CMPS 1371 Introduction to Computing for Engineers CONDITIONAL STATEMENTS.
Programming Logic and Design Sixth Edition Chapter 5 Looping.
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (4): Control Flow (Chapter 2)
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Chapter 3. Control Structures and Program Design ► Two broad categories of control statement:  Branches  Loops ► These will make the program more complex.
MATLAB 及其工程应用 MATLAB and It’s Engineering Application 主讲教师: 胡章芳
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Matlab Programming for Engineers
1 CS1371 Introduction to Computing for Engineers Control Statements 9/4/2003.
Introduction to Computer Sciences References: [1] Fortran 95/2003 for Scientists and Engineers (3e) by Stephen J. Chapman. [2] Using Fortran 90 by Chester.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 3 Friday 03 Oct 2014 EGR 115 Introduction to Computing for Engineers.
September 7, 2004ICP: Chapter 3: Control Structures1 Introduction to Computer Programming Chapter 3: Control Structures Michael Scherger Department of.
Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1.
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 4 Monday 06 Oct 2014 EGR 115 Introduction to Computing for Engineers.
Controlling Program Flow with Decision Structures.
Interduction to MATLAB (part 2) Manal Alotaibi Mathematics department College of science King saud university.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
CSE123 - Lecture 4 Structured Programming- Loops.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
REPETITION CONTROL STRUCTURE
CS1100 Computational Engineering
Types of Flow of Control
3 Control Statements:.
Loop Statements & Vectorizing Code
Matlab Basics.
Loop Statements & Vectorizing Code
REPETITION Why Repetition?
Presentation transcript:

Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering

Fall 2004CS 1112 Branches Branches are used to select and execute specific sections of the code while skipping other sections Selection of different sections depend on a condition statement We will learn: if statement switch statement

Fall 2004CS 1113 Branches: “if” Statement if ( condition ), statement 1 statement 2... end condition statement group true false statement group

Fall 2004CS 1114 Branches: “if” Statement Conditions can be: any real value (0 is false, non-zero is true) combination of relational and logical operators e.g. ( x > 0 ) & ( x < 10 ) logical functions isempty() isnumeric(), ischar() isinf(), isnan() exist()

Fall 2004CS 1115 Branching Examples Examples: if ( r <= 0 ), disp( ‘Radius must be positive’ ); end if ( ( grade 100 ) ), disp( ‘Grade must be in [0,100] range’ ); end if isinf( result ), disp( ‘Result is infinite’ ); end

Fall 2004CS 1116 Branching Examples Water tank example: r = input('Enter the radius of the tank base (in meters):'); if ( r 0 ), disp( [ 'There is ' num2str(space) ' m3 extra space' ] ); else disp( 'Tank is full' ); end

Fall 2004CS 1117 Branches: “if-else” Statement if ( condition ), statement 1 statement 2... else statement 1 statement 2... end condition statement group 1 truefalse statement group 2 statement group 1 statement group 2

Fall 2004CS 1118 Branching Examples Example: Assigning letter grades How can we compute the letter corresponding to a given numeric grade? RangeGrade 100  grade > 95 A 95  grade > 86 B 86  grade > 76 C 76  grade > 66 D 66  grade > 0 F

Fall 2004CS 1119 Branching Examples if ( grade > 95 ), disp( ‘Grade is A’ ); else if ( grade > 86 ), disp( ‘Grade is B’ ); else if ( grade > 76 ), disp( ‘Grade is C’ ); else if ( grade > 66 ), disp( ‘Grade is D’ ); else disp( ‘Grade is F’ ); end nested if statements

Fall 2004CS Branches: “if-elseif-else” Statement if ( condition 1 ), statement 1 statement 2... elseif ( condition 2 ), statement 1 statement 2... else statement 1 statement 2... end statement group 1 condition 1 statement group 1 truefalse condition 2 statement group 2 statement group 3 truefalse statement group 2 statement group 3

Fall 2004CS Branching Examples Letter grade example: if ( grade > 95 ), disp( ‘Grade is A’ ); elseif ( grade > 86 ), disp( ‘Grade is B’ ); elseif ( grade > 76 ), disp( ‘Grade is C’ ); elseif ( grade > 66 ), disp( ‘Grade is D’ ); else disp( ‘Grade is F’ ); end

Fall 2004CS Branching Examples Example: Finding roots of the quadratic equation “ax 2 + bx + c = 0” Pseudocode: d = b 2 – 4ac if d > 0, two real roots else if d == 0, two identical roots else two complex roots

Fall 2004CS Branching Examples % Prompt the user for the coefficients of the equation disp ('This program solves for the roots of a quadratic '); disp ('equation of the form A*X^2 + B*X + C = 0. '); a = input ('Enter the coefficient A: '); b = input ('Enter the coefficient B: '); c = input ('Enter the coefficient C: '); % Calculate discriminant discriminant = b^2 - 4 * a * c; % Solve for the roots, depending on the value of the discriminant if discriminant > 0 % there are two real roots, so... x1 = ( -b + sqrt(discriminant) ) / ( 2 * a ); x2 = ( -b - sqrt(discriminant) ) / ( 2 * a ); disp ('This equation has two real roots:'); fprintf ('x1 = %f\n', x1); fprintf ('x2 = %f\n', x2); elseif discriminant == 0 % there is one repeated root, so... x1 = ( -b ) / ( 2 * a ); disp ('This equation has two identical real roots:'); fprintf ('x1 = x2 = %f\n', x1); else % there are complex roots, so... real_part = ( -b ) / ( 2 * a ); imag_part = sqrt ( abs ( discriminant ) ) / ( 2 * a ); disp ('This equation has complex roots:'); fprintf('x1 = %f +i %f\n', real_part, imag_part ); fprintf('x2 = %f -i %f\n', real_part, imag_part ); end

Fall 2004CS Branching Examples Example: Decision for playing tennis outlook sunnyovercastrain humiditywind highlowstrongweak don’t play tennis play tennis don’t play tennis play tennis

Fall 2004CS Branching Examples outlook = input( ‘How is the outlook? (o)vercast, (s)unny, (r)ainy: ‘, ‘s’ ); if ( outlook == ‘o’ ), disp( ‘You can play tennis’ ); elseif ( outlook == ‘s’ ), humidity = input( ‘How is humidity? (h)igh, (l)ow: ‘, ‘s’ ); if ( humidity == ‘h’ ), disp('I do not recommend you play tennis’ ); elseif ( humidity == ‘l’ ), disp( ‘You can play tennis’ ); else disp( ‘Invalid humidity info’ ); end elseif ( outlook == ‘r’ ), wind = input( ‘How is the wind? (s)trong, (w)eak: ‘, ‘s’ ); if ( wind == ‘s’ ), disp( ‘I do not recommend you play tennis’ ); elseif (wind == ‘w’ ), disp( ‘You can play tennis’ ); else disp( ‘Invalid wind info’ ); end else disp( ‘Invalid outlook info’ ); end

Fall 2004CS Branching Examples outlook = input( ‘How is the outlook? (o)vercast, (s)unny, (r)ainy: ‘, ‘s’ ); if ( outlook == ‘o’ ), disp( ‘You can play tennis’ ); elseif (outlook == 's'), humidity = input( ‘How is humidity? (h)igh, (l)ow: ‘, ‘s’ ); if ( humidity == ‘h’ ), disp('I do not recommend you play tennis’ ); elseif ( humidity == ‘l’ ), disp( ‘You can play tennis’ ); else disp( ‘Invalid humidity info’ ); end elseif ( outlook == ‘r’ ), wind = input( ‘How is the wind? (s)trong, (w)eak: ‘, ‘s’ ); if ( wind == ‘s’ ), disp( ‘I do not recommend you play tennis’ ); elseif (wind == ‘w’ ), disp( ‘You can play tennis’ ); else disp( ‘Invalid wind info’ ); end else disp( ‘Invalid outlook info’ ); end indentation is important for understandability

Fall 2004CS Branches: “switch” Statement switch ( expression ), case value 1, statement 1 statement 2... case value 2, statement 1 statement 2... end statement group 1 statement group 2  expression is a scalar or string constant

Fall 2004CS Branches: “switch” Statement switch ( expression ), case {value set 1}, statement 1 statement 2... case {value set 2}, statement 1 statement 2... otherwise, statement 1 statement 2... end statement group 1 statement group 2 optional statement group that is executed if none of the cases is satisfied

Fall 2004CS Branching Examples Example: Odd or even numbers switch (value), case {1,3,5,7,9}, disp( ‘Odd number’ ); case {2,4,6,8,10}, disp( ‘Even number’ ); otherwise, disp( ‘Out of range’ ); end

Fall 2004CS Branching Examples Example: Unit converter x = input( ‘length (in cm): ‘ ); u = input( ‘unit: ‘, ‘s’ ); switch (u), case { ‘cm’, ’centimeter’ }, disp( [ num2str(x) ‘cm’ ] ); case { ‘mm’, ’millimeter’ }, disp( [ num2str(10*x) ‘mm’ ] ); case { ‘m’, ’meter’ }, disp( [ num2str(x/100) ‘m’ ] ); case { ‘in’, ’inch’ }, disp( [ num2str(2.54*x) ‘in’ ] ); otherwise, disp( ‘Unknown unit’ ); end

Fall 2004CS Loops Loops are used to execute a sequence of statements more than once We will learn: while loop for loop They differ in how the repetition is controlled

Fall 2004CS Loops: “while” Loop Statements are executed indefinitely as long as the condition is satisfied while ( condition ), statement 1 statement 2... end statement group condition statement group true false

Fall 2004CS Loop Examples Example: Arithmetic mean and standard deviation of non-negative measurements Pseudocode: Initialize sum_x, sum_x2, n Read first value, x while x >= 0, n  n + 1 sum_x  sum_x + x sum_x2  sum_x2 + x^2 Read next value, x end x_mean  sum_x / n x_std  sqrt( ( n * sum_x2 – sum_x^2 ) / ( n * (n-1) ) ) Display results to the user

Fall 2004CS Loop Examples % Initialize sums. n = 0; sum_x = 0; sum_x2 = 0; % Read in first value x = input('Enter first value: '); % While Loop to read input values. while x >= 0 % Accumulate sums. n = n + 1; sum_x = sum_x + x; sum_x2 = sum_x2 + x^2; % Read in next value x = input('Enter next value: '); end % Calculate the mean and standard deviation x_bar = sum_x / n; std_dev = sqrt( (n * sum_x2 - sum_x^2) / (n * (n-1)) ); % Tell user. fprintf('The mean of this data set is: %f\n', x_bar); fprintf('The standard deviation is: %f\n', std_dev); fprintf('The number of data points is: %f\n', n);

Fall 2004CS Loops: “for” Loop Statements are executed a specified number of times for index = expression, statement 1 statement 2... end Expression is usually a vector in shortcut notation first:increment:last statement group

Fall 2004CS Loop Examples Example: for x = 1:2:10, x end Output: x = 1 x = 3 x = 5 x = 7 x = 9

Fall 2004CS Loop Examples Example: for x = [ ], x end Output: x = 1 x = 5 x = 13

Fall 2004CS Loop Examples Example: for x = [ 1 2 3; ], x end Output: x = 1 4 x = 2 5 x = 3 6

Fall 2004CS Loop Examples Example: Factorial (n!) of an integer n n = input( ‘Please enter n: ‘ ); if ( ( n < 0 ) | ( fix(n) ~= n ) ), error( ‘n must be a non-negative integer’ ); end if ( ( n == 0 ) | ( n == 1 ) ), f = 1; else f = 1; for ii = 2:n, f = f * ii; end end

Fall 2004CS Loop Examples Example: Arithmetic mean and standard deviation of non-negative measurements Pseudocode: Initialize sum_x, sum_x2 Read the number of measurements, n for ii = 1:n, Read value, x sum_x  sum_x + x sum_x2  sum_x2 + x^2 end x_mean  sum_x / n x_std  sqrt( ( n * sum_x2 – sum_x^2 ) / ( n * (n-1) ) ) Display results to the user

Fall 2004CS Loop Examples % Initialize sums. sum_x = 0; sum_x2 = 0; % Get the number of points to input. n = input('Enter number of points: '); % Check to see if we have enough input data. if n < 2 % Insufficient data disp ('At least 2 values must be entered.'); else % we will have enough data, so let's get it. % Loop to read input values. for ii = 1:n % Read in next value x = input('Enter value: '); % Accumulate sums. sum_x = sum_x + x; sum_x2 = sum_x2 + x^2; end % Now calculate statistics. x_bar = sum_x / n; std_dev = sqrt( (n * sum_x2 - sum_x^2) / (n * (n-1)) ); % Tell user. fprintf('The mean of this data set is: %f\n', x_bar); fprintf('The standard deviation is: %f\n', std_dev); fprintf('The number of data points is: %f\n', n); end

Fall 2004CS Loop Examples Example: Guessing a number computer picks between 1 and 10 Pseudocode: Pick a random number, num, in [1,10] Read user’s guess while ( guess ~= num ), Read user’s new guess end

Fall 2004CS Loop Examples num = round( (10-1) * rand + 1 ); guess = input( 'Your guess?' ); tries = 1; while ( guess ~= num ), guess = input( 'Your guess?' ); tries = tries + 1; end fprintf( 'You guessed correctly in %d tries', tries );

Fall 2004CS Loop Examples Number guessing example: User has only 3 tries Pseudocode: Pick a random number, num, in [1,10] Read user’s guess Initialize number of tries to 1 while ( ( guess ~= num ) & ( tries < 3 ) ), Read user’s new guess Increment number of tries end

Fall 2004CS Loop Examples num = round( (10-1) * rand + 1 ); guess = input( 'Your guess?' ); tries = 1; while ( ( guess ~= num ) & ( tries < 3 ) ), guess = input( 'Your guess?' ); tries = tries + 1; end if ( guess == num ), disp( 'Congratulations!' ); else disp( 'You could not guess correctly' ); end

Fall 2004CS Loop Examples Example: Nested loops for ii = 1:3, for jj = 1:5, p = ii * jj; fprintf( '%d x %d = %d\n', ii, jj, p ); end end

Fall 2004CS Loops: “break/continue” Statements Break statement terminates the execution of a loop and passes the control to the next statement after the end of the loop Continue statement terminates the current pass through the loop and returns control to the top of the loop

Fall 2004CS Loop Examples Example: for ii = 1:5, if ( ii == 3 ), break; end fprintf( 'ii = %d\n', ii ); end disp( 'End of loop' ); Output: ii = 1 ii = 2 End of loop

Fall 2004CS Loop Examples Example: for ii = 1:5, if ( ii == 3 ), continue; end fprintf( 'ii = %d\n', ii ); end disp( 'End of loop' ); Output: ii = 1 ii = 2 ii = 4 ii = 5 End of loop

Fall 2004CS Loop Examples Number guessing example: User has only 3 tries Pseudocode: Pick a random number, num, in [1,10] for tries = 1:3, Read user’s new guess Stop if guess is correct end

Fall 2004CS Loop Examples num = round( (10-1) * rand + 1 ); for tries = 1:3, guess = input( 'Your guess?' ); if ( guess == num ), disp( 'Congratulations!' ); break; end if ( guess ~= num ), disp( 'You could not guess correctly' ); end

Fall 2004CS Advice Use indentation to improve the readability of your code Never modify the value of a loop index inside the loop Allocate all arrays used in a loop before executing the loop If it is possible to implement a calculation either with a loop or using vectors, always use vectors Use built-in MATLAB functions as much as possible instead of reimplementing them