0% found this document useful (0 votes)
10 views

Programming Midterm

Uploaded by

munamak13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Programming Midterm

Uploaded by

munamak13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

To design a

program
Th
Algorithm . Pseudocode Flowchart

② ③

7 -

Algorithm
set of comprehensive step
a
by step instructions to resolve a
problem
-

steps must be performed in correct order


-

Any algorithm consists of 5


major components
:
-

I-start

2 -

Input
3-task

4 - output
5 End

Example 1

* Create an
algorithm to
computed , display gross salary for an
hourly employee

Therefore ; (start , input , task output end (


, ,

1-start
2 -

Input the number of hours (N)


3 Input the (R)
hourly pay rate
-

4-
multiply the number of hours worked by hourly rate

.
5
Display the result of calculation that was performed in Step 4 .

6- End
Example 2

* Create
change the temperature from farenheit to centigrade.
an
algorithm to

c =( ·
F -

32)
Therefore : -

1-start
- enter value of
2
temp .
in Fahrenheit

3- subtract 32

4 -

Multiply the result in .


Step (3) by 5
5 -
divide result in Step (4) by 9 .

6
-
Display the result .
C

. End
7

Since to be its steps must be converted into code !


an
algorithm isn't
yet ready
run
;

&↓
-
eudocodeon Pseudocode Flowchart

informal lang. that has rules and


no
syntax
is not meant to be compiled or executed.
-

each statement in it ;
represents an
operation
that be performed
can in a
computer program!

Example 1

* create a Pseudocode to find sum of 2 numbers


·
we can
easily generate it by using the algorithim created earlier !

Algorithm VS . Pseudocode
> Start > Start .

- enter the two numbers in and M


> Input N

the variables N & M

> Sum them and save the result > S = N + M

in the variable S

> output the results > Displays


> End > End
-

They arent actual programming languages


cannot be compiled into an executable
program
-

They short term simple english to write code before


-

use or a

it gets converted into a


specific program .

Example
* Write the
algorithm and Pseudocode to find if
any given number is odd/even

Algorithm Pseudocode

. Start
1 . Start
1

.
2 enter value of the number .
2 Input N

the number (-1) to the "


3 raise
. 3 . x =
( 1) N
-

power of the number entered

in Step .
2

4 If
. if display
4 the result of step 3 is 1 then
then . X = 7
,

display the number is even N is even

. If the result of
5 Step 3 is -1 , . If X
5 = 1 then display
then the odd N is odd
display no .
is

Basic template for Pseudocode !

1 . Start

N
.
2
Input
3 .
S =
0

4 .
k = 1
. S
5 =
S + K
6
. If k = N then
display S : End
7 . k = k +1

8 : Go to step 5
Draw flowchart to computed the gross
a
display salary of
-

an

hourly employee !
·

Algorithm
1 -
Start
2 -

Input the number of hours (N)


3 Input the (R)
hourly pay rate
-

4-
multiply the number of hours worked by hourly rate

.
5
Display the result of calculation that was performed in Step 4 .

6- End

·
Flowchart

Start

sim ↓ all inputs in one step.

gross pay (G) =


NXR


Lisplay
a
J

Fend
Draw a flowchart to find the sum of 2 numbers .

(Using Pseudocode
·
pseudo code · Flowchart

1 start
Nand M
t
2
Input ↓
-

Enter
M
3 5 N
nam/
.
= +

4 .

Display S

. End
5
#ets
N = + M

Display

Send

Try one on your own !

* if have N numbers find the value


you maximum .

Start

But
N
yo numbers when have

Display
I max val .

E
MATLAB - Basics

Exponential & scientific notation

• When writing extremely large numbers we can use exponential


notation / scientific notation
• Either very large or very small numbers

Predefined constants

- Matlab has several predefined special constants, such as:-

• The constant pi = 3.14

• The symbol Inf = infinity


> A number so large that matlab can't present it exp.
-
5/0 generates the answer “Inf”

• The symbol NaN = not a number

• The symbol eps = the smallest number which when added to


one generates a number greater than it (1)

• Symbols i and j denote an imaginary unit, where i=j= sqrt(-1)


We use i and j to create + represent complex
numbers like:
X= 5 + 8i

* Try not to use the names of special constants as variables!


Complex number operations
Matlab handles complex number algebra automatically
• Exp: the no. C1 =1 -2i is entreated as it is or you can type
C1 = complex (1,-2)

Formatting -

Control how a number appears on the screen


commands

Command Description + example

Built in functions
Matlab has hundred of functions
• To compute sin x where X has a value in radius, you type sin (x)
• To compute cos x, type cos (x)
• Exponential function e^x is computed from exp(x)
• The natural logarithm, Inx, is computed by typing log(x)
• You compute base-l0 logarithm by typing log10(x)
• To inverse sine, or arcsine, is obtained by typing asin(x). It returns
an answer in radians not degrees
• The function asind(x) returns degrees
Arrays

• Matlab is good at handling a collection of numbers called arrays as if


they were single variables.
> An example of an array variable is one that contains numbers 0,4,3,6
in this order.
• We use square brackets to define the variable X to contain this collection
by typing x = [ 0,4,3,6]
• Elements of an array are separated by commas or spaces, but commas
are preferred to improve readability & avoid mistakes
* when the variable has different order of numbers it isn't the same!
• if we were to type an array without the square brackets it would
treat this as separate inputs
• We can add 2 arrays x and y to produce another array z by typing the
single line z =x + y.
• We don't type all the numbers in an array in if they are regularly spaced
instead; we type the first number and the last number with the spacing
in the middle separated by colons
• exp: u= 0: 0.1: 10
• To see a particular array we type the no.in btw brackets after the U for
example u(7)

You can use length to determine how many values are in an array.

Polynomial roots

We can describe a polynomial with an array whose elements are the


polynomials coefficients starting with the highest power
• polynomial roots can be found with the roots (a) function where a is the
polynomials array
• We could've combined the two commands into one single
command roots ([ 1, -7, 40, -39])
Saving and retrieving your workspace variables

• if you want to continue a session at a later time you must use the save
and load commands
• Typing save causes matlab to the workspace variables

• To retrieve the workspace type load, you can then continue your work
session
• To save the workspace variables in another five named filename-mat
type, save filename

Plotting with Matlab


Script files -

pptX.

>
- A file that contains all commands and it , it will have
by running
performed the the command window
operation you type
same as when in

When
you type its name in the command window it will run .

>
- When Matlab M-file should be used
Saving programs a

e 1 m
g program
.
: - .

* 2 types of on-files

function firs
- cript files (command files

Creating a
script file
:
-

1-select New from file menu = > then select script


.
2 use the Keyboard & Edit menu to create + edit file

3-once done select save from file menu in editor/debugger


4- After its been saved write file name in command window

5-you should see results displayed

Advantages : -

commands
* avoid
typing long lengthy
* Do not script file the that of
give a same name as

a command

to check if the name alr exists type :


-

· exist
(example 1')
= if it shows O then it doesn't exist
I if it shows 1 then it exists
Built-in functions :
they are like building blocks that form the
basis of other Matlab functions

>
-
Debugging
A
process of finding & removing the "bugs" or errors a
program
might have

Errors
may be
:
-

1-
Syntax errors

Styping the
wrong command like putting paranthesis & comma
2- Runtime errors

(incorrect mathematical calculations

The
Symbol % designates a comment
,
this isn't executed by Matlab
· used to document files

the symbol may put anywhere in the line


be
to the right of % gets ignored
anything
·

e
g
.

% This is a comment
3) x = 2+ 3 % so is this
-

to the of %
3) X =
right
5 So its not considered !

Controls Input/output

-disp >
-
short for display (used to
display the value of variables only
-disp(t) >
-
displays variables name as shown in Matlab

disp function also display a


message to the user such
:

can as
-

: -

disp (' predicted speed 1( :

Ans => Speed =


69 ;
input1 displays text on screen ; awaits for the
-

user

write specifical
to
somthing and then stores it in a variable

input /(please of )
-

X =
enter value X :

# if
you were to type X and press enter

x =
5

-
A string variable is composed of letters (text)

menu >
-
generates menu with choices for user input

* Try writing a script file.


Arrays
one of the its ability to handle collections of items
strengths of Matlab is
-

known as
'Arrays' as one
single entity
.

We also
specify the location of any value
using Cartesian coordinates
-

can

or vectors in X, y , and z directions .

· A rector can
only have one column
,
or
only one row

· to
type a row vector in MATLAB , you just type the elements (e g .
.
1
,
2
, 3)
inside square brackets [7 .

you can either


separate elements by a
space or
using a commo ;

however you are less likely to make errors using commas .

·
For column vector -
:

separate the elements


-

you can
by semicolcons !
-

Alternatively you ,
can also create a now rector then use the

transpose notation (1) ; to covert a row Vector >


- column Vector

or Vice versa.

>
- Row vectors
(horizontally)
(vertically) /
>
-
column vectors

Vectors
·
can
easily be combined to other vectors ; this process is called

"appending"
M=
J

vector 'M' [r , . The


eg-to create a new row we type
vector followed
result will be the combination of elements for r
by
the elements of Vector 'M' .
Waking a new row

the (: ) vector of
· colon operator generates a
large regularly spaced elements

exp :
typingX = m:
g:n

would create vector of values with the


a x
spacinga
-

the first value is m


.

-
the last value is n.

* if m-n is the last value would be n!


an
interger multiple of 9 ;
if not then
*
; it creates the rector up
to the
greatest integer not

our n-value .

Demonstration :

> X = 0: 2 : 8 -
> m -
n = 0-8 = 8 which is a
multiple of 21
therefore the vector X =
[0 ,
2
,
9, 6
, 8
while if we type this insted

x = 0 : 2: 7 >
-
m-n = 0 -
7 = 7 not a
multiple of 2X

therefore our vector X stops after 6 : X =


50 ,
2 ,
4, 6)
> The increment be
a can
negative
-
.

if thats the case the m-value should be than


greater our n !

exp :
v =
10 : - 2 : 4

line space command creates


linearly spaced row vector
·
a

syntax :
linespace (x1 , X Limit
&
lower limit
no · of
points

·
logspace command creates an of
logarithmically spaced elements
array
Syntax :
logspace (c ,
b ,
n)
Yno of
· prints
no. btw
10d los

An & two-dimensional that


array having rows columns is a
array can be

called a 'matrix'
denoted by bold letters .
usually case

a size of an
array is determined by the no ·
of rows X no · of columns

·
exp .
3x2 >
- 3 rows a 2 colums

* No of rows mentioned first


.
are
always !
-

Indices which are subscripts like (ij) are used to indicate an elements

location with to its column .


respect rows +

> Most direct to create matrix is to the matrix row


way a type by row,

separating each element


by their rows & columns .
exp : A =
(2 ,
4 ,
10 ; 16 3 7] ; creates the following
, ,

A =

[41]
* When matrix has & the next
a
many elements
you can
press Enter Continue
typing on

finished when bracket (3) .


line ... MATLAB knows
you are
you add the closing

Transpose operation does the following


-

:
-

a =
[ = 55] a =
[ -]
· it swiches the rows & columns

vector into
converts a row a column vector
!
Alternatively type (') to
transpose the and still
-

the same
you can
array get
exact result .

Array Indices

>
-
Array indices arerow
& column numbers of an element in
any given array
to track the

location of elements

exp : the notation v(5) refers to the fifth element in the vector .
V

· A (2 , 3) refers to the element in row 2


,
column 3 in Matrix A .

Can be used to correct entries in without


retyping the entire
array
-

an
array
to of
exp .

change the element in row7 ,


column 3 a matrix D to 6

you type : -
D (1 3)
,
= 6

Array addressing
4 v (i) all and of vector
represents rows columns

& V (2 : 5) "the second


through fifth elements (12) ,
V(3), V(4) , +(5)
2) A ( :, 3) denotes all the elements in the 3rd column of Matrix A .

& A (3 ,: ) /" 1 in the 3rd row of A


.

Empty array

contains elements and is expressed [] .


-

no as

exp .

A(3 : ) =
5) deletes the 3rd row in A.

A ( :, 2 4) 5] : =
"and
through 4th columns in A
clear used to clear all variables that
is
you specify
-

exp : A - clears A
clear
only before
proceeding with
any more

commands .

The (A) function returns element A if A


max the
algebraically in is a

elements.
Vector having all real

A =
C -
2 + 2i
,
4 + i ,
-

1 -

3i] ;
B =
max(A)

Output
B = 4 . 000 + 1 , 000 :

* if A has one or more complex elements the max , min and sort
, ,

functions act on the abs . values of the element that has the

largest magnitudee.

=
[
expi

max(Al returns the vector [10 -5],

·
Midterm Review !

Pseudocode P KK24341 K
example Comput
= ...
:

1 .

Start
.
2 Inputn We
*
changed the variable

3 .

SoP1 K to i; since we alr

4 . i =
1 have .
K

5 .
p =
Paki
j

<
6 .

If EU then
displend
i+
7 .#+ i =

easy elp !
8 to 5 will be
go
.

(know it well
difficult
Focus
* on the labwork !!! nothing more

any factorial
Find the value of number
example 2 :

4) =
4x3X2x1 = 24

I I
. Start
1 1 Start
.

.
2 Input N
.
2 N
Input
.
3 S =
1
3 . 5 =

4 .
k
= 1
4 K = N

first
.

5 . 5 = 55k
5 .

S =
SAK
6 .
If k = N then disp (end
:
6 If K =
1 then disp (end)
:

7
.
4 =
k+1
7. k =
k - 1

8 .

go to 5 8 go .
to 5
No
>
-
explanation
No
* convert from decimal to

something

+ understand.
focus on these !
-> Practice
>
-
coding (Labwork) > start
- with the
>
-
Pseudo code lab work.

> Flow
- Chart
3 understand
(EASY inshallah)MID-
well ! TERM

Application of
Arrays !

Polynomial operations
-

· The function
poly(r) computes the coefficients of the
polynomial
whose roots are
specified by the array r .

the result that contains the


polynomial's coefficient.
is
array
a row

p =

poly([1 .

To add 2 that describe coefficient


polynomials add the
·
their
, arrays

You might also like