PC Intro Devamı

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 143

EXAMPLES

Algorithms and Programming Languages


Question-1

• Write an algorithm to determine a student’s final grade .


• Note That:
– Indicate whether it is passing or failing
• If the final grade is greater than or equal to 50 the
result is PASS; otherwise, FALL.
– The final grade is calculated as the average of four
marks.
– Firstly, Write the pseudocode of the algorithm
– Secondly, Draw the flowchart of the algorithm
• The output must be represented as a document.
Answer -1 For Pseudocode
1. START
2. Input a set of 4 marks.
3. Calculate their average by summing and dividing by 4
4. IF average is below 50 THEN Print “FAIL”
ELSE Print “PASS”
5. END

Step 1: START
Step 2: Input M1,M2,M3,M4
Step 3: GRADE  (M1+M2+M3+M4)/4
Step 4: IF (GRADE < 50) THEN Print “FAIL”
ELSE Print “PASS”
ENDIF
Step 5: END
Answer -1 For Flowchart
Step 1: START
Step 2: Input M1,M2,M3,M4
START
Step 3: GRADE  (M1+M2+M3+M4)/4
Step 4: IF (GRADE < 50) THEN Print “FAIL”
M1,M2,M3,M4
ELSE Print “PASS”
ENDIF
GRADE=(M1+M2+M3+M4)/4
Step 5: END
NO GRADE<50 YES

END
Another Way For Answer -1
START
Step 1: START
Step 2: Input G1,G2,G3,G4
G1,G2,G3,G4 Step 3: AVR  (G1+G2+G3+G4)/4
Step 4: IF (AVR < 50) THEN
AVR=(G1+G2+G3+G4)/4 Result  “FAIL”
ELSE
NO YES Result “PASS”
AVR>=50
ENDIF
Step 5: OUTPUT Result
Result=“FALL” Result=“PASS”
Step6: END

Result

END
QUESTION-2

Write an algorithm that find biggest among two numbers.


Note That:
– Firstly, write the pseudocode of the algorithm.
– Secondly, draw the flowchart of the algorithm.
– The numbers must be entered by the user.
– Display the largest value with an identifying message.
• Like: The largest value is …..
Step 1: START
ANSWER -2 For Step 2: Input VALUE1, VALUE2
The Pseudocode and Flowchart Step 3: IF (VALUE1 > VALUE2) THEN MAX  VALUE1
ELSE MAX  VALUE2
ENDIF
START
Step 4: Print “The largest value is”, MAX
Step 5: END

VALUE1,VALUE2

YES NO
VALUE1>VALUE2

MAX = VALUE1 MAX = VALUE2

“The Largest Value is”, MAX

END
ozi
QUESTION -3
Write an algorithm that finds the largest number among three numbers.
Note that:
• The numbers must be entered by the user.
• You must assign the numbers to the variables called as
• N1, N2, N3 and MAX for the biggest number.
• You must only use IF statement.
• All of IF statements has only one condition NOT including
logical operators.
• Store the value of the largest number into a storage device.
• Firstly, write the pseudocode of the algorithm.
• Secondly, draw the flowchart of the algorithm.

ozi 8
ANSWER-3 For the Pseudocode
Step 1: START
Step 2: Input N1, N2, N3
Step 3: if (N1>N2) then
if (N1>N3) then MAX  N1
else MAX  N3
endif
else
if (N2>N3) then MAX  N2
else MAX  N3
endif
endif
Step 4: Store MAX
Step 5: END
ozi
ANSWER - 3 For Flowchart
START

N1, N2, N3

MAX = MAX
N2 > N3 N1 > N2 N1 > N3
N2 =N1

MAX = N3 MAX=N3

MAX

END 10
QUESTION -4
Write an algorithm that to find the sum of the first 50 natural numbers.
Note that:
• You must use only two variables called as “counter” and “sum”
for the counter and addition, respectively.
• You must use the WHILE loop.
• Display the sum on the screen.
• Firstly, write the pseudocode for the algorithm.
• Secondly, draw the flowchart of the algorithm.

ozi 11
ANSWER-4
STEP 1: START
STEP 2: sum  0, counter  1
STEP 3: WHILE (counter <= 50)
START Do
sum  sum + counter
sum = 0
counter = 1
counter  counter + 1
ENDWHILE
STEP 4: OUTPUT sum
STEP 5: END
counter <= 50 sum

sum=sum + counter
END
counter=counter + 1
QUESTION -5

Draw a flowchart to take a positive integer from user and calculate the
factorial of that number.
Note that:
• Assign the positive number entered by the user to the variable “N”
• You must use a variable called as “Fact” that indicates the factorial
of that number.
• You must use FOR loop.
• Display the result on the screen.
• Firstly, write the pseudocode for the algorithm.
• Secondly, draw the flowchart of the algorithm.

ozi 13
ANSWER-5
START

STEP 1: START N

STEP 2: Input N
STEP 3: Fact←1, i←1 Fact = 1
i=1
STEP 4: Repeat the steps until i=N
4.1: Fact←Fact*i
4.2: i←i+1
i <= N Fact
STEP 5: Output Fact
STEP 6: END

Fact=Fact * i
END
i=i+1
ANSWER-5

STEP 1: START
STEP 2: Read value of N
STEP 3: Fact ← 1
STEP 4: FOR (i←1 to N)
DO
Fact←Fact*i
ENDFOR
STEP 5: Display Fact
STEP 6: END
ozi 16
ozi 17
X Output N Output T
85 ?=2 ?= 85
3190 ?=4 ?=3190
-40 ?=1 ?= -40

ozi 18
ozi 19
Introduction to Matlab
Outline:
❑What is Matlab?
• Matlab Screen
• Variables, array, matrix, indexing
• Operators (Arithmetic, relational, logical )
• Display Facilities
• Flow Control
• Using of M-File
• Writing User Defined Functions
• Conclusion
What is Matlab?
❑ Matlab is basically a high level language which has many
specialized toolboxes for making things easier for us
❑ How high?

Matlab

High Level
Languages such as
C, Pascal etc.

Assembly
Matlab
Series of
Matlab
commands
Command
m-files mat-files
Line

functions Command execution Data


Input like DOS command storage/
Output window loading
capability
Getting started – Matlab Desktop

Current Directory

Workspace

Current Folder
Command Window

Command History

