CS 221 Lecture. Tuesday, 11 October 2011

Similar documents
CS 221 Lecture. Tuesday, 4 October There are 10 kinds of people in this world: those who know how to count in binary, and those who don t.

ENGR 1181 MATLAB 09: For Loops 2

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

INTRODUCTION OF LOOPS

Programming for Experimental Research. Flow Control

CS 221 Lecture. Tuesday, 13 September 2011

Loops / Repetition Statements

Lecture 7: General Loops (Chapter 7)

More on Arrays CS 16: Solving Problems with Computers I Lecture #13

Branches, Conditional Statements

Repetition Structures Chapter 9

CS 3512, Spring Instructor: Doug Dunham. Textbook: James L. Hein, Discrete Structures, Logic, and Computability, 3rd Ed. Jones and Barlett, 2010

Dept. of CSE, IIT KGP

EGR 111 Loops. This lab is an introduction to loops, which allow MATLAB to repeat commands a certain number of times.

Genome Sciences 373 Genome Informa1cs. Quiz Sec1on #1 March 31, 2015

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

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

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

CS 310 Advanced Data Structures and Algorithms

Intro to Computational Programming in C Engineering For Kids!

function [s p] = sumprod (f, g)

Lecture Transcript While and Do While Statements in C++

Programming in MATLAB

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

Programming with Arrays Intro to Pointers CS 16: Solving Problems with Computers I Lecture #11

EGR 111 Loops. This lab is an introduction to loops, which allow MATLAB to repeat commands a certain number of times.

Conditionals !

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

Structured Program Development

7 Control Structures, Logical Statements

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Lecture 2. CS118 Term planner. Refinement. Recall our first Java program. Program skeleton GCD. For your first seminar. For your second seminar

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

Optimization Problems and Wrap-Up. CS 221 Lecture 14 Tue 6 December 2011

Physics 326G Winter Class 6

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

Programming for Electrical and Computer Engineers. Pointers and Arrays

2. All answers should go on blank paper that will be provided. Very carefully number and draw lines separating each solution!

APPM 2460: Week Three For, While and If s

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

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Chapter 4: Programming with MATLAB

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

LOOPS. Repetition using the while statement

! Addition! Multiplication! Bigger Example - RSA cryptography

Assertions & Verification & Example Loop Invariants Example Exam Questions

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

Scientific Computing with MATLAB

MATLAB GUIDE UMD PHYS401 SPRING 2011

(Refer Slide Time: 00:26)

REPETITIVE EXECUTION: LOOPS

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Visual basic tutorial problems, developed by Dr. Clement,

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Lecture Notes, CSE 232, Fall 2014 Semester

Counting Loop: DO-END DO. DO var = initial-value, final-value, step-size

What is recursion? Recursion. How can a function call itself? Recursive message() modified. contains a reference to itself. Week 7. Gaddis:

MATLAB - Lecture # 4

CS 199 Computer Programming. Spring 2018 Lecture 5 Control Statements

Programming in MATLAB Part 2

Add Binary Numbers What is the largest decimal number you can represent using 3 bits?

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

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Describing and Implementing Algorithms

Arrays 2 CS 16: Solving Problems with Computers I Lecture #12

Control Statements. if for while

Lesson 2 Characteristics of Good Code Writing (* acknowledgements to Dr. G. Spinelli, New Mexico Tech, for a substantial portion of this lesson)

Short Version of Matlab Manual

isinstance and While Loops

The continue command goes back to the start of a loop and increments by one unit.

Assertions & Verification Example Exam Questions

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

Friday Four Square! Today at 4:15PM, Outside Gates

Lecture 8. Conditionals & Control Flow

Computer Programming

Mathworks (company that releases Matlab ) documentation website is:

ECE 102 Engineering Computation

Practice Exam 2. CS112 Computation for the Sciences

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

Dr. Khaled Al-Qawasmi

CMPE 8 Lab 3: Introduction to the Scribbler 2 and SPIN

Lecture 10: Recursion vs Iteration

CSCE 110: Programming I

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved.

Number System. Introduction. Natural Numbers (N) Whole Numbers (W) Integers (Z) Prime Numbers (P) Face Value. Place Value

CS1114: Matlab Introduction

CS 112: Intro to Comp Prog

Fall 2014 MAT 375 Numerical Methods. Introduction to Programming using MATLAB

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Introduction to Matlab. By: Hossein Hamooni Fall 2014

COE428 Lecture Notes Week 1 (Week of January 9, 2017)

