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

Session1 - 3 - Introduction To Algorithm I - Final

Uploaded by

Ahmad Mukhtar
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Session1 - 3 - Introduction To Algorithm I - Final

Uploaded by

Ahmad Mukhtar
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 101

Introduction to Algorithm I

Outline Materials
• Definition of an Algorithm
• Good Algorithm Practice
• Example of Algorithms
• Phase of Algorithm Development
• Definition of Problem
• Definition of Flow Chart
• Structured Theorem
• Algorithm vs Program
• Advantage of Algorithm
• Programming Language
Outline Materials
• Introduction to C
• Data Type
• Identifier
• Keyword
• Variable
• Definition of Pseudo Code
• Definition of Selection
What’s an Algorithm?

• Originating from al-Khwārizmī


(Abu Jafar Muhammad Ibnu Musa Al
Khawarizmi)
– the famous Islamic mathematician

• Step by step procedure for calculations

• Well specified method for solving a


computational problem
Definition of Algorithm
• Set of sequential instructions developed to describe important
processes in producing an output with specific required input is given

• Procedure for solving a problem in terms of the actions to be


executed, and the order in which these actions are to be
executed

• In the programming domain, algorithm define as method that


consist of structured steps in problem solving using computer.
Simple Algorithm Example
Rise and Shine Algorithm
(1)Get out of bed
(2)Take off pajamas
(3)Take a shower
(4)Get dressed
(5)Eat breakfast
(6)Carpool to work
Simple Algorithm Example
Breakfast Algorithms
Start
Take a plate
Put rice and dishes on the plate
Take spoon and fork
Repeat
Hold spoon and fork
Scoop up rice and dishes
Put rice and dishes on the mouth
Put spoon and fork
Chew rice and dishes
Do until rice and dishes finished
End
Simple Algorithm Example
Calculator Usage Algorithm
(for sum up price)
Start
Turn on calculator
Reset calculator
Repeat
Input price
Push button Plus (+)
Until all prices are inputted
Show total
Turn off calculator
End
Good Algorithm Practice

• Having the right logical flow to solve the problem

• Producing the correct output in a time efficient manner

• Written using unambiguous structured language

• Easy implementation into real programming language

• All steps and operations are clearly defined and ended


Efficient Algorithms
• Correct
• Fast
• Small space
• General
• Simple
• Clever
Logical Algorithm Example
There are 2 buckets, Bucket 1 and Bucket 2. Bucket 1 is
filled by sand, while Bucket 2 is filled by water. How
to swap the content of those two buckets with an
empty mediator bucket?
Write the algorithm, step by step!

Sand Water

Bucket 1 Mediator Bucket Bucket 2


Answer
• Solution
– Move sand from Bucket 1 to mediator bucket
– Move water from Bucket 2 to Bucket 1
– Move sand from mediator bucket to Bucket 2

Try to find another example!


Exercise: Hanoi Tower
Simulate a movement of 4 blocks below, from start pole to end pole with the same order position (from the biggest
to the smallest). Rule: smaller block can’t be put under bigger block. Write the algorithm step by step.

Blok 4

Block 3

Block 2

Block 1

START ANTARA END


Phase of Algorithm Development
START

PROBLEM
BOUNDARY

MODEL DESIGN

ALGORITHM DESIGN PROGRAMMING

PROGRAM TESTING AND


ANALYSIS
CORRECTION

15
DOCUMENTATION FINISH
Algorithm Representation
• Description
– Describe in sentences with normal language
• Diagram or symbol
– Flow Chart
• Pseudo code
– Outline of computer programs
Definition of Problem
• To define a problem, we need to read repeatedly the
problem until the problem can be fully understood.

• At initial analysis, problem is divided into 3 parts:


1. Input : required data to solve the problem
2. Process: set of necessary actions to create an output
3. Output : expected result from the process
Design Solution Algorithm
• After define a problem, the next step is how to design solution
algorithm.
• Defined existing process will be modified into an solution
algorithm by using pseudo code.
Solution Algorithm Testing
• Once solution algorithm is defined, testing need to be
conducted to acknowledge correctness of the solution.
• There are several steps to conduct an algorithm testing:
1. Choose simple valid data. (2-3 data)
2. Determine output for each chosen data.
3. Run testing, step by step according the algorithm (from start
command/statement until the end)
4. Repeat those steps using another chosen data.
Algorithm Representation
• Description
– Describe in sentences with normal language
• Diagram or symbol
– Flow Chart
• Pseudo code
– Outline of computer program
Flow Chart Definition

