APPM 2460: Week Three For, While and If s

Similar documents
Programming for Experimental Research. Flow Control

Computer Programming: C++

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

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

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

Introduction to Programming for Biology Research

An Introduction to MATLAB

Repetition Structures Chapter 9

ME 142 Engineering Computation I. Condition Statements

EE 301 Signals & Systems I MATLAB Tutorial with Questions

Chapter 4: Programming with MATLAB

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

MATLAB TUTORIAL WORKSHEET

Lesson 10. Homework Problem Set Sample Solutions. then Print True else Print False End if. False False True False False False

Top bar items. Current folder should be shown. Command Window This has the the prompt >>

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

Unit 7. Lesson 7.1. Loop. For Next Statements. Introduction. Loop

Post Experiment Interview Questions

HW 4 HINTS. 1. Chapter 6

Boolean Logic & Branching Lab Conditional Tests

Reviewing all Topics this term

Chapter 5: Control Structures

Relational and Logical Operators. MATLAB Laboratory 10/07/10 Lecture. Chapter 7: Flow Control in Programs. Examples. Logical Operators.

Chapter 4 Introduction to Control Statements

BCA-105 C Language What is C? History of C

Flow Control. Statements We Will Use in Flow Control. Statements We Will Use in Flow Control Relational Operators

MATLAB Laboratory 10/07/10 Lecture. Chapter 7: Flow Control in Programs

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Conditional Control Structures. Dr.T.Logeswari

Laboratory 5: Implementing Loops and Loop Control Strategies

Repetition Structures

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

2: Complexity and Recursion

Introduction to Counting, Some Basic Principles

Physics 326G Winter Class 6

Quiz Determine the output of the following program:

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

REPETITIVE EXECUTION: LOOPS

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

APPM 2460 Matlab Basics

Computer Programming: C++

CS1100 Introduction to Programming

7 Control Structures, Logical Statements

Python lab session 1

CS 221 Lecture. Tuesday, 11 October 2011

Numerical Methods Lecture 1

Our Strategy for Learning Fortran 90

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

MATH2070: LAB 3: Roots of Equations

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 14: OCT. 25TH INSTRUCTOR: JIAYIN WANG

YOLOP Language Reference Manual

EL2310 Scientific Programming

DOWNLOAD PDF MICROSOFT EXCEL ALL FORMULAS LIST WITH EXAMPLES

Ch.5. Loops. (a.k.a. repetition or iteration)

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us?

Einführung in die Programmierung Introduction to Programming

Short Version of Matlab Manual

CISC 181 Lab 2 (100 pts) Due: March 4 at midnight (This is a two-week lab)

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

If Statements, For Loops, Functions

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

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

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

CS195H Homework 1 Grid homotopies and free groups. Due: February 5, 2015, before class

Loops / Repetition Statements

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

Introduction. C provides two styles of flow control:

Strategies for Proofs

Computational Photonics, Summer Term 2012, Abbe School of Photonics, FSU Jena, Prof. Thomas Pertsch

SIMPLE INPUT and OUTPUT:

Introduction to Matlab

(Refer Slide Time: 02:59)

- If you want to repeat the same blocks of code over and over you have two choices. Copy

Create a Login System in Visual Basic. Creating a login system. Start a new visual basic Windows Forms application project. Call it Login System

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

Chapter 4 The If Then Statement

Over and Over Again GEEN163

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

