Selections. Zheng-Liang Lu 91 / 120
|
|
- Dana Riley
- 5 years ago
- Views:
Transcription
1 Selections ˆ Selection enables us to write programs that make decisions on. ˆ Selection structures contain one or more of the if, else, and elseif statements. ˆ The end statement denotes the end of selection structures. Zheng-Liang Lu 91 / 120
2 Example: if-else ˆ Write a program which takes a number as input. ˆ If the number is a nonnegative real number, then calculate its square root. ˆ We may use the function input which takes a number from the keyboard. 1 clear; clc; 2 3 x = input('enter a number? '); % input from keyboard 4 if x >= 0 5 sqrt(x) 6 else 7 disp([num2str(x),' is a negative number.']); 8 end Zheng-Liang Lu 92 / 120
3 Exercise: Nested Conditional Statements 1 clear; clc; 2 x = input('enter x?', 's'); 3 % Contribution by Mr. Curtis Yen on Sep. 10, w = str2num(x); 5 if isempty(w) % w is not empty if w is a number 6 disp([x, ' is not a number.']); 7 else 8 if w >= 0 9 sqrt(w) 10 else 11 disp([x ' is not a positive real number.']); 12 end 13 end ˆ Do not write a deeply nested conditional statement. Zheng-Liang Lu 93 / 120
4 Example: if-elseif-else 1 clear; clc; 2 x = input('enter x?', 's'); 3 w = str2num(x); 4 if isempty(w) % w is not empty if w is a number 5 disp([x ' is not a number.']); 6 elseif w >= 0 7 sqrt(w) 8 else 9 disp([x ' is not a positive real number.']); 10 end ˆ Can we change the order of the conditions? ˆ You can put w >= 0 in the first condition. 1 ˆ The empty set can be evaluated as false by the if statement. 1 Thanks to a lively class discussion (Matlab-260) on August 29, Zheng-Liang Lu 94 / 120
5 Example: GPA Conversion Problem 2 ˆ Write a program which converts centesimal points to GPA. ˆ Let x be the grade input. ˆ For simplicity, ˆ If 90 x 100, then x is converted to 4. ˆ If 80 x < 90, then 3. ˆ If 70 x < 80, then 2. ˆ If 60 x < 70, then 1. ˆ If x < 60, then 0. 2 See GPA. Zheng-Liang Lu 95 / 120
6 1 clear; clc; 2 x = input('enter points? '); 3 if x >= 90 && x <= disp('4'); 5 elseif x >= 80 && x < 90 6 disp('3'); 7 elseif x >= 70 && x < 80 8 disp('2'); 9 elseif x >= 60 && x < disp('1'); 11 else 12 disp('0'); 13 end ˆ Can we reverse the conditions? ˆ Can we place the conditions at your will? Zheng-Liang Lu 96 / 120
7 & vs. && 1 clear; clc; 2 3 x = [ ]; 4 y = [ ]; 5 6 x > 0 & y > 0 % return [ ] 7 all(x > 0) && any(y > 0) % return 0 ˆ Consider A && B. ˆ If A returns false, then B won t be evaluated. ˆ This is so-called the short-circuit operator, which facilitates time-saving. ˆ Note that the argument for if statements can be a scalar only! Zheng-Liang Lu 97 / 120
8 Another Selection Structure: switch-case ˆ The switch-case statements allow you to choose between multiple outcomes by checking the value of the target variable. ˆ For example, 1 clear; clc; 2 city = input('enter the name of a city: ', 's'); 3 switch city 4 case {'Taipei', 'New Taipei'} 5 disp('price: $100'); 6 case 'Taichung' 7 disp('price: $200'); 8 case 'Tainan' 9 disp('price: $300'); 10 otherwise 11 disp('not an option.'); % default option 12 end Zheng-Liang Lu 98 / 120
9 Why Not if? if strcmp(city, 'Taipei') strcmp(city, 'New... Taipei') 3 disp('price: $100'); 4 elseif strcmp(city, 'Taichung') 5 disp('price: $200'); 6 elseif strcmp(city, 'Tainan') 7 disp('price: $300'); 8 else 9 disp('not an option.'); 10 end ˆ Can you implement the strcmp function? 3 Thanks to a lively class discussion (Matlab-244) on August 20, Zheng-Liang Lu 99 / 120
10 Exercise ˆ We can try to replicate the functionality of strcmp by not calling it. ˆ You may use the function length to calculate the size of the string (or any arrays later) istaipei = length(city) == length('taipei') &&... 3 all(city == 'Taipei'); 4 isnewtaipei =... % Do the same thing below. 5 if istaipei isnewtaipei 6... % Show the ticket price. 7 elseif % Do the same thing below. 9 end Zheng-Liang Lu 100 / 120
11 Error and Error Handling ˆ You can issue an error if you do not allow the callee for some situations. 4 1 >> error('this is an error.'); ˆ Also, you can use a try-catch statement to handle errors. 1 try 2 % normal operations 3 catch 4 % handler operations 5 end 4 In other words, you can decide if the action can be performed. Zheng-Liang Lu 101 / 120
12 Example: Combinations ˆ For all nonnegative integers n k, ( n k) is given by ( ) n n! = k k!(n k)!. ˆ Note that factorial(n) returns n!. 1 clear; clc; 2 3 n = input('n =? '); 4 k = input('k =? '); 5 y = factorial(n) / (factorial(k) * factorial(n - k)) 6 disp('end of program.'); Zheng-Liang Lu 102 / 120
13 ˆ Try n = 2, k = 5. ˆ factorial( 3) is not allowed! ˆ So your program stops in Line 5, and terminates abnormally. ˆ The reason is that Line 5 produces an error and the program is not designed to handle it. ˆ Then Matlab takes over and kills this program try 3 y = factorial(n) / (factorial(k) *... factorial(n - k)) 4 catch e % capture the thrown exception 5 disp(['error: ' e.message]); 6 end 7 disp('end of program.'); Zheng-Liang Lu 103 / 120
14 Exercise: Divided by Zero ˆ Write a program which calculates x/y for any two real numbers x, y. ˆ The program restricts the user to do division by zero. ˆ Note that we don t use this error-handling mechanism for normal executions in regard to the performance! 1... % assume x = 1 any y = 0 2 if y == 0 3 error('divided by zero!'); 4 else 5 ans = x / y; 6 end 7... Zheng-Liang Lu 104 / 120
15 Repetitions ˆ If a group of instructions is potentially repeated, you should wrap those in a repetition structure, called loops. ˆ All loops consist of 3 parts: ˆ Find the repeated pattern for each iteration. ˆ Warp them by a loop. ˆ Set the continuation condition by defining a loop variable with some criterion. ˆ Matlab provides two different types: the for loops and the while loops. ˆ Use for loops if you know the number of iterations. ˆ Otherwise, use while loops. Zheng-Liang Lu 105 / 120
16 for Loops ˆ A for loop is the easiest choice when you know how many times you need to repeat the loop. 1 for loopvar = somearray 2 % body 3 end ˆ Particularly, we often use for loops to manipulate arrays! Zheng-Liang Lu 106 / 120
17 Zheng-Liang Lu 107 / 120
18 Example 1 for i = 1 : 10 2 disp(i); 3 end ˆ Can you show the odd integers from 1 to 9? 1 for student = {'Arthur', 'Alice'} 2 disp(cell2mat(student)); 3 % remember to take things out of cells 4 end ˆ Clearly, Matlab has for-each loops, which is an enhanced one compared to the naive one in C. ˆ Note that we use the function cell2mat so that a string stored in the cell can be extracted as a string. Zheng-Liang Lu 108 / 120
19 Example: Find Maximum (Revisited) 1 clear; clc; 2 3 x = [ ]; % input list 4 max = x(1); 5 for i = 2 : 7 6 if max < x(i) 7 max = x(i); 8 end 9 end 10 max ˆ Can you find the location of the maximum element? ˆ Try to find the minimum element and its location. Zheng-Liang Lu 109 / 120
20 Example: Running Sum ˆ Write a program which calculates the sum of array elements. 1 clear; clc; 2 3 x = 1 : 1 : 100; 4 s = 0; 5 for i = 1 : length(x) 6 s = s + x(i); % running sum 7 end 8 s ˆ Use length(x) instead of 100 in Line 5. ˆ Then the loop will do as many times as the number of elements in x. Zheng-Liang Lu 110 / 120
21 Exercise: Estimating π by Monte Carlo Simulation 5 ˆ Write a program which estimates π by generating a certain number of sample points (x, y) and calculating ˆπ = 4 m n, where m is the number of points falling in the region of the quarter circle shown in the next page, n is the total number of points, and ˆπ is the estimate of π. 5 Monte Carlo was a code word used in World War II to describe sampling-based methods for neutron scattering computations associated with Manhattan project. Zheng-Liang Lu 111 / 120
22 Zheng-Liang Lu 112 / 120
23 1 clear; clc; 2 3 n = 1e5; 4 m = 0; 5 for i = 1 : n 6 x = rand(1); 7 y = rand(1); 8 if x ˆ 2 + y ˆ 2 < 1 9 m = m + 1; 10 end 11 end 12 estimated pi = 4 * m / n ˆ ˆπ π as n by the law of large numbers (LLN). 6 ˆ Try to vectorize this program. 6 See Zheng-Liang Lu 113 / 120
24 More Exercises ˆ Write a program to estimate 5 by Monte Carlo. ˆ Write a program to estimate 1 0 xdx by Monte Carlo. ˆ Write a program to estimate the call price of European option by Monte Carlo. Zheng-Liang Lu 114 / 120
25 while Loops ˆ The while loops are preferred when you need to keep repeating the instructions until a continuation criterion is not met. 1 while criterion 2 % body 3 end ˆ Note that before entering the while loop, the criterion will be checked. ˆ Also note that the if statement is similar to the while loop except that the if statement executes only once. Zheng-Liang Lu 115 / 120
26 Zheng-Liang Lu 116 / 120
27 Example: Compounding ˆ Let x be the initial amount of some investment, and r be the annual interest rate. ˆ Write a program which calculates the holding years n so that this investment doubles it value. Zheng-Liang Lu 117 / 120
28 Solution ˆ In this case, we don t know how many iterations we need before the loop. 1 clear; clc; 2 3 balance = 100; 4 goal = 200; 5 r = 0.01; 6 years = 0; 7 8 while balance < goal 9 balance = balance * (1 + r); 10 years = years + 1; 11 end 12 n ˆ Note that the criterion is to continue the loop. Zheng-Liang Lu 118 / 120
29 Infinite Loops 1 while true 2 disp('press ctrl+c to stop me!!!'); 3 end ˆ Note that your program can terminate the program by pressing ctrl+c. Zheng-Liang Lu 119 / 120
30 More Exercises ˆ Let a > b be two any positive integers. ˆ Write a program which calculates the remainder of a divided by b. ˆ Do not use mod(a, b). ˆ Write a program which determines the greatest common divisor (GCD) of a and b. ˆ Do not use gcd(a, b). Zheng-Liang Lu 120 / 120
Arrays. ˆ An array, is a linear data structure consisting of a collection of elements, each identified by one array index. ˆ For math, arrays could be
Arrays ˆ An array, is a linear data structure consisting of a collection of elements, each identified by one array index. ˆ For math, arrays could be ˆ row vectors: u R 1 n for any positive integer n ˆ
More informationVariables and Assignments
Variables and Assignments ˆ A variable is used to keep a value or values. ˆ A box which contains something. ˆ In most languages, a statement looks like var = expression, where var is a variable and expression
More informationStructure Array 1 / 50
Structure Array A structure array is a data type that groups related data using data containers called fields. Each field can contain any type of data. Access data in a structure using dot notation of
More informationArithmetic Compound Assignment Operators
Arithmetic Compound Assignment Operators Note that these shorthand operators are not available in languages such as Matlab and R. Zheng-Liang Lu Java Programming 76 / 141 Example 1... 2 int x = 1; 3 System.out.println(x);
More informationExample: Monte Carlo Simulation 1
Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149
More informationCommon Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141
Common Errors 2 double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141 Generating random numbers Example Write a program which generates
More information7 Control Structures, Logical Statements
7 Control Structures, Logical Statements 7.1 Logical Statements 1. Logical (true or false) statements comparing scalars or matrices can be evaluated in MATLAB. Two matrices of the same size may be compared,
More informationLoops / Repetition Statements
Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for
More informationProgramming for Experimental Research. Flow Control
Programming for Experimental Research Flow Control FLOW CONTROL In a simple program, the commands are executed one after the other in the order they are typed. Many situations require more sophisticated
More informationBranches, Conditional Statements
Branches, Conditional Statements Branches, Conditional Statements A conditional statement lets you execute lines of code if some condition is met. There are 3 general forms in MATLAB: if if/else if/elseif/else
More informationswitch-case Statements
switch-case Statements A switch-case structure takes actions depending on the target variable. 2 switch (target) { 3 case v1: 4 // statements 5 break; 6 case v2: 7. 8. 9 case vk: 10 // statements 11 break;
More informationLogic is the anatomy of thought. John Locke ( ) This sentence is false.
Logic is the anatomy of thought. John Locke (1632 1704) This sentence is false. I know that I know nothing. anonymous Plato (In Apology, Plato relates that Socrates accounts for his seeming wiser than
More information1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133
1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 88 / 133 Flow Controls The basic algorithm (and program) is constituted
More informationScope of Variables. In general, it is not a good practice to define many global variables. 1. Use global to declare x as a global variable.
Scope of Variables The variables used in function m-files are known as local variables. Any variable defined within the function exists only for the function to use. The only way a function can communicate
More information1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137
1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 89 / 137 Flow Controls The basic algorithm (and program) is constituted
More information1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221
1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221 Functions Recall that an algorithm is a feasible solution to the specific problem. 1 A function is a piece of computer code that accepts
More information1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225
1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225 Functions The first thing of the design of algorithms is to divide and conquer. A large and complex problem would be solved by couples
More informationCOGS 119/219 MATLAB for Experimental Research. Fall 2016 Week 1 Built-in array functions, Data types.m files, begin Flow Control
COGS 119/219 MATLAB for Experimental Research Fall 2016 Week 1 Built-in array functions, Data types.m files, begin Flow Control .m files We can write the MATLAB commands that we type at the command window
More informationMATLAB Laboratory 10/07/10 Lecture. Chapter 7: Flow Control in Programs
MATLAB Laboratory 10/07/10 Lecture Chapter 7: Flow Control in Programs Lisa A. Oberbroeckling Loyola University Maryland loberbroeckling@loyola.edu L. Oberbroeckling (Loyola University) MATLAB 10/07/10
More informationIntroduction to Matlab. By: Hossein Hamooni Fall 2014
Introduction to Matlab By: Hossein Hamooni Fall 2014 Why Matlab? Data analytics task Large data processing Multi-platform, Multi Format data importing Graphing Modeling Lots of built-in functions for rapid
More informationIntroduction to MATLAB
Introduction to MATLAB Dr./ Ahmed Nagib Mechanical Engineering department, Alexandria university, Egypt Spring 2017 Chapter 4 Decision making and looping functions (If, for and while functions) 4-1 Flowcharts
More informationRepetition Structures Chapter 9
Sum of the terms Repetition Structures Chapter 9 1 Value of the Alternating Harmonic Series 0.9 0.8 0.7 0.6 0.5 10 0 10 1 10 2 10 3 Number of terms Objectives After studying this chapter you should be
More informationNumber System. Introduction. Natural Numbers (N) Whole Numbers (W) Integers (Z) Prime Numbers (P) Face Value. Place Value
1 Number System Introduction In this chapter, we will study about the number system and number line. We will also learn about the four fundamental operations on whole numbers and their properties. Natural
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationRelational and Logical Operators. MATLAB Laboratory 10/07/10 Lecture. Chapter 7: Flow Control in Programs. Examples. Logical Operators.
Relational and Logical Operators MATLAB Laboratory 10/07/10 Lecture Chapter 7: Flow Control in Programs Both operators take on form expression1 OPERATOR expression2 and evaluate to either TRUE (1) or FALSE
More informationExercise (Revisited)
Exercise (Revisited) Redo the cashier problem by using an infinite loop with a break statement. 1... 2 while (true) { 3 System.out.println("Enter price?"); 4 price = input.nextint(); 5 if (price
More informationExample. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.
Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()
More informationWhile Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical
Recommended Readings Chapter 5 Topic 5: Repetition Are you saying that I am redundant? That I repeat myself? That I say the same thing over and over again? 1 2 Repetition So far, we have learned How to
More informationPrevious Lecture: Today s Lecture: Announcements: Nesting if-statements Logical operators short-circuit. Iteration using for
Previous Lecture: Nesting if-statements Logical operators short-circuit Today s Lecture: Iteration using for Announcements: Discussion this week is in the classrooms as listed in Student Center Register
More informationRelational & Logical Operators, Selection Statements
Relational & Logical Operators, Selection Statements by Ahmet Sacan selection statements, branching statements, condition, relational expression, Boolean expression, logical expression, relational operators,
More information++x vs. x++ We will use these notations very often.
++x vs. x++ The expression ++x first increments the value of x and then returns x. Instead, the expression x++ first returns the value of x and then increments itself. For example, 1... 2 int x = 1; 3
More informationMATLAB TUTORIAL WORKSHEET
MATLAB TUTORIAL WORKSHEET What is MATLAB? Software package used for computation High-level programming language with easy to use interactive environment Access MATLAB at Tufts here: https://it.tufts.edu/sw-matlabstudent
More informationIEEE Floating-Point Representation 1
IEEE Floating-Point Representation 1 x = ( 1) s M 2 E The sign s determines whether the number is negative (s = 1) or positive (s = 0). The significand M is a fractional binary number that ranges either
More informationBoolean Logic & Branching Lab Conditional Tests
I. Boolean (Logical) Operations Boolean Logic & Branching Lab Conditional Tests 1. Review of Binary logic Three basic logical operations are commonly used in binary logic: and, or, and not. Table 1 lists
More informationScientific Computing with MATLAB
Scientific Computing with MATLAB Dra. K.-Y. Daisy Fan Department of Computer Science Cornell University Ithaca, NY, USA UNAM IIM 2012 2 Focus on computing using MATLAB Computer Science Computational Science
More information1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207
1 class Lecture4 { 2 3 "Loops" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207 Loops A loop can be used to make a program execute statements repeatedly without having
More information21-Loops Part 2 text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie
21-Loops Part 2 text: Chapter 6.4-6.6 ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie While Loop Infinite Loops Break and Continue Overview Dr. Henry Louie 2 WHILE Loop Used to
More informationCS 221 Lecture. Tuesday, 11 October 2011
CS 221 Lecture Tuesday, 11 October 2011 "Computers in the future may weigh no more than 1.5 tons." - Popular Mechanics, forecasting the relentless march of science, 1949. Today s Topics 1. Announcements
More informationPractice Reading for Loops
ME 350 Lab Exercise 3 Fall 07 for loops, fprintf, if constructs Practice Reading for Loops For each of the following code snippets, fill out the table to the right with the values displayed when the code
More informationScanner Objects. Zheng-Liang Lu Java Programming 82 / 133
Scanner Objects It is not convenient to modify the source code and recompile it for a different radius. Reading from the console enables the program to receive an input from the user. A Scanner object
More informationAPPM 2460: Week Three For, While and If s
APPM 2460: Week Three For, While and If s 1 Introduction Today we will learn a little more about programming. This time we will learn how to use for loops, while loops and if statements. 2 The For Loop
More informationConstraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial
1 Matlab Tutorial 2 Lecture Learning Objectives Each student should be able to: Describe the Matlab desktop Explain the basic use of Matlab variables Explain the basic use of Matlab scripts Explain the
More informationStep by step set of instructions to accomplish a task or solve a problem
Step by step set of instructions to accomplish a task or solve a problem Algorithm to sum a list of numbers: Start a Sum at 0 For each number in the list: Add the current sum to the next number Make the
More informationArithmetic Compound Assignment Operators
Arithmetic Compound Assignment Operators Note that these shorthand operators are not available in languages such as Matlab and R. Zheng-Liang Lu Java Programming 76 / 172 Example 1... 2 int x = 1; 3 System.out.println(x);
More informationˆ Note that we often make a trade-off between time and space. ˆ Time complexity ˆ Space complexity. ˆ Unlike time, we can reuse memory.
ˆ We use O-notation to describe the asymptotic 1 upper bound of complexity of the algorithm. ˆ So O-notation is widely used to classify algorithms by how they respond to changes in its input size. 2 ˆ
More informationMechanical Engineering Department Second Year
Lecture 3: Control Statements if Statement It evaluates a logical expression and executes a group of statements when the expression is true. The optional (elseif) and else keywords provide for the execution
More informationMATH 2221 A Mathematics Laboratory II
MATH 2221 A Mathematics Laboratory II Lab Assignment 7 Name: Student ID.: In this assignment, you are asked to run MATLAB demos to see MATLAB at work. The color version of this assignment can be found
More informationSECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB
SECTION 2: PROGRAMMING WITH MATLAB MAE 4020/5020 Numerical Methods with MATLAB 2 Functions and M Files M Files 3 Script file so called due to.m filename extension Contains a series of MATLAB commands The
More information4. Use a loop to print the first 25 Fibonacci numbers. Do you need to store these values in a data structure such as an array or list?
1 Practice problems Here is a collection of some relatively straightforward problems that let you practice simple nuts and bolts of programming. Each problem is intended to be a separate program. 1. Write
More informationSelection Statements
Selection Statements by Ahmet Sacan selection statements, branching statements, condition, relational expression, Boolean expression, logical expression, relational operators, logical operators, truth
More informationFlow Control. Spring Flow Control Spring / 26
Flow Control Spring 2019 Flow Control Spring 2019 1 / 26 Relational Expressions Conditions in if statements use expressions that are conceptually either true or false. These expressions are called relational
More informationH.C. Chen 1/24/2019. Chapter 4. Branching Statements and Program Design. Programming 1: Logical Operators, Logical Functions, and the IF-block
Chapter 4 Branching Statements and Program Design Programming 1: Logical Operators, Logical Functions, and the IF-block Learning objectives: 1. Write simple program modules to implement single numerical
More informationExample. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.
Example Generating random numbers Write a program which generates 2 random integers and asks the user to answer the math expression. For example, the program shows 2 + 5 =? If the user answers 7, then
More informationExercise: Sorting 1. ˆ Let A be any array. ˆ Write a program which outputs the sorted array of A (in ascending order).
Exercise: Sorting 1 ˆ Let A be any array. ˆ Write a program which outputs the sorted array of A (in ascending order). ˆ For example, A = [5, 4, 1, 2, 3]. ˆ Then the sorted array is [1, 2, 3, 4, 5]. ˆ You
More informationThis is the basis for the programming concept called a loop statement
Chapter 4 Think back to any very difficult quantitative problem that you had to solve in some science class How long did it take? How many times did you solve it? What if you had millions of data points
More informationDr. Iyad Jafar. Adapted from the publisher slides
Computer Applications Lab Lab 5 Programming in Matlab Chapter 4 Sections 1,2,3,4 Dr. Iyad Jafar Adapted from the publisher slides Outline Program design and development Relational operators and logical
More informationAPCS Semester #1 Final Exam Practice Problems
Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester
More informationConditionals !
Conditionals 02-201! Computing GCD GCD Problem: Compute the greatest common divisor of two integers. Input: Two integers a and b. Output: The greatest common divisor of a and b. Exercise: Design an algorithm
More informationExample. Write a program which generates 2 random integers and asks the user to answer the math expression.
Generating random numbers Example Write a program which generates 2 random integers and asks the user to answer the math expression. For example, the program shows 2 + 5 =? If the user answers 7, then
More informationBEng (Hons) Telecommunications. Examinations for / Semester 2
BEng (Hons) Telecommunications Cohort: BTEL/14B/FT Examinations for 2014-2015 / Semester 2 MODULE: NUMBERS, LOGICS AND GRAPHS THEORIES MODULE CODE: Duration: 3 Hours Instructions to Candidates: 1 Answer
More informationUniv. of Illinois Due Wednesday, Sept 13, 2017 Prof. Allen
ECE 298JA NS #2 Version.28 April 22, 208 Fall 207 Univ. of Illinois Due Wednesday, Sept 3, 207 Prof. Allen Topic of this homework: Prime numbers, greatest common divisors, the continued fraction algorithm
More informationProgramming 1. Script files. help cd Example:
Programming Until now we worked with Matlab interactively, executing simple statements line by line, often reentering the same sequences of commands. Alternatively, we can store the Matlab input commands
More informationThe while Loop 4/6/16 4
Chapter 4: Loops Chapter Goals To implement while and for loops To hand-trace the execution of a program To become familiar with common loop algorithms To understand nested loops To implement programs
More informationAssertions & Verification & Example Loop Invariants Example Exam Questions
2014 November 27 1. Assertions & Verification & Example Loop Invariants Example Exam Questions 2. A B C Give a general template for refining an operation into a sequence and state what questions a designer
More informationChapter 3 Problem Solving and the Computer
Chapter 3 Problem Solving and the Computer An algorithm is a step-by-step operations that the CPU must execute in order to solve a problem, or to perform that task. A program is the specification of an
More informationProgramming in MATLAB
2. Scripts, Input/Output and if Faculty of mathematics, physics and informatics Comenius University in Bratislava October 7th, 2015 Scripts Scripts script is basically just a sequence of commands the same
More informationJava. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures
Chapter 5: Control Structures II Java Programming: Program Design Including Data Structures Chapter Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled,
More informationControl Statements. Objectives. ELEC 206 Prof. Siripong Potisuk
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
More informationCOMP MATLAB.
COMP110031 MATLAB chenyang@fudan.edu.cn M 2 M 3 M 4 M 5 M 6 M script MATLAB MATLAB 7 M function M function [y1,...,yn] = myfunc(x1,...,xm) myfunc x1,...,xm y1,...,yn eters 8 function y=myfunc(x) y=x+1;
More informationSummer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define
CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationLecture Notes, CSE 232, Fall 2014 Semester
Lecture Notes, CSE 232, Fall 2014 Semester Dr. Brett Olsen Week 11 - Number Theory Number theory is the study of the integers. The most basic concept in number theory is divisibility. We say that b divides
More informationCEMTool Tutorial. Control statements
CEMTool Tutorial Control statements Overview This tutorial is part of the CEMWARE series. Each tutorial in this series will teach you a specific topic of common applications by explaining theoretical concepts
More informationMAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB
MAT 75 Laboratory Matrix Computations and Programming in MATLAB In this laboratory session we will learn how to. Create and manipulate matrices and vectors.. Write simple programs in MATLAB NOTE: For your
More informationJump Statements. ˆ The break statement exits a for or while loop completely.
Jump Statements ˆ The break statement exits a for or while loop completely. ˆ No longer in the loop. ˆ Aka early termination. ˆ To skip the rest of the instructions in the loop and begin the next iteration,
More informationStructured programming
Exercises 8 Version 1.0, 1 December, 2016 Table of Contents 1. Recursion................................................................... 1 1.1. Problem 1...............................................................
More informationProgramming 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
More informationChapter 4: Programming with MATLAB
Chapter 4: Programming with MATLAB Topics Covered: Programming Overview Relational Operators and Logical Variables Logical Operators and Functions Conditional Statements For Loops While Loops Debugging
More informationEP375 Computational Physics
EP375 Computational Physics Topic 1 MATLAB TUTORIAL BASICS Department of Engineering Physics University of Gaziantep Feb 2014 Sayfa 1 Basic Commands help command get help for a command clear all clears
More informationEL2310 Scientific Programming
(pronobis@kth.se) Overview Overview Wrap Up More on Scripts and Functions Basic Programming Lecture 2 Lecture 3 Lecture 4 Wrap Up Last time Loading data from file: load( filename ) Graphical input and
More information11.3 Function Prototypes
11.3 Function Prototypes A Function Prototype contains the function s return type, name and parameter list Writing the function prototype is declaring the function. float square (float x); In a function
More informationPhysics 326G Winter Class 6
Physics 36G Winter 008 Class 6 Today we will learn about functions, and also about some basic programming that allows you to control the execution of commands in the programs you write. You have already
More informationLoops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input
Loops / Repetition Statements Repetition s allow us to execute a multiple times Often they are referred to as loops C has three kinds of repetition s: the while loop the for loop the do loop The programmer
More informationSCHOOL OF ENGINEERING & BUILT ENVIRONMENT. Mathematics. Numbers & Number Systems
SCHOOL OF ENGINEERING & BUILT ENVIRONMENT Mathematics Numbers & Number Systems Introduction Numbers and Their Properties Multiples and Factors The Division Algorithm Prime and Composite Numbers Prime Factors
More informationAn Introduction to MATLAB
An Introduction to MATLAB Day 1 Simon Mitchell Simon.Mitchell@ucla.edu High level language Programing language and development environment Built-in development tools Numerical manipulation Plotting of
More informationChapter 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
More informationSECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing
SECTION 5: STRUCTURED PROGRAMMING IN MATLAB ENGR 112 Introduction to Engineering Computing 2 Conditional Statements if statements if else statements Logical and relational operators switch case statements
More informationCOP 4516: Math for Programming Contest Notes
COP 4516: Math for Programming Contest Notes Euclid's Algorithm Euclid's Algorithm is the efficient way to determine the greatest common divisor between two integers. Given two positive integers a and
More informationFall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives
CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write
More informationOutline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.
CSE 170 Interacting with MATLAB Instructor: Aijun An Department of Computer Science and Engineering York University aan@cse.yorku.ca Outline Starting MATLAB MATLAB Windows Using the Command Window Some
More informationChapter Summary. Mathematical Induction Recursive Definitions Structural Induction Recursive Algorithms
Chapter Summary Mathematical Induction Recursive Definitions Structural Induction Recursive Algorithms Section 5.1 Sec.on Summary Mathematical Induction Examples of Proof by Mathematical Induction Mistaken
More informationREPETITIVE EXECUTION: LOOPS
Contents REPETITIVE EXECUTION: LOOPS... 1 for Loops... 1 while Loops... 6 The break and continue Commands... 8 Nested Loops... 10 Distinguishing Characteristics of for and while Loops Things to Remember...
More informationGlobal Variables. ˆ Unlike local variables, global variables are available to all functions involved.
Global Variables ˆ Unlike local variables, global variables are available to all functions involved. ˆ Use global to declare x as global. ˆ For example, the universal constant, say,. 1 ˆ However, it is
More informationWhat is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment
What is MATLAB? MATLAB PROGRAMMING Stands for MATrix LABoratory A software built around vectors and matrices A great tool for numerical computation of mathematical problems, such as Calculus Has powerful
More information1) Generate a vector of the even numbers between 5 and 50.
MATLAB Sheet 1) Generate a vector of the even numbers between 5 and 50. 2) Let x = [3 5 4 2 8 9]. a) Add 20 to each element. b) Subtract 2 from each element. c) Add 3 to just the odd index elements. d)
More informationWhat is recursion? Recursion. How can a function call itself? Recursive message() modified. contains a reference to itself. Week 7. Gaddis:
Recursion What is recursion? Week 7! Generally, when something contains a reference to itself Gaddis:19.1-19.4! Math: defining a function in terms of itself CS 5301 Fall 2013 Jill Seaman 1! Computer science:
More informationAlgorithm Discovery and Design. Why are Algorithms Important? Representing Algorithms. Chapter 2 Topics: What language to use?
Algorithm Discovery and Design Chapter 2 Topics: Representing Algorithms Algorithmic Problem Solving CMPUT101 Introduction to Computing (c) Yngvi Bjornsson & Jia You 1 Why are Algorithms Important? If
More informationComputational Finance
Computational Finance Introduction to Matlab Marek Kolman Matlab program/programming language for technical computing particularly for numerical issues works on matrix/vector basis usually used for functional
More informationProgramming in MATLAB
Programming in MATLAB Scripts, functions, and control structures Some code examples from: Introduction to Numerical Methods and MATLAB Programming for Engineers by Young & Mohlenkamp Script Collection
More informationLOOPS. 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
More information