• shows logic of an algorithm

• emphasizes individual steps and their interconnections

• e.g. control flow from one action to the next


Flow Chart
Flow Chart Example
START
Step 1: Input M1,M2,M3,M4
Step 2: GRADE  (M1+M2+M3+M4)/4
Input
M1,M2,M3,M4
Step 3: if (GRADE <50) then
Print “FAIL”
else
GRADE(M1+M2+M3+M4)/4 Print “PASS”
endif
N IS Y
GRADE<5
0

PRINT PRINT
“PASS” “FAILED”

STOP
Flow Chart Example
Start

Input a,b,c

d = b^2 – 4ac

Y
d<0
T

x1=(-b+sqrt(d))/2a Print message


x2 =(-b-sqrt(d))/2a “Imaginary”

Print: x1, x2

Stop
Structured Theorem
• There are 3 main structure to write a computer program:
1. Sequence
2. Selection
3. Repetition
Sequence

• Sequence is series of consecutive commands/statements

• Commonly programming language has sequence of statements flowing from


top of the program to its end

• Can be used to perform 4 basic operations: compute, output, input, store


Sequence
• Example :
Print “Number of students:”
Set total to 49
Print “Add new student:”
Read newStudent
total = total + newStudent
Print “Number of students:”
Print total

• Description
Sequence of command is from the 1st line to the end of code. If
newStudent input is 2 then total that later on printed out is 51
Algorithm vs. Program
• Program is a set of computer statements, while methods and
systematic instructions is described as algorithm.
• Program is written using programming language.
• Program is implementation of algorithm into programming
language.

Program = Algorithm + Programming Language (Data Structure)


Advantage of Algorithm
• Algorithm construction is independent from any programming
language.
• Algorithm notation can be translated into any programming
language
• Despite of the programming language, the expected output is
same
Programming Language
• an artificial language designed to communicate instructions to
a machine, particularly a computer
• a notation for writing programs, which are specifications of a
computation or algorithm.

• Elements: syntax + semantics


Type of Programming Language
A programming paradigm provides the programmer’s view of
code execution.

• Procedural
• Structured
• Object-Oriented
Structure Programming Language
• Special type of procedural programming, that provides
additional tools to manage the problems.
• Structure programming
-> break program structure into small pieces of code
• Example:
– C
– Ada
– Pascal
Introduction
• Preparation to COMP6047 - Algoritma dan Pemrograman
course at 1st semester.

• Textbook: C : how to program


Paul J. Dietel,Harvey M. Deitel,. 2010.
Pearson Prentice Hall. New Jersey.
ISBN:978-0-13-705966-9
Why Using C
• Flexibility
Close to low level machine language yet easy to understand

• Portability
Used form micro computer to super computer

• A Well Known Programming Language


It is used in many forms of implementations such as O/S, scientific
application, business application, etc.

• Supported With a Large Number of Libraries


C Structure

• C language is a structural programming language


• It consists of functions
• There is no separation between function and
procedure (if you are from Pascal language
background)
• Each C program has one main function called main
• Program will be started from the first line of the main
function
• C language is case sensitive
• Every statement should be ended with a semi-colon (;)
C Structure

main() main()
1. { 3. {
statements; statements;
} return(0);
}

void main() int main()


2. { 4. {
statements; statements;
} return(0);
}
C Structure
• However, not all C compiler is familiar with all main
function format described previously
• No. 3 and 4 would be a general/standard main
function format
• return(0), suggesting a normal program exit
• A default integer (int) data type will be given for every
function as a default. No. 3 and 4 have the same
meaning
• Example:
 using Turbo C 2.0 (DOS) and Microsoft Visual C++ (windows)
compiler, (2), (3) and (4)  success, but (1) warning
 using Dev-C (windows) and gcc (linux) (1), (3), and (4) 
success, but (2) warning
C Structure

Using Turbo C 2.0, the


int main()
{ code will result in error.
printf (“Welcome to BINUS\n”); Error Message:
return 0;
}
Function should have a
function prototype

#include is a directive
#include<stdio.h>
int main() command to tell the
{ computer to search for
printf (“Welcome to BINUS\n”);
return(0);
printf function prototype
} at header file stdio.h as
well
C Structure
• Directive #include generally written at the beginning
of a program
• Coding Style (depends to the programmer)
#include<stdio.h>
int main()
{
printf (“Welcome to BINUS\n”);
return (0);
}

