Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

Similar documents
Programming for Experimental Research. Flow Control

Computer Programming ECIV 2303 Chapter 6 Programming in MATLAB Instructor: Dr. Talal Skaik Islamic University of Gaza Faculty of Engineering

COGS 119/219 MATLAB for Experimental Research. Fall 2016 Week 1 Built-in array functions, Data types.m files, begin Flow Control

ENGR 1181 MATLAB 09: For Loops 2

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

21-Loops Part 2 text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie

Programming in MATLAB Part 2

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

Loops / Repetition Statements

Chapter 7: Programming in MATLAB

Chapter 4: Programming with MATLAB

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

This is the basis for the programming concept called a loop statement

CS 221 Lecture. Tuesday, 11 October 2011

Branches, Conditional Statements

SECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB

Chapter 4 C Program Control

REPETITION CONTROL STRUCTURE LOGO

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

SECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing

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.

Repetition Structures Chapter 9

Introduction to Matlab. By: Hossein Hamooni Fall 2014

Introduction. C provides two styles of flow control:

Lecture 10. Daily Puzzle

Programming for Engineers Iteration

Computers and FORTRAN Language Fortran 95/2003. Dr. Isaac Gang Tuesday March 1, 2011 Lecture 3 notes. Topics:

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Attia, John Okyere. Control Statements. Electronics and Circuit Analysis using MATLAB. Ed. John Okyere Attia Boca Raton: CRC Press LLC, 1999

LOOPS. Repetition using the while statement

REPETITIVE EXECUTION: LOOPS

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

MODULE 2: Branching and Looping

Chapter 5: Control Structures

CMPT 102 Introduction to Scientific Computer Programming

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

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

Chapter 4: Control structures. Repetition

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

Chapter Goals. Contents LOOPS

LECTURE 5 Control Structures Part 2

Day06 A. Young W. Lim Mon. Young W. Lim Day06 A Mon 1 / 16

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Loops / Repetition Statements

Chapter 3 Structured Program Development

Chapter 4: Control structures

Lecture 7 Tao Wang 1

STUDENT LESSON A12 Iterations

Programming for Electrical and Computer Engineers. Loops

Module 4: Decision-making and forming loops

Chapter 17. Iteration The while Statement

Question Points Score Total 100

Lecture 6. Statements

ECE 102 Engineering Computation

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

Chapter 13 Control Structures

Unit 3 Decision making, Looping and Arrays

Theory of control structures

SNS COLLEGE OF ENGINEERING,

Loops. CSE 114, Computer Science 1 Stony Brook University

Chapter 4. Flow of Control

Scientific Computing with MATLAB

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

Chapter 4 C Program Control

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

MATLAB Operators, control flow and scripting. Edited by Péter Vass

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

Dr. Iyad Jafar. Adapted from the publisher slides

ECE 202 LAB 3 ADVANCED MATLAB

CS110D: PROGRAMMING LANGUAGE I

Chapter 4 Introduction to Control Statements

Repetition Structures II

do { statements } while (condition);

DECISION CONTROL AND LOOPING STATEMENTS

Fundamentals of Programming Session 13

CS112 Lecture: Repetition Statements

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

Chapter 2: Functions and Control Structures

Why Is Repetition Needed?

Conditional Control Structures. Dr.T.Logeswari

3.2 Recursions One-term recursion, searching for a first occurrence, two-term recursion. 2 sin.

Computer Programming I - Unit 5 Lecture page 1 of 14

Dept. of CSE, IIT KGP

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Computers Programming Course 7. Iulian Năstac

2/5/2018. Learn Four More Kinds of C Statements. ECE 220: Computer Systems & Programming. C s if Statement Enables Conditional Execution

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

Computer Programming: C++

Flow Control: Branches and loops

Dynamic Programming. An Introduction to DP

Subject: PIC Chapter 2.

Lecture Transcript While and Do While Statements in C++

Relational & Logical Operators

Fundamentals of Computer Programming Using C

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

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

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

Transcription:

Control Statements ELEC 206 Prof. Siripong Potisuk 1 Objectives Learn how to change the flow of execution of a MATLAB program through some kind of a decision-making process within that program The program makes these decisions by comparing values of some variables The comparison is done by using a combination of relational & logical operators 2 1

Controlling Flow of Execution Constructs that allow MATLAB to decide whether or not to execute some code that follows the statement or to repeat certain groups of statements Repetitions or loops: 1) for- 2) while- Decision-making: 1) if- 2) if-else- 3) if-elseif-else- 4) Switch case Jumping or Skipping: 1) break 2) continue 3 Flow Chart A diagram that shows the step-by-step flow of execution. It is particularly useful for showing how control statements work. Some common flowchart symbols are represents a sequence of commands represents an if-statement shows the direction of code execution 4 2

Repetitions or Loops A loop executes one set of commands repeatedly. MATLAB has two ways to control number of times loop executes commands - Method 1: for.. loop executes commands a specified number of times - Method 2: while.. loop executes commands as long as a specified expression is true 5 Loop index variable can have any variable name (usually i, j, k, m, and n are used) Avoid using i and j when working with complex numbers. In general, loop body should not change value of k Each for command must have an command 6 3

1. The loop sets k to f, and executes the loop body, i.e., commands between the for and the commands, 2. The loop then sets k to f+s and re-executes the body 3. The process repeats itself until k>t,at which point the program continues with commands that follow the command 7 f and t are usually integers while s usually omitted. If omitted, loop uses an increment of 1 The increment s can be negative e.g., k=25: 5:10 produces four passes with k = 25, 20, 15, 10 If f=t, the loop executes once If f>t and s>0, or if f<t and s<0,loop not executed Value of k not displayed automatically. To display the value in each pass, type k as one of commands in loop body (sometimes useful for debugging) When loop s, k has the value last assigned to it 8 4

If k, s, and t are such that the last value of k cannot be equal to t, then - for s positive, the last pass is one where k has largest value smaller than t. For example, k=8:10:50 produces five passes (k = 8,18,28,38,48) - for s negative, last pass is one where k has smallest value larger than t k can also be assigned specific values (typed as a row vector) For example: for k = [7 9 1 3 3 5] 9 EXAMPLE: Show the output of the following script for k=1:3:10 k x = k^2 fprintf('after loop k = %d\n', k); Output: k = 1 x = 1 k = 4 x = 16 k = 7 x = 49 k = 10 x = 100 After loop k = 10 10 5