m file comment
Matlab Screen
Command Window: Type commands Current Directory:View folders and m-files
Workspace: View program variables Command History: View past commands
Double click on a variable to Save a whole session
see it in the Array Editor using diary
MATLAB

▪ Managing the workspace


➢The results of one problem may have an effect on the next one
➢Use whos to list current variables and give information on size,
shape, type etc.
➢Issue a clear command at the start of each new independent
calculation to remove variables and functions from memory
(and the workspace)
➢clear t
➢clears variable t
➢clear
➢clears all variables
➢clear all
➢clears all variables, globals, functions, and MEX links
7
MATLAB

▪ Miscellaneous commands
➢To clear the Command Window
>> clc
➢To clear the current figure
>> clf
➢To abort a MATLAB computation
ctrl-C
➢To continue a line

➢To recall previous commands
Up arrow ( ), ctrl-p or double click command history pane
8
MATLAB

▪ Getting help
➢Use help to request info on a specific topic
➢ displays help in the command window
>> help sqrt

➢Use doc function to open the help browser window


>> doc plot

➢Use lookfor to find function by keywords


>> lookfor regression

9
Variables
• Don’t have to declare type
• Don’t even have to initialise
• Just assign in command window
>>
>> a=12; % variable a is assigned 12

Matlab comment
prompt suppress operator
assign
command
operator
output
10
Variables (continued …)
• View variable contents by simply typing the
variable name at the command prompt
>> a
a=
12
>>
>> a*2
a=
24
>>

11
Variables
• No need for types. i.e., int a;
double b;
float c;

• All variables are created with double precision unless specified


and they are matrices.

• After these statements, the variables are 1x1 matrices with


double precision
Array, Matrix
Editor Window Command Window
X=[1 4 7 9]; X=
Y=[1 2 3; 7 8 9; 4 5 6];
1 4 7 9
A=[ 1 2 3; 4 5 6];
trnp=A'; Y=

A= 1 2 3
1 2 3 7 8 9
4 5 6 4 5 6

trnp =
1 4
2 5
3 6
Long Array, Matrix

t=1:10

t= 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

a=2:-0.5:-2

a = 2.00 1.50 1.00 0.50 0 -0.50 -1.00 -1.50 -2.00

x=[1:3;5:7]

x=

1.00 2.00 3.00


5.00 6.00 7.00
THE COLON OPERATOR
• Colon operator occurs in several forms
– To indicate a range (as above)
– To indicate a range with non-unit increment
>> N = 5:10:35
N =?
5 15 25 35
>> P = [1:3; 30:-10:10]
P =?
1 2 3
30 20 10
• To extract ALL the elements of an array ?
extracts everything to a single column vector

>> A = [1:3; 10:10:30; >> A(:)


ans =
100:100:300] 1
A =? 10
100
1 2 3
2
10 20 30 20
100 200 300 200
3
30
300
Numerical Array Concatenation [ ]

Use [ ] to combine >> a=[1 2 3;4 5 6]


Use square
existing arrays as a =
brackets [ ]
matrix “elements”
1 2 3
Row separator: 4 5 6
semicolon (;) >> cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]

Column separator:
cat_a =?
space / comma (,) 1 2 3 2 4 6
4 5 6 8 10 12
3 6 9 4 8 12
12 15 18 16 20 24
N.B. Matrices
5*a 5 10 15 6 12 18
MUST
20 25 30 24 30 36
be rectangular.
4*a
Generating Vectors from functions
• zeros(M,N) MxN matrix of zeros

• ones(M,N) MxN matrix of ones

• rand(M,N) MxN matrix of uniformly


distributed random
numbers on (0,1)
>> I=eye(4) (i.e., identity matrix)
I=
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

>> A=magic(4) (i.e., magic square)


A=
16 2 3 13 =34
5 11 10 8 =34
9 7 6 12 =34
4 14 15 1 =34
=34
=34
=34
=34
Matrix generation

▪ Colon operator in a matrix

➢Colon operator is very useful in the usage of MATLAB

➢For example, A(m:n,k:l) specifies portions of a matrix A:


rows m to n and columns k to l.

➢Examples:
A(2:3, 2:3)
A(2, :) note: just colon means all elements
A(2:end, :) note: use of end keyword

20
Array Subscripting / Indexing
The matrix indices begin from 1 (not 0 (as in C))

The matrix indices must be positive integer

1 2 3 4 5
A= 4
1
10
6
1
11
6
16
2
21

2 8 2
1.2 7 9 12
4 17
25 22
A(1:5,5) A(1:end,end)
3 7.2 3
5 8
7 13
1 18
11 23 A(:,5) A(:,end)
A(21:25) A(21:end)’
A(3,1) 4 0 4
0.5 9 4 14
5 19
56 24
A(3)
5 23 5
83 10 13 15 0 20
10 25
A(4:5,2:3)
A([9 14;10 15])
• Use () parentheses to specify index
• colon operator (:) specifies range / ALL
• [ ] to create matrix of index subscripts
• 'end' specifies maximum index value
EXAMPLE
A=[3 4 5;11 12 13; 7 8 9];

Write a matrix of index subscripts by


using the matrix ‘A’ for obtaining below