#include<stdio.h>
int main(){
printf (“Welcome to BINUS\n”);
return (0);
}
Comments in C
• Used for readability of the program
• Not accounted as a command/statement by the compiler
• Using /* and */
• Using // at the beginning of line for one line comment
• Example:
/*--------------------------
My First Program
--------------------------*/
#include<stdio.h>
void main(){
printf (“Hello, BINUSIAN\n”);

}
// This program will simply print out a message
Escape Sequences
• \a bell, alert, system beep
• \b back space
• \t horizontal tab
• \n new line, line feed
• \v vertical tab
• \r carriage return
• \’ single quote
• \” double quote
• \\ backslash
• \xdd hexadecimal notation
• \ddd octal notation
Data Type
• In C, there are 5 data types and 4 modifiers
Data types:
– Character  char
– Integer  int
– Floating point  float
– Double floating point  double
– Void  void
Modifiers:
- signed
- unsigned
- long
- short
Data Type

DATA TYPE SYNTAX MEMORY RANGE

character unsigned char 1 byte 0 to 255

char 1 byte -128 to 127

integer unsigned int 2 byte 0 to 65535

int 2 byte -32768 to 32767

short int 1 byte -128 to 127

unsigned long 4 byte 0 to 4294967295

long 4 byte -2147483648 to 2147483647

float float 4 byte 3.4E-38 to 3.4E+38

double 8 byte 1.7E-308 to 1.7E+308

long double 16 byte 3.4E-4932 to 1.1E+4932


Data Type
• The default is signed, so to write int equals to signed
int
• Example:
― int x; has similar meaning with signed int x;
― short int x; has similar meaning with signed
short int x;
• Range of data type on C language depends on its
compiler and operating system
• Example:
– integer in Turbo C 2.0 (DOS) has range between 2 bytes (-32768
to 32767)
– integer in Dev-C (Windows) has range between 4 bytes
(-2147483648 to 2147483647)
Data Type
• Why char data range between -128 to 127 ?
• 1 Byte = 8-bit
00000000 to 01111111 (MSB=>0 = Positive value)

MSB = Most Significant Bit (most left)


10000000 to 11111111 (MSB=>1 = Negative value)

-128 -128 32 8 4 2 1

64 16

Total = -128 Total = -1


Data Type
• Beside used in function identifier type as no return
value, keyword void also used as data type in variable.

• Void data type: is data type that can be transform into


any data type
Character
• C program is written using ASCII character subset:
- Capital letters A…Z
- Lower Case a…z
- Digit 0…9
- Special characters ‘!’, ‘&’, ‘+’, ‘\’, ‘_’, etc.

• ASCII
American Standards Committee for Information Interchange
http://www.asciitable.com/
Identifier
• The naming mechanism for various element in a program
such as: variable, function, constant, etc.
• Started with a letter or underscore_
• It is case sensitive
• Maximum length is vary for every compiler
Example: Turbo 2.0 (DOS), max 32 characters
• Never use reserved word/keyword
(such as: for, while, if, main)
• Example:
name, x1, _total, cubic()
wrong: 1time, int
Keywords
• Keywords/reserved words are words that have special meaning to the C
compiler.
• Example:
Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

• Keywords added in C99


_Bool _Complex _Imaginary inline restrict
Keywords
Some compilers will highlight keywords with distinct color,
as seen from the figure below

Keywords in Visual
C++ use blue color
Variable
• Identifier for storing data/information
• Each variable has its name, address (L-value), type,
size and data (R-value)
• Data or variable value can be modified at run time
• Declaration format:
<data type> <variable name>;
<data type> <variable name> = <initial value>;
• Example:
int a, b, c, total;
float salary, bonus;
int num_students = 20;
Variable
• Example:

char ch=65 address


Memory

ch 65 123456

Range of value:
name -128 – 127
value
Variable
• Variable Declaration:
– Variable can be declared at every statement block
– Block statement or compound statement is statement
exists between { and } sign
– Example:
int x;
int y;
int z;

or:
int x, y, z;

or:

int x; int y; int z;


Algorithm Representation
• Description
– Describe in sentences with normal language
• Diagram or symbol
– Flow Chart

• Pseudo code
– Outline of computer program
Definition of Pseudo Code

• An artificial and informal language that helps you develop


algorithms
• Pseudo-code is similar to everyday English, convenient,
and user friendly
• Specific Keywords are used to describe control structure
Example:
if, else, print, set, add, while, etc.
Pseudo-code
Basic Computer Operation:
1. Input
2. Output
3. Compute
4. Storing value to an identifier (Store)
5. Compare
6. Repetition (Loop)
1. Input

