Top Banner
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort
16

Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

Dec 19, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

Lecture 5 ReviewProgrammingProgram Structures

ComparisonRepetition: looping or iterationConditional execution: branching

Bubble Sort

Page 2: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

ReviewMatrices – Two dimensional ArraysPlotting – Powerful Matlab commands used to

plot various functions over a specified range.>>plot(x,y) % Plot y as a function of xxlabel(‘axis name’), ylabel(‘yaxis name’),

title(‘Plot Title’)Importing Data

xlsread(‘file name’) % reads the data from an excel spreadsheet and stores them in a two dimensional array

Page 3: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

Programming with Script FilesPrograms are contained in script files also known as M-files. A program can be ran by typing its name at the command window.Example: Go to “File” -> “New” -> M-file The Editor window will appear (next slide) Type the following commands:% Program example1 . m% This program computers computes the sine of the square root,% and displays the result .x= sqrt ([3:2 :11]) ;y= sin(x)xlabel (‘x’) ; ylabel (‘f (x)’) ; grid Save as “example1” To run program type >>example1 on the command window NOTE: The m-file location path should be the same as the path

shown in the current directory window.

Page 4: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

Programming with Script FilesTo create a new script file:1. Go to the Matlab Desktop

Menu Toolbar.2. File Menu3. New4. M-FileTo open and existing script

file:5. Go to the Matlab Desktop

Menu Toolbar.6. File Menu7. New8. M-FileTo save a script file:9. Go to the Editor Window

Menu Toolbar10. File Menu11. Save As

Matlab code should be typed in the editor window

Page 5: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

Programming with Script Files

NOTE: The m-file location path should be the same as the path shown in the current directory window.

Saving an M-file

Setting the Current Directory Path

Page 6: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

Program StructuresTo enable the implementation of computer

algorithms, a computer language needs control structures for

ComparisonConditional execution: branchingRepetition: looping or iteration

Page 7: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

ComparisonComparison is achieved with relational

operators. The result of a comparison may also be modified by logical operators.

Logical operators are used to combine logical expressions (with “and” or “or”), or to change a logical value with “not”.

Operator Meaning

& And

| Or

~ Not

Page 8: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

Example – Logical Operators>> a = 2; b = 4;>> aIsSmaller = a < b;>> bIsSmaller = b < a;>> bothTrue = aIsSmaller & bIsSmallerbothTrue =0>> eitherTrue = aIsSmaller | bIsSmallereitherTrue =1>> ~eitherTrueans =0

Page 9: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

Conditional Execution or Branching:As the result of a comparison, or another logical

(true/false) test, selected blocks of program code are executed or skipped.

Conditional execution is implemented with if, if...else, andif...elseif constructs.

There are three types of if constructs1. Plain if2. if...else3. if...elseif

Syntax:if expressionblock of statementsend

Page 10: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

Examples1. >>if a < 0, disp(’a is negative’); end2. if x < 0 error(’x is negative; sqrt(x) is imaginary’);

else r = sqrt(x); end3. if x > 0

disp(’x is positive’);elseif x < 0disp(’x is negative’);elsedisp(’x is exactly zero’);end

Page 11: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

Repetition or LoopingA sequence of calculations is repeated until

either1. All elements in a vector or matrix have been

processed or2. The calculations have produced a result that

meets a predetermined termination criterionLooping is achieved with for loops and while

loops.Syntax:for index = expressionblock of statementsend

Syntax:while expressionblock of statementsend

Page 12: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

For LoopExample: Sum of elements in a vector

x = 1:5; % create a row vectorsumx = 0; % initialize the sumfor k = 1:length(x)sumx = sumx + x(k);end

Example: A loop with an index incremented by twofor k = 1:2:n...end

Example: A loop with an index that counts downfor k = n:-1:1...end

Page 13: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

While Loopwhile loops are most often used when an

iteration is repeated until some termination criterion is met.

Example>> while S+ (n+1)^2 < 100n = n+1; S = S + n^2;end>> [n, S]ans =6 91

Page 14: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

Bubble SortThe bubble sort works by iterating down an array

to be sorted from the first element to the last, comparing each pair of elements and switching their positions if necessary.

This process is repeated as many times as necessary, until the array is sorted. Since the worst case scenario is that the array is in reverse order, and that the first element in sorted array is the last element in the starting array, the most exchanges that will be necessary is equal to the length of the array. Here is a simple example:

Page 15: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

Bubble Sort Code – For Loop

Page 16: Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.

Assignment 51. Determine how long it will take to

accumulate at least $10,000 in a bank account if you deposit $500 initially and $500 at the end of each year , if the account pays 5 percent annual interest.

2. Use while loops to perform bubble sort.