Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 78

DASAR

PEMROGRAMAN

Anita Qoiriah


.

Program
kumpulan langkah-langkah instruksi yang
mengatur komputer untuk mengerjakan tugas
yang diinginkan dan menghasilkan hasil yang
diinginkan.
Bahasa Pemrograman
Bahasa pemrograman
adalah sekumpulan
aturan untuk
memberitahu
komputer, operasi apa
yang harus dilakukan.
What Can a Program Do?
Sebuah hanya program dapat memberi instruksi
pada komputer untuk:
Membaca Input
Sequence
Menghitung
Menyimpan data
Membandingkan dan branch
Iterate or Loop
Menulis Output
Sequence Control Structures
Sequence control structures mengatur urutan
instruksi program.
Satu instruksi mengikuti instruksi yang lain(dalam
rangkaian) menentukan control dan urutan operasi.
Calculate

Sebuahprogram dapat
memberi instruksi
Add 1 to
sebuah komputer untuk Counter
melakukan operasi
matematika.
Store
A program will often
instruct a computer to Place 1
store intermediate results. in
Counter
Program Control Flow

Up to now, program statements have been executed


sequentially
In listed order
Beginning of program to end
No provision for
skipping statements
repeating the same statement
Program Control Flow (cont.)

Sequential execution only handles some situations


Algorithms provide for conditional and iterative
situations
So should programs
Control Statements
Decision (conditional) statements
single execution
makes a one-time choice between actions

Repetition statements
executed multiple times
continues to make a choice to carry out an action
until some criterion is met
Decisions

Modeled in everyday life


We choose to:

Do something rather than nothing


Do one action over another
Choice is based on looking at current situation,
determining appropriate course of action
Decision Statements

Allow program choose to execute a statement or


not
Based on a boolean-valued expression using
relational and/or logical operators
All comparisons are two-way comparisons
If more than two possibilities exist, must perform
multiple comparisons, each between a pair of
situations
Repetitions

Also modeled in everyday life


We choose to:

Do something a predetermined number of times


Do something until some event occurs
Choice is based on looking at current situation,
determining whether or not to continue action
Repetition Statements

Allow program to choose how many times to


execute a statement
Based on a boolean-valued expression using
relational and/or logical operators
Compound statements

Group several executable statements into a block


{ and } are used as punctuation
Any statements between a { and its matching }will
always be executed together.
Compound Statements and Scope

Compound statements are used anywhere you


want several statements to be glued together
inside a decision or repetition statement.
Compound statements usually define a scope
IF

Make decisions based on two-way comparisons


Decision can be a choice between

carrying out an action or ignoring it


carrying out one of two mutually exclusive
actions
Capable of handling all decisions, regardless of
what they are based on
Compare and Branch

A program can instruct a computer to compare two


items and do something based on a match or
mismatch which, in turn, redirect the sequence of
programming instructions.
There are two forms:
IF-THEN
IF-THEN-ELSE
Compare and Branch
A program can instruct a computer to compare
two items and do something based on a match
or mismatch which, in turn, redirect the
sequence of programming instructions. There
are two forms:
IF-THEN
IF-THEN-ELSE
IF-THEN
Entry

Test false true


condition p

Exit
True
statement a
Syntax
Form 1 -- carry out an action or ignore it

if (boolean expression)
executable statement;

if (average < 0)
printf( You cannot have an average less than zero.\n);
Action

The executable statement is executed if the


boolean expression has a value of true.
Otherwise the program skips to the next statement
IF-THEN-ELSE
Entry

Test
condition p false true

false true
statement a Exit statement a
Syntax

Form 2 -- carry out one of two mutually exclusive


actions

if (boolean expression)
executable statement 1;
else
executable statement 2;
A simple IF-ELSE statement:

if (average >= 6)
printf( You have passed this course.\n);
else
printf( You did not pass this course.\n);
Action

Executable statement 1 is executed if the boolean


expression has a value of true; executable
statement 2 is skipped.
Otherwise, the boolean expression has a value of
false, so executable statement 1 is skipped;
executable statement 2 is carried out.
There is no way that both executable statements
can be executed!
Comments

The boolean expression can involve any


combination of relational and logical operators.
The boolean expression can involve any type of
variables or data.
Comments (cont.)

Theexecutable statement can be any legal