EXAMPLE: Write a script file using a for- loop to calculate the sum of the first n terms of the series: n (-1) k k 1 2 k k for n = 4 and 20. n = input( Enter the # of terms: ) sum = 0; for k=1:n sum = sum+(-1)^k*k/2^k; fprintf( The total sum is %f \n', sum) Output: Enter the # of terms: 4 The total sum is -0.125000 11 The while- loop used when - number of loop iterations not known - a testable condition to stop looping when it is false. Examples of test condition: - keep reading data from a file until the is reached - keep adding terms to a sum until the difference of the last two terms is less than a certain amount 12 6

1. Loop starts by evaluating conditional expression 2. If true, executes code in the loop body, then goes back to step 1 3. If false, skips code in the loop body and continue program execution with the code after the statement 13 The conditional expression must have a variable which changes its value after each pass There must be some value of the variable that makes the conditional expression false EXAMPLE: The script x = 1 while x <= 15 x = 2*x outputs x = 1 x = 2 x = 4 x = 8 x = 16 14 7

EXAMPLE: The sequence of Fibonacci numbers F [n] is a sequence of integers starting with 0 and 1, i.e., F [1] = 0 and F [2] = 1. The next number in the sequence is the sum of the previous two numbers, i.e., 0 1 1 2 3 5, 8, 13,.. (a) Derive a recursive equation that can be used to compute the sequence. (b) Write a script file using a while- loop to compute the first 25 numbers in the sequence. 15 (a) F[n] = F [n 1] + F [n 2], n 3 (b) N = input( Enter the # of terms: ) F(1) = 0; F(2) = 1; k = 3; while k <= N F(k) = F(k-1)+F(k-2); k = k+1; fprintf( The first %d terms of the Fibonacci sequence is \n',n) fprintf( %d \n, F) 16 8

Output: Enter the # of terms: 25 The total sum is -0.125000 The first 25 terms of the Fibonacci sequence is 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 17 An infinite loop (also known as indefinite loop) happens if the conditional expression never becomes false, the loop will keep executing... forever! If there is no output from the loop (as if often the case), it will look like MATLAB has stopped responding If your program gets caught in an indefinite loop, activate (i.e., put the cursor in) the Command Window and press CTRL+C 18 9

Common Causes of Indefinite Loops 1. No variable in conditional expression d1 = 1; d2 = 10; d3 = 0; d1 and d2 never change while d1 < d2 fprintf('distance = %d\n', d3); 2. Variable in conditional expression never changes min_d = 42; D_Increment = 0; D = 0; while D < min_d D = D + D_Increment; Typo should be 10 19 3. Wrong variable in conditional expression changed Min_D = 42; delta = 10; D = 0; while D < min_d min_d = min_d + delta; Typo should be D 4. Conditional expression never becomes false Min_D = 42; x = 0; y = 0; while -sqrt(x^2+y^2) < min_d x = x + 1; y = y + x; Typo shouldn't be any negative sign in front of sqrt 20 10

Conditional Statements A construct that allows MATLAB to decide whether or not to execute some code that follows the statement Four general forms if- if-else- if-elseif-else- switch case 21 Conditional expression true MATLAB execute code segment between the if and statement conditional expression false MATLAB skips the code segment between the if and statement Then, it continues executing the code after the -line 22 11

This construct executes one section of code if a condition is true and a different section of code if it is false. 23 24 12

if-elseif-else- structure chooses one of three or more sections of code to execute Can have as many elseif statements as necessary Can omit else statement If omitted and no match to if- or elseifstatements, no code in structure gets executed An easier-to-read alternative structure to the if-elseif-else- structure Choose code to execute based on value of scalar or string, not just true/false 25 26 13

The switch-case structure When the switch-expression is evaluated, If value is equal to value1, executes Group 1 all commands then executes code after statement If value is equal to value2, same as above but Group 2 commands only Etc. 27 The switch-case structure If switch-expression not equal to any of values in case statement, commands after otherwise executed. If otherwise not present, no commands executed If switch expression matches more than one case value, only first matching case executed Comparisons of text strings (within single quotes) are case-sensitive. 28 14

Nesting If a loop or conditional statement is placed inside another loop or conditional statement, the former are said to be nested in the latter Most common to hear of a nested loop, i.e., a loop within a loop Often occur when working with twodimensional problems Each loop and conditional statement must have an statement 29 30 15

The break Command When inside a loop (for and while), break terminates execution of loop - MATLAB jumps from break to command of loop, then continues with next command (does not go back to the for or while command of that loop). - break s whole loop, not just last pass If break inside nested loop, only nested loop terminated (not any outer loops) 31 The break Command break command in script or function file but not in a loop terminates execution of file break command usually used within a conditional statement. If In loops, provides way to looping if some condition is met 32 16

Trick "1" is always true so it makes loop iterate forever! while( 1 ) name = input( 'Type name or q to quit: ', 's' ); if length(name) == 1 && name(1) == 'q' break; Only way to exit loop! else fprintf('your name is %s\n', name); If user entered only one letter and it is a "q", jump out of loop; Otherwise print name 33 The continue command Use continue inside a loop (for- and while-) to stop current iteration and start next iteration continue usually part of a conditional statement When MATLAB reaches continue it does not execute remaining commands in loop but skips to the command of loop and then starts a new iteration 34 17

for ii=1:100 if rem( ii, 8 ) == 0 count = 0; fprintf('ii=%d\n',ii); continue; % code % more code Every eight iteration reset count to zero, print the iteration number, and skip the remaining computations in the loop 35 18