GENN004 Lect4 Algorithms1
GENN004 Lect4 Algorithms1
Algorithms Part I
Calculating sum and average, Getting
the maximum, Counting occurrences,
Finding matches
Overview
• Calculating sum & average of students’ grades
• Getting the maximum
• Counting number of zeroes
• Finding locations of zeroes
• Counting number of occurrences
• Finding the matched elements
One Dimension Arrays
X= [4 5 2 6 8]
X(1) 4
length(X): number of elements X(2) 5
X(3) 2
To access the array elements use
for-loop.
X(4) 6
X(5) 8
for i=1:length(X)
% use X(i)
end
Calculate sum & average of students’
grades (Program and Testing)
X=input(‘enter student grades:’); i X(i) sum
sum=0; 0
1 8 8
for i=1:length(X)
2 7 15
sum=sum+X(i); 3 9 24
end 4 5 29
avg = sum/length(X); 5 6 35
disp(sum);
disp(avg);
max=X(i); 3 -2 5
4 7 7
end 5 1 7
end
disp(max);
enter elements: [3 5 -2 7 1]
Getting the maximum and its index
(Program)
X=input(‘enter elements:’); i X(i) max maxi
max=0; 0
for i=1:length(X)
1 3 3 1
if X(i)>max
2 5 5 2
max=X(i);
maxi = i; 3 -2 5 2
end 4 7 7 4
end 5 1 7 4
disp(max);
disp(maxi);
enter elements: [3 5 -2 7 1]
Counting number of zeroes I
(Problem)
• Given a list of values, count how many zeroes
is found in the list.
• Example 1:
– Input: [6 0 12 0 12]
– Output: 2
• Example 2:
– Input: [6 5 12 14 10]
– Output: 0
Counting number of zeroes I
(Algorithm)
- Get N elements
- Set count=0
- Make a for loop from 1 to N
In every iteration, get one number x
if x equal zero then increment count
- Print count
Counting number of zeroes I
(Program)
X=input(‘enter elements:’);
i X(i) count
count=0;
0
for i=1:length(X)
1 6 0
if X(i)==0 2 0 1
count=count+1; 3 12 1
end 4 0 2
end 5 12 2
disp(count);