executable statement.
Yes, this means other decision statements
This is how we make decisions that have more
than two options
A nested IF-ELSE statement:
Allows for a decision with more than two options
if (average >= 10)
grade = 33;
else if (average >= 8)
grade = 27;
else if (average >= 7)
grade = 24;
else if (average >= 6)
grade = 20;
else
grade = 18;
Iterate
A program loop is a
form of iteration. A
computer can be
instructed to repeat
instructions under
certain conditions.

No
Loops

Adding decision statements to sequential


statements helps
However, very often we have to do something
repeatedly
Either we copy the code as many times as we need
to repeat the action,
Or we come up with another type of statement!
Repetitions

Also modeled in everyday life


We choose to:

Do something a predetermined number of times


Do something until some event occurs
Choice is based on looking at current situation,
determining whether or not to continue action
Repetition Statements

Allow program to make choice as to how many


times to execute a statement
Based (explicitly or implicitly) on value of a
Boolean expression using relational and/or logical
operators
Types of Repetition Statements

q General purpose
handles all repetition situations
WHILE-DO statement
q Special-purpose
handles only some repetition situations, based
on characteristics of repetition
FOR-DO and REPEAT-UNTIL statements
Iteration Control Structures
Iterationcontrol structures are looping
mechanisms.
Loops repeat an activity until stopped. The
location of the stopping mechanism
determines how the loop will work:
Leading decisions
Trailing decisions
Leading Decisions
Ifthe stop is at the beginning of the iteration, then
the control is called a leading decision.
The command DO WHILE performs the iteration
and places the stop at the beginning.
Trailing Decisions

q If the stop is at the end of the iteration, the


control
mechanism is called a trailing decision.
q The command REPEAT UNTIL or DO
WHILE
perform the iteration and puts the stop at the end
of the loop.
Another way of classifying repetitions

q Counting loops
q Sentinel (event)-controlled loops
Counting loops

know ahead of time how many repetitions


so you just count them
all looping statements can be set up to count
repetitions
FOR-DO statements are specific for counting
Examples:

count = 0;
while (count <= 10) {
count = count + 1;
printf (Counter: %d\n, count);
}
Comment

q As written, these three statements do exactly


the
same thing.
q That will not always be the case!
q Otherwise, why would we have three different
looping statements?
Sentinel (event)-controlled loops
dont know ahead of time how many repetitions,
so you wait for some event to occur
read in a specific value or values
compute a specific value or values
both WHILE-DO and REPEAT-UNTIL loops can be
controlled by events
FOR-DO statements cannot be controlled by events
Examples:

read (letter);
while (letter <> )
read (letter);
repeat
read (letter);
until (letter = );
DO WHILE Loop

Entry

Exit
Test No
condition p
Yes
Loop
statement a
Limitations

q None, really
q Some situations may be handled more
elegantly
with another type of loop, but thats really not a
limitation
Generic Syntax

q while (boolean-valued expression)


statement;
q for(init-cond;limit;step)
statement;
Generic Syntax (cont.)
q if the body of the loop is actually more than one
statement, we create a block with those
statements:
while (boolean-valued expression) {
statement1;
statement2;
.
}
Action

q The computer determines whether the


boolean-valued
expression is true.
q If so, it executes the statements in the body of
the loop.
q Otherwise, it skips over the remainder of the
loop and goes
on to the next statement after the loop.
Executable statements

q Any executable statement is allowed.


q If two or more executable statements are
needed,
we form a compound statement (block) with { and
}.
Example #1

q Count controlled using an int value


q count = 0;
while (count < 10) {
count++;
printf(Counter %d\n, count);
}
Example #2

q Sentinel controlled using a char value


getc(NextCh);
while (NextCh != Q)
getc( NextCh);
Example #3

q Sentinel controlled, counts internally


count = 0;
getc( NextCh);
while (NextCh != Q) {
count++;
getc( NextCh);
}
Watch Out For This One!

q while (x >= 0);


x -= 1;
q Note the semicolon after the right parenthesis
q This gives you a loop that does nothing, over
and
over without end.
q You never get to the assignment statement!
Cautions with WHILE loops
q Avoiding infinitely-executing loops:
The boolean-valued expression MUST use at
least one variable.
That variable MUST change value at some
point within the loop.
q WHILE loops may not execute at all
if the boolean-valued expression is false to
begin with, nothing happens
Trailing Decisions
Ifthe stop is at the end of the iteration, the control
mechanism is called a trailing decision.
The command DO UNTIL performs the iteration
and puts the stop at the end of the loop.
DO UNTIL Loop/REPEAT UNTIL