MATLAB GUIDE UMD PHYS375 FALL 2010

Title. Java Just in Time. John Latham. October 25, October 25, 2017 Java Just in Time - John Latham Page 1(0/0)

Relational & Logical Operators, Selection Statements

ECE 2574: Data Structures and Algorithms - Recursion Part I. C. L. Wyatt

Programming for Engineers Iteration

Standard Version of Starting Out with C++, 4th Edition. Chapter 19 Recursion. Copyright 2003 Scott/Jones Publishing

CS101 Lecture 04: Binary Arithmetic

Lecture 8: Control Structures I

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

Transcription:

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 2. if statements ( logical statements in the textbook) select among alternatives. 3. while repeats statements until a condition becomes false. 4. Formatted output is easier with fprintf(). 5. Loops are useful for processing arrays element-by-element 6. for-loops: a shorthand for bounded loops

1. Announcements Remaining Quiz Dates: In class: 25 October, 22 November In lab: 3 November, 1 December Bring your text to lab!

2. if selects among alternatives. if score >= 60 % score is at least 60 grade = P ; % this is alternative 1 else % ~ (score >= 60) % therefore: score < 60 grade = F ; % this is alternative 2 Exactly one alternative will be selected!

Quiz Problem Correct Solution if quality < 10 disp( Reject ) elseif quality < 30 % 10 quality < 30 disp( Maybe ) else % quality 30 no need to test! disp( Accept )

Quiz Problem Common Mistakes if quality < 10 disp( Reject ) ifelse quality >= 10 && quality < 30 disp( Maybe ) else quality >= 30 disp( Accept )

3. while Repeats Statements Until a x = 10; while x < 20 x = x + 2 Condition Becomes False If the condition is initially false, the statement is never executed! x = 30; while x < 20 x = x + 2 % this is not executed

Example: Euclid s Algorithm for the Greatest Common Divisor (GCD) The Greatest Common Divisor (GCD) of two positive integers is the largest integer that divides both numbers. The GCD of two numbers is always 1 Let s write GCD as a function: GCD(m,n) takes two positive integers and returns the largest integer that divides both m and n. The GCD function has the following properties: GCD(x,x) == x GCD(x,y) == GCD(x,x y)

Euclid s Algorithm Computes the GCD Euclid s algorithm*: Given two positive integers m and n: 1. If m and n are equal, stop: m is the GCD (so is n). 2. Otherwise (they are unequal): Replace the larger number with their difference 3. Go back to the first step. *Definition of algorithm: An effective procedure given as a sequence of steps for carrying out a specific computation.

Natural Language Description Corresponds to this MATLAB Code: while <m and n are not equal> <Replace the larger of m and n with the difference between them>;

GCD Function in MATLAB function x = gcd(m,n) % gcd: compute greatest common divisor while m ~= n if m > n m = m n; else % n > m (Note: this is a COMMENT!) n = n m; % at this point we know m==n x = m;

4. Producing Formatted Output (Text Section 4.5) disp(): basic output capabilities Show a variable or array in default format fixed number of decimal places What if you want to embed a number in a string? E.g., to get The number <v> is even. where <v> is the value of variable v, you have to create an array of strings and convert v to a string with num2str(): disp( [ The number, num2str(v), is even ] ) What if you want to print only two decimal places? What if you don t want a newlineline printed after the output?

fprintf() gives greater control over output formatting. fprintf(<format string>, var1, var2,...) <format string> is a string containing conversion indicators (starting with %) that show where to put the values of var1, var2,... and how to format them Example: fprintf( The value of x is %d\n, x) prints: The value of x is 100 when x is 100. Conversion indications consist of: % 12.5 d %: indicates the beginning of the field 12: minimum field width in characters 5: precision (number of decimal places) d: conversion to apply (d = decimal integer, i does the same thing)

fprintf Examples

5. Loops are useful for processing arrays element-by-element You are given an array of numbers between 0 and 100. You want to print only the values in the array that are at least 70 and less than 90; all others should left blank. For example: V = [ 10 89 9 88 65 90 34 75 70] should produce output: V = [ 89 88 75 70]

Outlining a Solution Look at each element of the array: If it is in the desired range, print it Need each element to be the same width -> use fprintf() Otherwise, print the appropriate number of blanks How to code this? Need to process elements V(1), V(2),... one at a time Use a variable to hold the index into the array Call the variable i Start with i = 1 (smallest array index) After processing each element, increase i by 1 Stop after processing the last element

