Algoritma Perancangan Saintifik-5 GFH
Algoritma Perancangan Saintifik-5 GFH
Algoritma &
Pemrograman
Saintifik
Gatot F. Hertono, Ph.D
Departemen Matematika
SCMA601401
Breaking News
90
80
70
60
50
40
30
20
10
0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
• Assignment:
To "assign" a variable means to symbolically associate a
specific piece of information with a name. Any operations
that are applied to this "name" (or variable) must hold true
for any possible values.
• Branching:
When an "Algorithm" makes a choice to do one of two (or
more things) this is called branching. The most common
programming "statement" used to branch is the "IF"
statement.
• Looping:
A Loop is used to repeat a specific block of code a over and
over. There are two main types of loops, for loops and while
loops.
Source: http://www.cs.utah.edu/~germain/PPS/Topics/
Variable Assignment
The '=' symbol is the assignment operator which SHOULD NEVER be used
for equality (which is the double equals sign).
As an example:
If the grade is greater than 90, then
give the student an A,
otherwise
if the grade is greater than 80,
give the student a B,... etc.
if ( something is true )
do this code;
Syntax: do all code before the end or else;
do not do anything in the else "block" of code
else
% if the something is false (NOTE: we don't have to test this)
do other code;
end
Source: http://www.cs.utah.edu/~germain/PPS/Topics/
Examples
grade = % some_number;
Y
if ( grade > 75 )
fprintf('congrats, your grade %d is passing\n', grade);
end N
if (money < 5) Y
do this;
elseif (money < 10)
N
do that;
Y
elseif (money < 1000)
do a lot of stuff;
else
N
do a default action when nothing above is true; Y
end
N
Looping
Loops - or repeating yourself
Loops allows us to repeat a single (or several) lines of code over and over again.
This allows us to "write once" and then "execute many times“.
% implied increment by 1
for var_index = start_value : end_value
% Do this code
end
for i=1:10
while ( y < 10 )
disp(i);
x = x + 1;
for j=1:i
end;
Infinite disp(j);
loops for k=1:j
while ( true ) disp(i*j*k)
disp('hello'); end
end; end
end
Exercises
Build a program to compute:
𝑥 𝑥 2 𝑥 3 𝑥 𝑛
ex = 1 + + + +⋯ , −∞ < 𝑥 < ∞
1! 2! 3! 𝑛!
and
Number Guess Games:
The computer will come up with a random
number between 1 and 1000. The player must
then continue to guess numbers until the player
guesses the correct number. For every guess, the
computer will either say "Too high" or "Too low",
and then ask for another input. At the end of the
game, the number is revealed along with the
number of guesses it took to get the correct
number.