Entry

Loop
statement a
Exit
Test No Yes
condition p
Programs are Solutions
to Problems
Programmers arrive at these solutions by using one
or more of these devices:
Logic flowcharts
Structure charts
Pseudocode
Structured Programming
Logic Flowcharts
Theserepresent the
flow of logic in a
program and help
programmers see
program design.
Common Flowchart Symbols
Common Flowchart Symbols

Terminator. Shows the starting and ending points of the program. A terminator has
flowlines in only one direction, either in (a stop node) or out (a start node).

Data Input or Output. Allows the user to inputdata and results to be displayed.

Processing. Indicates an operation performed by the computer, such as a variable


assignment or mathematical operation.

Decision. The diamond indicates a decision structure. A diamond always has two
flowlines out. One flowlineout is labeled the yes branch and the other is labeled the
no branch.

Predefined Process. One statement denotes a group of previously defined statements.


For instance, Calculate m! indicates that the program executes the necessary commands
to compute m factorial.

Connector. Connectors avoid crossing flowlines, making the flowchart easier to read.
Connectors indicate where flowlines are connected. Connectors come in pairs, one with
a flowline in and the other with a flowline out.

Off-page connector. Even fairly small programs can have flowcharts that extend several
pages. The off-page connector indicates the continuation of the flowchart on another
page. Just like connectors, off-page connectors come in pairs.

Flowline. Flowlines connect the flowchart symbols and show the sequence of operations
during the program execution.
Flowchart for a
Cash Register Program
Start

sum=0

Input price

sum=sum+price

Yes More
items?

No
tax=sum x 0.0725
total=sum+tax

Output sum, tax,


and total

Stop
Structure Charts
Structurecharts illustrate the structure of a
program by showing independent hierarchical
steps.
Major divisions are subdivided into smaller pieces
of information.
Psuedocode
This device is not visual but is considered a
first draft of the actual program.
Pseudocode is written in the programmers
native language and concentrates on the logic
in a programnot the syntax of a
programming language.
Example Loop Pseudo-code

q for count := 1 to 10 do
write (count);
q count := 0;
repeat
count := count + 1;
write (count);
until count > 10
Pseudocode for a
Cash Register Program
sum=0
While More items do
Input price
sum=sum+price
End While
tax=sum x 0.0725
total=sum+tax
Output sum, tax, total
Structured Programming
Structured program languages lend
themselves to flowcharts, structure charts,
and pseudocode.
Structured programming languages work
best where the instructions have been
broken up into small, manageable parts.
The Program Development Cycle
Analyze the problem

Design the solution algorithm

Design the user interface

Write the code

Test and debug the program

Complete the documentation


Levels of Programming Languages

Machine language
Assembly Language
High Level Languages
Fourth Generation Languages (4GL)
Machine Languages
different for each computer processor
0100
001101 100000 001101 110001
00101 10001 10000
01110
111001
. . .
Assembly Languages
different for each computer processor
main proc pay
mov ax, dseg
mov ax, 0b00h
add ax, dx
mov a1, b1
mul b1, ax
mov b1, 04h
High-Level Languages
Higher Level Languages
Use traditional programming logic where the
programming instructions tell the computer what to do
and how to perform the required operations.
4GLs
Use high-level English-like instructions to specify what
to do, not how to do it .
Interpreter vs Compiler
Interpreter
Translates instructions to machine code line-by-line.
Compiler
Translates the entire program to machine code before
running it.
Types of Programming Languages
Machine language
Procedure-oriented languages
Object-oriented languages
Event-driven languages
Procedure-Oriented Languages
FORTRAN
COBOL
Pascal
C
Ada
OOED Languages

Object-oriented languages
Smalltalk
C++
Ada 95
Event-driven languages
VisualBasic
most Visual languages
Programmers Lingo
Program - detailed set of instructions for a computer

Programming Language - tool used to create a


program; defined by semantics and syntax

Semantics - the meaning of words in a language

Syntax - rules for combining symbols of a language


Programmers Lingo
Source Code (code) - program you write using a
programming language

Interpreter - translates and executes source code statement


by statement
Programmers Lingo

Interpreter Process
Programmers Lingo

Compiler Process

You might also like