• Statements can be used when a computer receive


information or input
Read, Get, Input or Key-In

• Example:
Read bilangan
Get tax_code
Baca students_name
2. Output

• Statements can be used when a computer displaying


information or output:
Print, Write, Put, Output, or Display

• Example:
Print “Bina Nusantara University”
Write “Algorithm and Programming”
Output Total
3. Compute
• To do arithmetic calculation the following operators are used:
+ (add)
- (subtract)
* (multiply)
/ (divide)
() (scope)

• Statement Compute, Calculate or Add also can be used

• Example:
Add number to total
Total = Total + number
4. Storing Value to An Identifier (Store)

• There are three ways of storing value into a variable:


– Initializing value using statement Initialize or Set
– Storing value as calculation result using =
– To simply store a value into a variable using “Save” or
Store

• Example:
Set Counter to 0
Total = Price * Qty
Simple Pseudo Code Example
Class Average
Start
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Add one to the grade counter
Set the class average to the total divided by ten
Print the class average.
End
Example: Rate of exchange
• A program to convert rate of exchange from Rupiah to US
Dollar. (input: Rupiah)

• Formula:
US Dollar = Rupiah / 10000
Answer: Rate of exchange
• Problem Definition

Input Proses Output


Rupiah Read Rupiah US Dollar
Calculate US Dollar
Print US Dollar calculation
Answer: Rate of exchange
• Simple Algorithm Solution

Start
Read Rupiah
Dollar = Rupiah / 10000
Print Dollar
End
Answer: Rate of exchange

• Complete Solution Algorithm

Start
Print “Input amount of Rupiah = “
Read Rupiah
Dollar = Rupiah / 10000
Print “Amount of Dollar = ”
Print Dollar
End
Answer: Rate of exchange

• Testing:
– Data 1 : Rupiah = 10000
– Data 2 : Rupiah = 25000

Expected Output :

Data 1 Data 2
Dollar 1 2.5
Example: Number Calculation
• A program needed to read 2 numbers and do calculation
(addition, subtraction, multiplication, division). Final result
will be show to the screen.
Example: Number Calculation
• Problem Definition
Input Proses Output
Bil_1 Read num_1, Addition
Bil_2 num_2 Subtraction
Do addition Multiplication
Do subtraction Division
Do multiplication
Do division
Print addition
Print subtraction
Print multiplication
Print division
Example: Number Calculation
• Solution Algorithm
BEGIN
Read num_1, num_2
addition = num_1 + num_2
subtraction = num_1 - num_2
multiplication = num_1 * num_2
division = num_1 / num_2
print addition, subtraction, multiplication, division
END
• Testing:
– Data 1 : Num_1 = 10 and Num_2 = 5
– Data 2 : Num_1 = 20 and Num_2 = 10

Expected output:

Data 1 Data 2
Addition 15 30
Subtraction 5 10
Multiplication 50 200
Division 2 2
Pseudo Code Example 1
Create an algorithm pseudo code to calculate area
of rectangle with following formula:
area = length* width

Length = 5

Width = 3
Answer of Example1
• Pseudo code

Start
Print “Calculate Area of Rectangle”
Length = 5
Width = 3
Print “Area of Rectangle = ”
Area = Length * Width
Print Area
End
Pseudo Code Example 2
• Create an algorithm pseudo code to calculate an area of
rectangle with the same formula of previous example, with
new condition where the length and width is given by user
(input).
Answer of Example 2
• Pseudocode

Start
Print “Input & Calculate Area of Rectangle”
Print “Input Length = ”
Input Length
Print “Input Width = ”
Input Width
Area = Length * Width
Print “Area of Rectangle = ”
Print Area
End
Exercise
1. Create a pseudo code to convert inputted seconds into
minutes and hours
Formula: Seconds = Hours*3600 + Minutes*60

2. Create an pseudo code to determine if an inputted number is


an odd or even number
(Hint : Even number is completed divided by 2)
Exercise
• Create a program to do sum up and print assets of a
company, based on obligation and equity data of the
company. Formula:

assets = obligation + equity


Exercise
• Create a program to calculate item price, based on cost, tax
and discount.
Price = Cost – Discount + Tax
5. Compare
• One of the main operation in computing is comparing
values and choosing options based on its result

• Keyword used: IF, THEN and ELSE

• Compare same with selection in structure theorem


Selection Definition

• Selection control structure is structure that allow us to choose from


several options of statement/command

• The first statement will be executed if the condition is satisfied, if