MATH (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab

MATLAB. Devon Cormack and James Staley

CSE200 Lecture 6: RECURSION

Score score < score < score < 65 Score < 50

Case by Case. Chapter 3

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Repetition, Looping CS101

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:

COMP 102: Computers and Computing

Introduction to the Java Basics: Control Flow Statements

Control Structures. March 1, Dr. Mihail. (Dr. Mihail) Control March 1, / 28

CSE 331 Final Exam 12/9/13

Maple for Math Majors. 14. Maple's Control Statements

EL2310 Scientific Programming

Class 1: Homework. Intro to Computer Science CSCI-UA.0101 New York University Courant Institute of Mathematical Sciences Fall 2017

Homework 1 Description CmpE 362 Spring Instructor : Fatih Alagoz Teaching Assistant : Yekta Said Can Due: 3 March, 23:59, sharp

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Loop Statements and Vectorizing Code

MATLAB GUIDE UMD PHYS401 SPRING 2011

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

Transcription:

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 A for-loop is a simple way of repeating a series of steps a given number of times. To see how it works, open an M-file and save it in your directory: as for ex.m, and enter: for i = 1:1:10 2*i The for-loop works in the following manner. We give the loop a variable, in this case i, and we start it at 1, taking steps of size 1, until i equals 10. The inside of the loop tells Matlab to print the value of 2 i at each step, because we didn t follow the 2 i located inside the loop with a semi-colon. Run this file to see what it does. Notice the syntax here. Every for-loop has a for declaration statement in which a variable is set to an initial value, in this case 1. This variable is a counter. The for declaration is followed by a series of statements that Matlab executes until it reaches the statement. Notice that there is never a semicolon after the for declaration statement. Once Matlab reaches the statement, it goes back to the for declaration and adds the specified step size to the index variable. Then it checks this variable s value to see if it exceeds the final specified value, in this case 10. If so, then Matlab is finished with the loop and will execute the line immediately following the statement. If not, then Matlab will enter the loop again. Note that the default step size in Matlab is 1. 3 Something more complicated Let s use a for-loop to make some plots of y = a sin(x), where a = 0.2 k, k = 1, 2, 3, 4, 5, and x is in the interval [0, 1]. Let s make it so it plots on the same figure each time. Modify for ex.m 1

as follows: hold on x = 0:.05:1 for k = 1:1:5 a = 0.2*k; plot(x,a*sin(x)); hold off Any time you need to repeat something a known amount of times, consider using a for-loop. It will save you a great deal of time and effort. And yes, you can put one for-loop inside another one. Just be sure to use a different counter variable for the second loop. 4 Logic Operators Before we move on to while loops and if-statements, we need to learn about logic operators to be used with the if-statements. We start with and and or. The logical operator for and is &. The logical operator for or is. The button is right above the enter button. The & operator simply takes two statements and returns the value of true only if both are true, and returns false otherwise. P Q P&Q true true true true false false false true false false false false For example, 3 is an integer & 4 is even. This is true because both statements are true. In fact, the only case where the & operator is true is if both statements are true statements. Otherwise, it is considered false. The operator is much nicer. It takes two statements as well, and has a True or False value associated with it too. P Q P Q true true true true false true false true true false false false For example, 3 is larger than 4 4 is prime. This is false because both statements are false. In fact, the only case where the is false is when both statements are false statements. Otherwise, if either statement is true then the whole or statement is true. 5 The If-Statement Before, we were using a for loop to loop through a set of instructions a given number of times. An if-statement will perform a set of instructions once the right conditions are met. The syntax is 2

if (condition goes here) action to be performed The conditions you can put in are either equal(==), not equal ( =), less than (<), less than or equal to (<=), greater than (>), and greater than or equal to (>=). Let s do an example. Open an M-file and call it if example.m If the value of some number, a, is greater than or equal to zero, then we ll print out the value. Type for a = -3:1:3 if a>=0 a See how the values of a that were greater than or equal to zero were printed to the command window? Note that we have nested an if-statement inside the for-loop. You can nest if-statements and for loops as many times as needed. We can have more than one condition in our if-statements. If we want two conditions to hold, we use the and operator &, which is found on the 7 key. If we want either one of two conditions to hold we use the or operator,, which is found above the enter key. Let s take the previous example and make it work only for a greater than or equal to zero, but also less than 2. Try for a = -3:1:3 if (a>=0)&(a<2) a We can modify the if-statement so that if the condition is not met, it does something. We use the else statement for this. Let s take the previous example, and make it so that if 2 a 3, then we print 4 a. Type for a = -3:1:3 if (a>=0)&(a<2) a else 4*a We can make the else statement have a condition on it by typing elseif instead of else and then giving it a condition just like we did before. We can have more than one elseif statement if needed. 3

So let s give a couple of examples. In both examples, we will be calculating the factorial of a number. Create two functions, factorial 1 and factorial 2 which take an input value and output the factorial of that value. We must first make sure that the integer being used is positive. We must also make sure that if it is zero, we set the value equal to 1. We could do this by nested if-statements or by just one if-statement with an elseif. We begin with the nested if-statements. if a>=0 f = 1; if a == 0 return % if-statement for i = 1:a f = f*i; % for loop return % if-statement Notice, each if-statement needs an for this to work. This way also requires a return inside the nested if-statement. Otherwise, the program would still run the for loop and give a wrong answer. Finally, we show the same process except with the elseif if a<0 disp( Negative Integer ); elseif a == 0 f = 1; else f = 1; for i = 1:a f = f*i; % for loop % if statement Notice, there is only a need for one on the if-statement. There is also no need for a return call because the structure of the if-statement only allows for one outcome to occur. We do not have to worry about the for loop being executed when a = 0. 6 While Loops A while-loop is another way of repeating a series of steps, but instead of using a counter variable, we use a condition statements. Create a new M-file and save it in your directory: as while ex.m and rewrite both examples from the for-loop section. Below are the new while-loops, verify that the output is the same. 4

i =1; while i <=10 2*i i = i+1; hold on x = 0:.05:1; k = 1; while k<=5 a = 0.2*k; plot(x,a*sin(x)); k = k+1; As you can see, we have the condition statement instead of the counter variable. However we are still counting how many times we repeat the action. While loops are useful when you are unsure how many times you must repeat the loop but have another condition that you must follow. For example, we could implement Euler s Method to approximate an ODE. We could run Euler s method till the iterations are within a value aka y n y n 1 < ɛ. 7 Homework 1. Your first job is to write a function that will calculate the number of different ways in which one could form different unordered groups of m elements from from a total of n elements. The mathematical formula for this is: ( ) n n! = m (n m)!m! where the! is the factorial symbol (i.e. 5! = 5 * 4 * 3 * 2 * 1 = 120) and n and m are non-negative integers and n > m. The function should take as input the total number of elements and the number of different groups. It should then return the correct answer. Please call your function groupings. Assume that the user is smart enough to give as input positive integers and that n will always be greater than m. DO NOT USE Matlab s factorial function! Programs that use this will not receive any credit. Keeping this in mind, the best way to start solving this problem is to write your own function, myfactorial, which takes as input a nonnegative integer n and gives n! as the output. Once you have this function, you can use it to define your final function, groupings. To get the function to work correctly, the user should type, for example, myanswer=groupings(5,3); 5

and the answer will be stored in myanswer. To check your work, groupings(5,3) should return 10. As with every assignment, be sure to place comments at the top of each file with a description of the file followed by your name, assignment number, date, and any other necessary information. (this is a good practice) 2. Your second job is to create a function, primesum, that accepts from the user an array of integers and displays the following in one sentence on the command line: the length of the array the sum of all the prime numbers in the array the number of primes in the array Hint: You will need the isprime, length, and num2str commands. You may need to use the disp command, and a counter variable as well. Ask me if you need help with these concepts. 6