How to find the max index of a vector? length(v) returns the number of elements in V. For arbitrary array A: the largest dimension of A Now we have: i = 1; while i <= length(v) <process element at index i> <increase i by 1>

Refining the Script i = 1; while i <= length(v) if <the i th element is in range> <print it with a space on either side> else <print 4 spaces> <increase i by 1>

Refining the Script i th element is in range 70 <= V(i) && V(i) < 90 Print number V(i) with a space on either side: fprintf( %2d, V(i)) Print four spaces: fprintf( )

Final Script? i = 1; while i <= length(v) if 70 <= V(i) && V(i) < 90 fprintf( %2d, V(i)) else fprintf( ) i = i + 1; fprintf( \n );

Final Script i = 1; while i <= length(v) if 70 <= V(i) && V(i) < 90 fprintf( %6d, V(i)) else fprintf( ) i = i + 1; fprintf( \n );

Learn This Pattern! Iterating over the elements of a vector V using a while-loop: i = 1; % initialize index variable i while i <= length(v) <do something with V(i)> i = i + 1; % increment index!

Flowchart Pattern: Iteration over array with while

Iterating Over Some Elements Skip the first few elements: i = 3; while i <= length(v)... i = i + 1; Skip the last few elements: i = 1; while i <= length(v) 3... i = i + 1;

Iterating Over Some Elements Every other element (odd indices only): i = 1; while i <= length(v)... i = i + 2; Every other element (even indices only): i = 2; while i <= length(v)... i = i + 2;

5. for-loops provide a shorthand for bounded loops MATLAB, like many programming languages, has a shorthand for this kind of loop: for i=1:length(v) <statement> Read this as: for each (integer) value from 1 to length(v), execute <statement> with i having that value This is equivalent to the while-pattern just shown MATLAB automatically initializes i to 1, tests for exceeding the maximum before, and increments i after <statement> Usually <statement> uses i as an index into V But it is not required to do so

for-loops provide a shorthand for certain while-loops for i=1:length(v) <statement> This is equivalent to the while-pattern seen earlier MATLAB automatically initializes i to 1, tests for exceeding the maximum before, and increments i after <statement> <statement> will be executed length(v) times Usually <statement> uses i as an index into V But it is not required to do so

Example Script Revisited % i = 1 not needed! for i = 1:length(V) if 70 <= V(i) && V(i) < 90 fprintf( %6d, V(i)) else fprintf( ) % i = i + 1 not needed! fprintf( \n );

The General Form of a for-loop for <variable> = <vector expression> <statement> <variable> can be any MATLAB variable name. <vector expression> follows the pattern: <start value> [: <increment>] : < value> The effect is to begin with <start value> and increase by <increment> until the value exceeds < value> If the <increment> is not included it is set to 1

for-loop examples for index = 23:44... The loop is executed 22 times, with index having the values 23, 24, 25,..., 43, 44 for k = 3:4:19... Here k takes on the values: 3, 7, 11, 15, 19

Problem: Counting elements in a vector Write a function inrange() that takes three arguments: a vector (of any size) a lower bound an upper bound... and returns the number of elements in the vector that are between the bounds, i.e., that are at least the lower bound and less than the upper bound Use a for-loop to iterate over the elements

Counting Elements with Some Property function count = inrange(v, lower, upper) % inrange: count elements of vector between bounds count = 0; for j=1:length(v) if V(j) >= lower && V(j) < upper count = count + 1;

Iterating Over 2-Dimensional Arrays Requires Nested Loops How can we process each element of a twodimensional array? Elements are accessed via two indices: A(row,col) Example: A is a 3 x 5 matrix We need all 15 combinations of row and column #s: (1,1) (1,2) (1,3) (1,4) (1,5) (2,1) (2,2) (2,3) (2,4) (2,5) (3,1) (3,2) (3,3) (3,4) (3,5)

Example: Summing positive elements in a 3x5 array sum = 0; % to hold the sum % first row for col=1:5 if A(1,col) > 0 sum = sum + A(1,col); % second row for col=1:5 if A(2,col) > 0 sum = sum + A(2,col); % third row for col=1:5 if A(3,col) > 0 sum = sum + A(3,col);

Example: Summing positive elements in a 3x5 array sum = 0; % to hold the sum row = 1; % first row for col=1:5 if A(row,col) > 0 sum = sum + A(row,col); row = 2; % second row for col=1:5 if A(row,col) > 0 sum = sum + A(row,col); row = 3; % third row for col=1:5 if A(row,col) > 0 sum = sum + A(row,col);