not then the else statement will be executed (if the other exist)
Selection
• Example :
IF Day=1 THEN
Print “Monday”
ELSE
Print “Obviously not Monday”

• Description
The word “Monday” will be printed out if Day’s value
equal to 1, else it will print out the sentence
“Obviously not Monday”.
Selection
• Example :
IF Menu=‘1’ THEN
Discount = 0.1 * price
ELSE
Discount = 0.2 * price
ENDIF

• Description
The word Discount value will multiply by 10% if menu
equal to , else will multiply by 20%.
Selection
• Type of selection:
1. Simple IF
2. Simple IF – ELSE
3. Switch Case
Simple IF selection
• Selection with only one IF (one condition)
• Statement will be executed with only one TRUE condition
• Example:
IF Balance > 300 THEN
Interest = Balance * 0.1
ENDIF
Simple IF selection
• IF Construction

false true

condition

statements
Selection: IF in C Program
Syntax :
if (boolean expression) statement;
or
if (boolean expression) {
statement1;
statement2; Block of
statements
……
}

If boolean expression resulting in True, then a statement


or some statements will be executed.
T0016 - Algorithm and Programming 85
Simple IF ELSE selection
• Selection to choose between two alternative conditions, TRUE
or FALSE.

• Keyword : “IF”, “THEN”, “ELSE”, and“ENDIF”


Simple IF ELSE selection
• IF – ELSE Construction

false true

condition

statements 2 statements 1
Selection: IF-ELSE in C Program
Syntax :
if (boolean expression) statement1;
else statement2;
or If boolean
if (boolean expression){ expression
resulting in TRUE,
statement1; then statement1 or
statement2; Block statement1 block statement1
…… will be executed, if
} FALSE then
else { statement2 or
statement3; block statement2
be executed.
statement4; Block statement2

}
T0016 - Algorithm and Programming
Simple IF ELSE selection
• Example
IF balance < 300 THEN
interest = 0.05 false true
ELSE Saldo < $300
interest = 0.1
ENDIF
Bunga = 0.1 Bunga = 0.05
Combined IF selection
• Combined Selection is defined for checking more than one
conditions as a statement.

• Condition can be combined with AND or OR.


AND Logic

TRUE TRUE TRUE FALSE

AND AND

TRUE FALSE
OR Logic

TRUE TRUE TRUE FALSE

OR OR

TRUE TRUE
Combined Selection

• Truth Table

A B NOT A A AND B A OR B
True True False True True
True False False False True
False True True False True
False False True False False
Combined Selection
• Example:
IF balance> 300 AND code= 1 THEN
interest= balance* 0.1
ELSE
interest= balance* 0.05
ENDIF

• Statement “interest= balance* 0.1”, will be executed


only when both conditions are TRUE
Example

Create an algorithm to read 2 numbers, and find bigger


number between those 2 inputted numbers .

Input Process Output


Num_1 Read Num_1 and Num_2 Bigger Number
Num_2 Compare Num_1 and Num_2

Determine which is bigger

Print bigger number


Answer
• Solution Algorithm
Start
Read Num_1
Read Num_2
IF Num1 > Num2 THEN
Max = Num_1
ELSE
Max= Num_2
END IF
PRINT “The bigger number is =”, Max
End
Try to test with
•Num_1 = 5, Num_2 = 6
•Num_1 = 45, Num_2 = 30
Selection: SWITCH-CASE
• Switch-Case Operation
This statement is used in exchange of IF-ELSE, when if-else nested
number of level is enormous and difficult to read

• Syntax:
switch (expression) {
case constant1 : statements1; break;
.
.
case constant2 : statements2; break;
default : statements;
}
T0016 - Algorithm and Programming
Selection: SWITCH-CASE
 Flow Chart of SWITCH-CASE Statement

true
case a case a action(s) break

false

true
case b case b action(s) break
false

.
.
.

true
case z case z action(s) break
false

default action(s)

T0016 - Algorithm and Programming


Exercise 1
• Create a program to calculate and print profit of a
company based on following formula:

Profit = Selling Price - Basic Price

• Mark the status:


– “Profit” if profit> 0,
– “Equal” if profit=0 and
– “Loss” if profit<0
Exercise 2
• Create a program to show student’s grade based on inputted number.
• Grade rules :
‘A’ : 85 -100
‘B’ : 75 – 84
‘C’ : 65 – 74
‘D’ : 50 – 64
‘E’ : 0 – 49
• Expected output:
Input number = 77
Your Grade is B
Input number = 90
Your Grade is A
-End-

You might also like