=? A([7:end]')
A([1 3 4 6 7 9;2 5 8 3 6 9])=?
3 7 4 8 5 9
11 12 13 7 8 9
A(-2), A(0) Error: ??? Subscript indices must either be real positive integers or logicals.
A(4,2) Error: ??? Index exceeds matrix dimensions.
Colon Operator
j:k is the same as [j,j+1,...,k] is empty if j > k
j:i:k is the same as [j,j+i,j+2i, ..,k] is empty if i > 0 and j > k or if i < 0 and j < k
A(:,j) is the j-th column of A
A(i,:) is the i-th row of A
A(:,:) is the equivalent two-dimensional array. For matrices this is the same as A.
A(j:k) is A(j), A(j+1),...,A(k)
A(:,j:k) is A(:,j), A(:,j+1),...,A(:,k)
A(:,:,k) is the k-th page of three-dimensional array A.
A(i,j,k,:) is a vector in four-dimensional array A. The vector includes A(i,j,k,1),
A(i,j,k,2), A(i,j,k,3), and so on.
A(:) is all the elements of A, regarded as a single column. On the left side of an
assignment statement, A(:) fills A, preserving its shape from before. In this
case, the right side must contain the same number of elements as A.
Concatenating Matrices
• Matrix concatenation is the process of joining one or more matrices to make a new matrix.
• The brackets [] operator discussed earlier in this section serves not only as a matrix
constructor, but also as the MATLAB concatenation operator.
• The expression C = [A B] horizontally concatenates matrices A and B.
• The expression C = [A; B] vertically concatenates them.

This example constructs a new matrix C by concatenating matrices A and B in a vertical


direction:

A = ones(2, 5) * 6; % 2-by-5 matrix of 6's Concatenate matrices X and Y


B = rand(3, 5); % 3-by-5 matrix of random values in a horizontal direction:

C = [A; B] % Vertically concatenate A and B >> x=[1 2 3];


C= >> y=[4;5;6];
6.0000 6.0000 6.0000 6.0000 6.0000
6.0000 6.0000 6.0000 6.0000 6.0000 C=[?];
0.6154 0.7382 0.9355 0.8936 0.8132
0.7919 0.1763 0.9169 0.0579 0.0099 C=[x;y']
0.9218 0.4057 0.4103 0.3529 0.1389
1 2 3 4 5 6
Matrix and Array Operators

Matrix Operators Array operators


() parentheses
Common Matrix Functions
inv matrix inverse
' complex conjugate .' array transpose
transpose det determinant
^ power .^ array power
rank matrix rank
* multiplication .* array mult. eig eigenvectors and
eigenvalues
/ division ./ array division svd singular value dec.

\ left division norm matrix / vector norm

+ addition

- subtraction

>> help ops >> help matfun


Matrices Operations
A=[1 2 3;4 5 6; 7 8 9]; B=[2 1 2;1 3 2;2 4 3];
1.00 2.00 3.00 2.00 1.00 2.00
4.00 5.00 6.00 1.00 3.00 2.00
7.00 8.00 9.00 2.00 4.00 3.00

3.00 3.00 5.00 -1.00 1.00 1.00


5.00 8.00 8.00 3.00 2.00 4.00
9.00 12.00 12.00 5.00 4.00 6.00

10.00 19.00 15.00 A' B'


25.00 43.00 36.00 1.00 4.00 7.00 2.00 1.00 2.00
40.00 67.00 57.00 2.00 5.00 8.00 1.00 3.00 4.00
3.00 6.00 9.00 2.00 2.00 3.00
Element-by-element operations:
Symbo Operation Form Examples

+ Scalar-array addition A + b [6,3]+2=[8,5]

- Scalar-array subtraction A – b [8,3]-5=[3,-2]

+ Array addition A + B [6,5]+[4,8]=[10,13]

- Array subtraction A – B [6,5]-[4,8]=[2,-3]

.* Array multiplication A.*B [3,5].*[4,8]=[12,40]

./ Array right division A./B [2,5]./[4,8]=[2/4,5/8]

.\ Array left division A.\B [2,5].\[4,8]=[2\4,5\8]

.^ Array exponentiation A.^B [3,5].^2=[3^2,5^2]

2.^[3,5]=[2^3,2^5]

[3,5].^[2,4]=[3^2,5^4]
A= 11
–9
5
4
B = –7
6
8
2
C = A.*B C = 11(–7)
–9(6)
5(8) =
4(2)
–77
–54
40
8

24 20 B = –4 5 C = 24/(–4) 20/5 = –6 4
A=
–9 4 3 2 C = A./B –9/3 4/2 –3 2

A=[1 2 3;4 5 6; 7 8 9] B=[2 1 2;1 3 2;2 4 3]

A.^B
1.00 2.00 9.00
4.00 125.00 36.00
49.00 4096.00 729.00
>> A = [1:3;4:6;7:9]
A =
1 2 3 Many common functions operate on
4 5 6 columns by default
7 8 9

>> mean(A) Mean of each column in A


ans =
4 5 6

>> sum(A)
ans =
12 15 18

>> mean(A(:)) Mean of all elements in A


ans =
5
Boolean (logical) operators
== is equal to isempty() true if matrix is empty, []
> greater than isfinite() true where elements are
< less than finite
>= greater than or equal to isinf() true where elements are
<= less than or equal to infinite
~ not any() true if any element is non-
zero
& and
all() true is all elements are
| or non-zero
x=1:10;
1.00 2.00 3.00 4.00 5.00 6.00 7.00 8.00 9.00 10.00

x>=5 ? 0 0 0 0 1 1 1 1 1 1

y=x.^0.5;
1.00 1.41 1.73 2.00 2.24 2.45 2.65 2.83 3.00 3.16

Y<3 ? 1 1 1 1 1 1 1 1 0 0

A= x>=5 B= Y<3
Then
A&B? A|B
A&B= 0 0 0 0 1 1 1 1 0 0
A|B = 1 1 1 1 1 1 1 1 1 1
x=11:20;
11 12 13 14 15 16 17 18 19 20

y=x.^0.5;
3.32 3.46 3.61 3.74 3.87 4.00 4.12 4.24 4.36 4.47

A= x>=14 0 0 0 1 1 1 1 1 1 1
B= Y<4 1 1 1 1 1 0 0 0 0 0
Convert logical index to numeric index by using function ‘find’
FOR A&B
A&B= 0 0 0 1 1 0 0 0 0 0
i=find(A&B)
i= 4 5
x(i)=14 15

y(i)=3.74 3.87
Matlab Conditional Structures

if expression cond. a = input('number1=');


sentences b = input('number2=');
if a==b
elseif expr. cond. fprintf('a is equal to b \n');
elseif a>0 && b>0
sentences fprintf('both positive \n');
elseif a<0 && b<0
else fprintf('both negative \n');
sentences else
fprintf('other case \n');
end end
Matlab Iteration Structures (I)
for variable = expr
sentence;
...
sentence;
end
M=
M = ones(3,3); suma = 0;
for i = 1:3
1.00 1.00 1.00
for j = 1:3 1.00 1.00 1.00
suma = suma + M(i,j); 1.00 1.00 1.00
end sum = 9
end
fprintf('sum = %d\n',suma);

M = rand(10,10); sumx = 0;
for i = [2,5:8] % rows 2 5 6 7 8
for j=[1:5,8:9] %columns 1 2 3 4 5 8 9
sumx=sumx+M(i,j);
end
end
fprintf('The Sum=%d',sumx);
Matlab Iteration Structures(II)
while expr
sentence;
...
sentence;
M = rand(4,4);
end i = 1; j = 1; suma = 0;

0.9134 0.5469 0.9706 0.1419 while i <= 4


0.6324 0.9575 0.9572 0.4218 while j <= 4
0.0975 0.9649 0.4854 0.9157 suma = suma + M(i,j);
0.2785 0.1576 0.8003 0.7922 j = j+1;
end
i = i+1; j=1;
sum(M) 1.9218 2.6269 3.2134 2.2716
end

fprintf(‘suma = %f\n’,suma);

sum(sum(M)) 10.0337
Example: Solving Equations
A = [-1 1 2; 3 -1 1;-1 3 4];
-x1 + x2 + 2x3 = 2
b = [2;6;4];
x = inv(A)*b 3x1 - x2 + x3 = 6
x= -x1 + 3x2 + 4x3 = 4
1.0000
-1.0000
2.0000
x = A\b
x=
1.0000
-1.0000
2.0000
Predefined Special Operators
pi 
i, j i(-1) eg. 2i = 2 -1
Inf Infinity
NaN Not-a-Number
clock Vector [y,m,d,hour,min,sec]
date Current date eg. 13-Feb-2004
ans Stores the result of an expression
Mathematical Functions
abs(x) absolute value
cos(x) cosine (rad)
sin(x) sine (rad)
tan(x) tangent (rad)
acos(x) arc cosine (rad)
asin (x) arc sine (rad)
atan(x) arc tangent (rad)
angle(x) Phase angle (rad)
exp(x) ex
log(x) Natural Log (ln x)
log10(x) Base 10 Log
sqrt(x) Square Root
mod(x,y) Remainder of x/y
angle=rad2deg(pi);
A=sin(pi/2);
B=cos(pi);
x=(0:15:90)*pi/180;
C=sin(x);

angle = 180.00

A = 1.00

B = -1.00

x= 0 0.2618 0.5236 0.7854 1.0472 1.3090 1.5708

C= 0 0.2588 0.5000 0.7071 0.8660 0.9659 1.000000


Rounding Functions
round(x) Rounds to nearest integer
ceil(x) Rounds up to nearest integer
floor(x) Rounds down to nearest int.
fix(x) Rounds to nearest int. towards 0
A=round(5.9); ? 6.00
B=ceil(3.1); ? 4.00
C=floor(7.9); ? 7.00
D=fix(-9.9); ? -9.00
Characters in fprintf Display Function
%d Integer format
%e Exponential format
%f Floating point format
%g Floating point or exponential,
whichever is shorter
\n Skip to a new line
Format Command
format short > 4 digits after decimal
format long > 14 digits after decimal
format short e > 5 digits plus exponent
format long e > 16 digits plus exponent
format bank > Two decimal digits
format rat > approximate ratio
END…
Introduction to Matlab
Outline:
❑What is Matlab?
• Matlab Screen
• Variables, array, matrix, indexing
• Operators (Arithmetic, relational, logical )
• Display Facilities
• Flow Control
• Using of M-File
• Writing User Defined Functions
• Conclusion
MATLAB - Plotting
• To plot the graph of a function, you need to take the
following steps −
• Define x, by specifying the range of values for the variable x, for
which the function is to be plotted
• Define the function, y = f(x)
• Call the plot command, as plot(x, y)

Plot the function y = x2

x = [1 2 3 4 5 6 7 8 9 10];
y = x.^2;
plot(x, y)
MATLAB - Plotting
Draw the graph of y = sin(x)
Note That:
• In the interval of [0, 2π].
• The values on the X-axis must be represented as the degrees.
• You must label the x-axis and y-axis and title for the graph
• For X-axis, “Angle 0<x<360” and For Y-axis, “sin(x)”
• For the title, “Line Plot of Sine Between 0 and 360 degrees”

x=0:360;% degrees
y=sin(x*pi/180);
plot(x,y);
xlabel('Angle 0<x<360');
ylabel('sin(x)');
title('Line Plot of Sine Between 0 and
360 degrees');
Plot the function cos(x) between 0≤x≤2π
• Build an x-array of 100 samples between 0 and 2π.
title('X Ranges From 0 to 2\pi');
x=linspace(0,2*pi,100);

• Calculate cos(.) of the x-array

ylabel('Cosine Values of X');


y=cos(x);

• Plot the y-array

plot(x,y);

• Add a title and label the axes


xlabel('X(rad)');
ylabel('Cosine Values of X');
title('X Ranges From 0 to 2\pi'); xlabel('X(rad)');
Showing multiple plots together in the same figure
• Build x vector including values between 0 and 4π at step of pi/12.
• Build y1 and y2 as sine and cosine values of x.
• Plot both sets of data.
• Add the title, labels, legend and grid lines .
• Line Plot of Sine and Cosine Between 0 and 4π
• Sine and Cosine Values for y-axis
• 0<x< 4π for x-axis
• y1=sin(x) and y2=cos(x) for legend

x = 0:pi/12:4*pi;
y1 = sin(x); y2 = cos(x);
figure
plot(x,y1,x,y2);
title('Line Plot of Sine and Cosine Between 0 and 4\pi');
xlabel('0 < x < 4\pi');
ylabel('Sine and Cosine Values');
legend('y1 = sin(x)','y2 = cos(x)');
grid on;
Line and Marker styles
Specifier Line Style Example For Line Style
- Solid line (default)
theta = 0:pi/6:2*pi;
Dashed line plot(theta*180/pi,sin(theta), '--')
--
: Dotted line

-. Dash-dot line
Line and Marker styles
Specifier Marker type Example
. Point For Marker and Line Style
o Circle
theta = 0:pi/6:2*pi;
x Cross/x-mark plot(theta*180/pi,sin(theta), '--o')
+ Plus sign line marker
* Asterisk/Star
s Square
d Diamond
Downward-pointing
v
triangle
Upward -pointing
^
triangle
< Left-pointing triangle
> Right-pointing triangle
p Pentagram
h Hexagram
Color Codes
Specifier Color Example For color
theta = 0:pi/6:2*pi;
r Red
plot(theta*180/pi,sin(theta), '-xr')
g Green
b Blue line marker color

c Cyan
m Magenta
y Yellow
k Black
w White
Final Exam-1
Draw two graphs one under the other showing the cosine and sine of a
vector on a single figure with grid in Matlab. Note that:
• Declare a vector called as “theta” that includes the angles 0 to 360 degrees at step
of 30 degrees.
• Declare two variables called as “y1” and “y2” that calculate the sin and cos of the
vector “theta”, respectively.
• Customize the tick values along the x-axis with respect to the step. Use function
“set” for the graph “y1”, Not using function “set” for graph “y2”.
• For the graph sine;
• The title is “The Graph of Sin(θ)”
• The labels must be represented as “Degrees (°)” and “Values of sin(θ)” for x-
axis and y-axis, respectively.
• Set the line style, marker symbol, and color to “Dashed Line”, “circle” and “blue”,
respectively.
• For the graph cos;
• The title is “The Graph of Cos(θ)”
• The labels must be represented as “Degrees (°)” and “Values of cos(θ)” for x-
axis and y-axis, respectively.
• Set the line style, marker symbol, and color to “Dashed-Dot Line”, “square”
and “magenta”, respectively.
Answer-1
theta = 0:30:360;

y1=sin(theta*pi/180);
y2=cos(theta*pi/180);

subplot(2,1,1)
plot(theta,y1, '--ob');
title('The Graph of Sin(\theta)');
xlabel('Degrees (\circ)');
ylabel('Values of sin(\theta)');
set(gca,'XTick',0:30:360);
grid on;

subplot(2,1,2)
plot(theta,y2, '-.sm');
title('The Graph of Cos(\theta)');
xlabel('Degrees (\circ)');
ylabel('Values of Cos(\theta)’);
xticks(0:30:360);
grid on;
Answer-1 For side by side

subplot(1,2,1) subplot(1,2,2)
plot(theta,y1, '--ob'); plot(theta,y2, '-.sm');
title('The Graph of Sin(\theta)'); title('The Graph of Cos(\theta)');
xlabel('Degrees (\circ)'); xlabel('Degrees (\circ)');
ylabel('Values of sin(\theta)'); ylabel('Values of Cos(\theta)');
set(gca,'XTick',0:30:360); xticks(0:30:360);
grid on; grid on;
Final Exam-2
Draw the given below graph in Matlab. Note that:
• Declare a vector “x” of angles in radians from 0 to 4π in the interval of 0.2 radians.
• Define a function called as “y1” that calculates the formula, sin(3 π x)/ex
• Define a function called as “y2” that calculates the formula, cos(3 π x)/ex
• Customize the tick values along the x-axis with respect to the step below for all
functions.
• You must use function “set” for the tick values.
• The values like : 0 0.5π π 1.5π 2π 2.5π 3π 3.5π 4π

• For “y1”, set the line style and color to “Solid Line” and “red”, respectively.
• For “y2”, set the line style and color to “Dashed line” and “blue”, respectively.
• Add a legend for both the functions “y1” and “y2”.
• For “y1”, 𝑒 −𝑥 sin 3𝜋𝑥
• For “y2”, 𝑒 −𝑥 cos 3𝜋𝑥
Answer-2
x=0:0.2:4*pi;

y1=sin(3*pi*x)./exp(x); y2=cos(3*pi*x)./exp(x);

plot(x,y1,'r',x,y2,'--b’); legend('e^{-x}sin(3\pix)','e^{-x}cos(3\pix)');

xticks=([0 0.5*pi pi 1.5*pi 2*pi 2.5*pi 3*pi 3.5*pi 4*pi]);

xticklabels={'0','0.5\pi','\pi','1.5\pi','2\pi','2.5\pi','3\pi','3.5\pi','4\pi'};

set(gca,'XTick',xticks,'XTicklabel',xticklabels );
Answer-2 NOT USING “SET” Function
x=0:0.2:4*pi;

y1=sin(3*pi*x)./exp(x); y2=cos(3*pi*x)./exp(x); plot(x,y1,'-r',x,y2,'--b’);

legend('e^{-x}sin(3\pix)','e^{-x}cos(3\pix’); grid on;

xticks([0 0.5*pi pi 1.5*pi 2*pi 2.5*pi 3*pi 3.5*pi 4*pi]);

xticklabels({'0','0.5\pi','\pi','1.5\pi','2\pi','2.5\pi','3\pi','3.5\pi','4\pi'});
Example For Final Exam
◼ Translate the following into MATLAB statements:

a) Add 1 to the value of i and store the result in i.


b) Cube i, add j to this, and store the result in i.
c) Set g equal to the larger of the two variables e and f.
d) If d is greater than zero, set x equal to minus b.
e) Divide the sum of a and b by the product of c and d, and store the
result in x. (a) i = i + 1
(b) i = iˆ3 + j
(c) if e > f
g = e
else
g = f
end
(d) if d > 0
x = -b
end
(e) x = (a + b)/(c * d) 16
Structure of a Function M-file
Keyword: function Function Name (same as file name .m)
Output Argument(s) Input Argument(s)

function y = AVERAGE(x)
% MEAN Average or mean value.
% For vectors, AVERAGE(x) returns the mean value.
Online Help
% For matrices, AVERAGE(x) is a row vector
% containing the mean value of each column.
[m,n] = size(x);
if m == 1
MATLAB
Code m = n;
end
y = sum(x)/m;
Example for the Function
function y=AVERAGE(x)
[m,n]=size(x);
if(m==1)
m=n;
end
y=sum(x)/m;
end

Save as “AVERAGE”
num=1:10;
avr=AVERAGE(num);
fprintf('The average of the numbers between 1 and 10= %.2f',avr);
Question-1
The following function named ”maxnum” should be written in a file
named maxnum.

Note That:
• The function takes four numbers as argument and returns the
maximum of the numbers.
• You must use only one “IF” statement.
• You can use “ELSE IF” statements and the logical operators in logical
expression.
Answer-1

function mx=maxnum(n1,n2,n3,n4) function mx=maxnum(n1,n2,n3,n4)


mx=n1;
if(n1>n2 && n1>n3 && n1>n4) if(n2>mx)
mx=n1; mx=n2;
elseif (n2>n3 && n2>n4) end
mx=n2; if (n3>mx)
elseif (n3>n4) mx=n3;
mx=n3; end
else if (n4>mx)
mx=n4; mx=n4;
end end
end end

function mx=maxnum(n1,n2,n3,n4)
mx=max([n1,n2,n3,n4]);
end
Question-2
Write a function named quadratic that would
calculate the roots of a quadratic equation.
Note That:
• The function would take three inputs; that is, the quadratic
co-efficient, the linear co-efficient and the constant term.
• It would return the roots.
• In the function, you must use the variables “x1”, “x2” and
“dc” for root 1 and 2, and the discriminant, respectively.

𝑎𝑥 2 + 𝑏𝑥 + 𝑐𝑥 = 0
Answer-2

function [x1,x2] = quadratic(a,b,c)

dc = sqrt(b^2 - 4*a*c);
x1 = (-b + dc) / (2*a);
x2 = (-b - dc) / (2*a);

end
Question-3
Write a program to calculate the factorial in MATLAB
Note That:
• Define a function called as “Fact” that calculates the factorial of the
given number.
• In the function “Fact”,
• You must NOT use any built-in functions in MATLAB.
• You must use only FOR loop
• In the main program;
• The number must be entered by the user.
• Invoke the function “Fact”.
• The output is like the following example:
• The factorial of “5” is 120.
Answer-3
num=input('Enter The Number=');
fprintf('The Factorial of "%d" is %d',num,Fact(num));
function prd=Fact(numx)
prd=1;
for i=1:numx
prd=prd*i;
end
end
Answer-3 Using built-in Function
num=input('Enter The Number=');
fprintf('The Factorial of "%d" is %d',num,Fact(num));

function prd=Fact(numx)
prd=factorial(numx);
end
Examples: What is the output?
alpha = 0.5; U(1) = 10;
for k=2:4
U(k) = (1-alpha)*U(k-1); ? 10.00 5.00 2.50 1.25
end
disp(U);

x = 2:4;k=1;
while k<4
s(k) = x(k)^2;
c(k) = x(k)^3; 4 27 256
f(k) = x(k)^4; ?
k=k+1;
end
A=[s;c;f];
disp(A([1 5 9]));
Examples: What is the output?
1 2 3 4
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(: , 5)=[]; 2 3 4 5
disp(a) 3 4 5 6
4 5 6 7

a = [ 10 20 30; 11 22 33; 111 222 333; 1 2 3];


a(2:3 , :)=[]; 10 20
a(:,end)=[]; 1 2
disp(a)

a = [ 1 2 3 ; 4 5 6; 7 8 9]; 4 5 6
new_mat = a([2,3,2,3],:);
disp(new_mat);
? 7 8 9
4 5 6
7 8 9
Question-4

Calculate the sum of elements 𝑎𝑖 = 2𝑖 − 1, i=1,2,3…


until the sum will exceed 20.

• Declare a variable called as “S” for sum.

• Not use any built-in function

• Use the WHILE loop.

• The output must be like:

• The Sum of The Elements is 21.41


ANSWER-4
S=0; % Initial assignment for sum to be able to check condition

i=1; % first value for i is 1

while S<20 %condition to check

S=S+(2*i-1)^(1/2); % recurrent formula for S

i=i+1; % next i

end

fprintf('The Sum of The Elements is %.2f',S);


What is the output
allNumbers = [1 5 1 20 4 6 9 40 7 9 5];
[m,n]=size(allNumbers);
count = 0;
for index = 1:1:n
if (allNumbers(index)>8 && allNumbers(index)<13)
count = count+1;
end
end
disp(count)
What is the output
allNumbers = [1 5 1; 20 4 6;9 40 7];
[m,n]=size(allNumbers);
count = 0;
for index = 1:1:n
if (allNumbers(index)>8 && allNumbers(index)<13)
count = count+1;
end
end
disp(count)
What is the output for MATLAB Codes
A=[1 2 3 4 5;6 7 8 9 10;4 4 4 4 4;3 2 1 0 -1];
1 2 3 4 5
6 7 8 9 10
4 4 4 4 4
3 2 1 0 -1
C=A([1,3],[1:3,5])
B=A(2:3,4:5) 9 10
4 4 1 2 3 5
4 4 4 4
3 2
2 3
D=[A(4,1:3)',C(1,2:4)']
1 5

0 0 0
2 0 5
E([2,5],[1,3])=A([1,3],[2,5]) 0 0 0
0 0 0
4 0 4
QUESTION?
INTRODUCTION TO
COMPUTER PROGRAMMING

C PROGRAMMING LANGUAGE
THE FİRST C PROGRAM
PRINT THE WORDS “HELLO, WORLD”
#include <stdio.h> include information about standard library
main() define a function called main that received no argument values
{ statements of main are enclosed in braces
printf("hello, world\n"); main calls library function printf to print this sequence of characters
} \n represents the newline character
DATA TYPES AND S İZES

There are only a few basic data types in C:


char a single byte, capable of holding one character in the local character set
an integer, typically reflecting the natural size of integers on the host
•int - integer
int
machine •char - character
float single-precision floating point
double double-precision floating point •float - float number
•double - long float
#include <stdio.h>
Example declarations:
#include <stdlib.h>
int a, b, c ; int main(int argc, char *argv[]) {
float r, p, q ; int t=8,i=10;
double x, y, z ; int res;
char m, n ; res=(2*i)+t;
printf("The Result=%d",res);
return 0;
}
EXAMPLE FOR FLOATING POINT
NUMBER
int main() Operator Meaning of Operator
{
int a = 9,b = 4, c; + addition or unary plus
- subtraction or unary minus
c = a+b;
printf("a+b = %d \n",c); a+b = 13 * multiplication
/ division
c = a-b;
printf("a-b = %d \n",c); a-b = 5 remainder after division( modulo
%
division)
c = a*b;
printf("a*b = %d \n",c); a*b = 36

c=a/b;
printf("a/b = %d \n",c); a/b = 2

c=a%b;
printf("Remainder when a divided by b = %d \n",c); Remainder when a divided by b = 1

return 0;
}
Meaning of Operator Meaning of Operator
Operator
Operator
== Equal to
&& Logial AND. True only if all operands are true
> Greater than
< Less than
!= Not equal to || Logical OR. True only if either one operand is true
Greater than or
>=
equal to
! Logical NOT. True only if the operand is 0
Less than or
<=
equal to

Operator Example Same as

= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
Format specifier Description Supported data types
%c Character char - unsigned char
%d Signed Integer Short - unsigned short – int – long
%f Floating point Float
%i Signed Integer Short - unsigned short – int - long
%s String char *

char charVal;
int intVal;
float floatVal;
double doubleVal;

printf("Enter a character: "); scanf("%c",&charVal);


printf("Enter an signed integer value: "); scanf("%d", &intVal);
printf("Enter a float value: "); scanf("%f", &floatVal);
printf("Enter a double value: "); scanf("%lf", &doubleVal);

printf("You entered character: '%c' \n", charVal);


printf("You entered signed int: %d \n", intVal);
printf("You entered float: %f \n", floatVal);
printf("You entered double: %lf \n", doubleVal);
ARITHMETIC OPERATORS
ORDER OF EVALUATION

x = 2 * 3 - (4 + 5) + 8 % 7;

X=?
x = 2 * 3 - 9 + 8 % 7;

x = 6 - 9 + 8 % 7;

x = 6 - 9 + 1;

x = -3 + 1;

x = -2;
If-else Statements

if (expr)
statement1 /*do this if expr is non-zero*/
else
statement2 /*do this if expr is zero*/

• The else clause is optional!

9
Concatenated If-else Statements

if (expr1)
statement1 /*do this if expr1 is non-zero*/

else if (expr2)
statement2 /*i.e., expr1 == 0, expr2 != 0*/

else if (expr3)
statement3 /expr1 and expr2 are zero, expr3 != 0*/
else if (expr4)
statement4 /expr1, expr2 , expr3 all zero, expr4 != 0*/
else
statement5 /*i.e., all expr are zero*/
10
EXAMPLE-1

Write a program in C to find whether a number is even


or odd.
Note That:
• The number must be entered by the user.
• You must use the mod operator.
• The output is like:
ANSWER-1
int main(int argc, char *argv[]) {
int num,res;
printf("Enter a number="); scanf("%d",&num);
res=num%2;
if(res==0)
{
printf("The Number %d is even",num);
}
else
{
printf("The Number %d is odd",num);
}
return 0;
}
EXAMPLE-2

Write a C Program to find greatest of three numbers


Note That:
• Three input integer numbers from the user
• Returns the greatest number as output.
• Use a simple if-elseif-else block.
• The output must be like:
ANSWER-2
int main(int argc, char *argv[]) {
int num1, num2,num3;
int max;
printf("Enter The First Number=");scanf("%d",&num1);
printf("Enter The Second Number=");scanf("%d",&num2);
printf("Enter The Third Number=");scanf("%d",&num3);
if(num1>num2 && num1>num3)
{
max=num1;
}
else if(num2>num3)
{
max=num2;
}
else
{
max=num3;
}
printf("The Largest Number Among %d %d %d is %d",num1,num2,num3,max);
return 0;
while loops

while (expression)
statement Often a compound statement

• Evaluate expression
• If true, execute statement and then repeat
• Repeat until expression becomes false

• statement may be executed zero or more


times!
15
for loop

• A counting loop
for (expr1; expr2; expr3)
statement
• Evaluate expr1 to initialize
• Evaluate expr2 to test
• If true, execute statement
• If not true, exit for loop
• Evaluate expr3 to prepare for next iteration
• Repeat expr2 to test
16
for loops and while loops

• The for loop


for (expr1; expr2; expr3)
statement
• is exactly equivalent to the following
expr1;
while (expr2) {
statement
expr3;
}

17
EXAMPLE-3

Write a C Program to find the Sum of First n Natural numbers.


Note That:
• Declare a variable called as “N” that is entered by the user.
• Declare a variable called as “sum” that calculate the sum of the numbers
from 1 to the number “N”.
• Firstly, you must use FOR loop for finding the sum.
• Secondly, you must use WHILE loop for finding the sum
• The output must be like:
ANSWER-3

int main(int argc, char *argv[]) {


int N;
int sum=0;
FOR-LOOP
int i;
printf("Enter The Number N =");
scanf("%d",&N);
for(i=1;i<=N;i++)
{
sum=sum+i;
}
printf("The Sum of The First %d Natural Numbers is %d",N, sum);
return 0;
}
ANSWER-3

int main(int argc, char *argv[]) {


int N;
int sum=0;
WHILE-LOOP
int i=1;
printf("Enter The Number N =");
scanf("%d",&N);
while(i<=N)
{
sum=sum+i;
i++;
}
printf("The Sum of The First %d Natural Numbers is %d",N, sum);
return 0;
}
EXAMPLE-4

Write a C Program as given below instructions:


• First: Find the Number of Integers Divisible by 5 in the range of [1,15].
• Second: Find the sum of all integers that are divisible by 5 in the given
range.
Note That:
• Declare a variable called as “count” that indicates the number of integers
divisible by 5 in the given range.
• Declare a variable called as “sum” that calculate the sum of all the integers
that are divisible by 5.
• You must use FOR loop.
• The output must be like:
ANSWER-4

int main(int argc, char *argv[]) {


int count=0;
int sum=0;
int i=1;
for(i=1;i<=15;i++)
{
if((i%5)==0){count++;sum=sum+i;}

}
printf("The Count is %d\n",count);
printf("The Sum is %d",sum);
return 0;
}
EXAMPLE-5

Write a C Program to Calculate the arithmetic mean of 5 numbers.


Note That:
• Declare five variables called as “n1, n2, n3, n4, n5” that indicates the given
numbers from the user.
• Declare a variable called as “sum” that calculates the sum of all the integer
numbers.
• Declare a variable called as “avr” which calculates the arithmetic mean of
the numbers.
ANSWER-5

int main(int argc, char *argv[]) {


int n1,n2,n3,n4,n5;
int sum=0;
double avr;
printf("Enter the five numbers=");
scanf("%d%d%d%d%d",&n1,&n2,&n3,&n4,&n5);
sum=(n1+n2+n3+n4+n5);
avr=sum/5.0;
printf("The Arithmetic mean of the numbers is %.2f",avr);
return 0;
}
C O N V E R T T H E T E M P E R AT U R E I N F A H R E N H E I T T O T H E D E G R E E C E L S I U S
celsius = (F - 32) * 5 / 9;

• Print Fahrenheit-Celsius table for fahr = 0, 10, 20, 30, . . .,100


• You must NOT use any array variable.
• You must use FOR loop.

int main(int argc, char *argv[]) {


double cel;
int i;
for(i=0;i<=100;i=i+10)
{
cel=(i-32)*5/9;
printf("%5d%7.2f\n",i,cel);
}
return 0;
}
C O N V E R T T H E T E M P E R AT U R E I N F A H R E N H E I T T O T H E D E G R E E C E L S I U S
celsius = (F - 32) * 5 / 9;

• Print Fahrenheit-Celsius table for fahr = 0, 10, 20, 30, . . .,100


• You must NOT use any array variable.
• You must use WHILE loop.

int main(int argc, char *argv[]) {


double cel;
int i=0;
while(i<=100)
{
cel=(i-32)*5/9;
printf("%5d%7.2f\n",i,cel);
i=i+10;
}
return 0;
}
EXAMPLE-6

Write a C Program to Calculate the sum of the input numbers from the user
until the user enters a zero or a negative number.
Note That:
• Declare a variable called as “sum” that calculates the sum of all the integer
numbers.
• You must use WHILE loop.
ANSWER-6

int main(int argc, char *argv[]) {


int num;
int sum=0;
scanf("%d",&num);
while(num>0)
{
sum=sum+num;
scanf("%d",&num);

}
printf("The Sum=%d",sum);
return 0;
}
QUESTION ?
INTRODUCTION TO EXAMPLES

C PROGRAMMING
©2016-2019 BY PEARSON EDUCATION.
EXAMPLE-1

• Write a program in C language that finds the quotient and


remainder of a division.
• Note that:
• Declare two variables called as “dividend” and “divisor” which are
entered by the user.
• The output of the program must be like:
ANSWER-1
int main(int argc, char *argv[]) {
int dividend, divisor;
int quotient, remainder;

printf("Enter dividend: ");scanf("%d",&dividend);


printf("Enter divisor: "); scanf("%d",&divisor);

quotient= dividend/divisor;
remainder= dividend%divisor;

printf("quotient: %d, remainder: %d\n",quotient,remainder);

return 0;
}
QUESTION FOR FINAL EXAM-1
• Write a C program that checks whether a number is palindrome or not.
• Note that:
• You must use four variables at most.
• You must use only while expression for loop.
• The number is entered by the user
• The output must be like as follows
ANSWER FOR FINAL EXAM -1
int main(int argc, char *argv[]) {
int num, relnum,palnum=0,rem;
printf("Enter The A Number=");
scanf("%d",&relnum);
num=relnum;
while(num!=0)
{
rem=num%10;
palnum=palnum*10+rem;
num=num/10;
}
if(palnum==relnum){printf("Number %d is a Palindrome Number",relnum);
}
else{printf("Number %d is NOT a Palindrome Number",relnum);}

return 0;
}
EXAMPLE-2

int main(int argc, char *argv[]) {


int num=369,sx=0;
while(num>0) { sx+=(num%3); num/=10; }
printf("The result=%d",sx);
return 0;
}
QUESTION FOR FINAL EXAM-2
• Write a program in C to convert a binary number to a decimal
number.

• Note That:
• Declare a variable called as “binnum” that is entered by the user like below:
• Enter a binary number: 1100

• Declare a variable called as “decnum” that indicates the conversion of the


binary number to the decimal number.
• You must use only WHILE loop.
• The output must be like:
ANSWER FOR FINAL EXAM-2

int main(int argc, char *argv[]) {


int binnum,rem,decnum=0,pw=2;
printf("Enter A Binary Number Like '1101': ");
scanf("%d",&binnum);
while(binnum!=0)
{
rem=binnum%10;
decnum=decnum+rem*(pw/2);
pw=pw*2;
binnum/=10;
}
printf("The Decimal Number:%d",decnum);
return 0;
}
QUESTION FOR FINAL EXAM-3
• Write a program in C to display the following output.
• Note That:
• You must use only two variables with type of integers, called as “r” and
“c”.
• You must use only WHILE expression for loop.
ANSWER FOR FINAL EXAM-3
int main(int argc, char *argv[]) {

int r=1,c=1;
while(r<=5)
{
while(c<=r)
{
printf("%d",c);
c++;
}
printf("\n");
c=1;
r++;
}
return 0;
}
INTRODUCTION TO EXAMPLES

C PROGRAMMING
©2016-2019 BY PEARSON EDUCATION.
int main(int argc, char *argv[]) {
int i,j,k,m;
for (i = 1; i <=3; i++)
{
for(m=3;m>i;m--) { printf(" "); }
for (j=1;j<=i;j++) { printf("%d",j); }
for(k=i-1;k>=1;k--) { printf("%d",k); }
printf("\n");
}
return 0;
}
Question for Final Exam-2
 Write a program in C to find the product of digits of a number.
 Note That:
 The number must be entered by the user.
 You must NOT use more than two variables.
 You must use the While loop for the product of the digits.
 The output must be like:
ANSWER FOR FINAL EXAM-2
int main(int argc, char *argv[]) {

int n, prd = 1;
printf("Enter a number=");
scanf("%d", &n);

while(n != 0)
{
prd*= (n%10);
n = n/10;
}
printf("The Product is %d", prd);
return 0;
}
QUESTION FOR FINAL EXAM-3
• Write the c program to check whether the number is armstrong or not.
• The number must be entered by the user and assigned to a variable named
as “num”.
• Declare a variable called as “arms” that indicates Armstrong number.
• Armstrong number is a number that is equal to the sum of cubes of its digits.
• 0, 1, 153, 370, 371 and 407 are the Armstrong numbers.
• The output must be like:
ANSWER FOR FINAL EXAM-3
int main(int argc, char *argv[]) {
int num,arms=0,rnum,rem;
printf("Enter A Number=");scanf("%d",&num);
rnum=num;
while(num!=0)
{
rem=num%10;
arms+=rem*rem*rem;
num/=10;
}
if(rnum==arms){printf("The Number '%d' is Armstrong number",rnum);}
else{printf("The Number '%d' is NOT Armstrong number",rnum);}
return 0;
}
int main(int argc, char *argv[]) {
int n, i = 1, sum = 0;
printf("Enter a number: ");
scanf("%d", &n);
while (i < n)
{
if (n % i == 0) { sum = sum + i; }
i++;
}
if (sum == n){ printf("%d is a perfect number", i);}
else{ printf("%d is not a perfect number", i);}
return 0;
}

You might also like