Post on 23-Jun-2015
description
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
Sebuah program dapat memberi instruksi sebuah komputer untuk melakukan operasi matematika.
Add 1 to
Counter
Store
A program will often instruct a computer to store intermediate results.
Place 1 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
Test condition p
false true
Entry
ExitTrue
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
false true
Entry
Exit
Test condition p
“true” statement a
“false” 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.)
The executable 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 Iteration control 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
If the 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
Ødon’t 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
No
Yes
Entry
Exit
Test condition p
Loop statement a
Limitations
q None, really q Some situations may be handled more elegantly with another type of loop, but that’s 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
If the 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
Loop statement a
No Yes
Entry
Test condition p
Exit
Programs are Solutionsto Problems
Programmers arrive at these solutions by using one or more of these devices:
Logic flowcharts Structure charts Pseudocode Structured Programming
Logic Flowcharts
These represent the flow of logic in a program and help programmers “see” program design.
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 commandsto 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 witha flowline in and the other with a flowline out.
Off-page connector. Even fairly small programs can have flowcharts that extend severalpages. 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.
Common Flowchart Symbols
Common Flowchart Symbols
Start
sum=0
Input price
sum=sum+price
Moreitems?
tax=sum x 0.0725total=sum+tax
Output sum, tax, and total
Stop
No
Yes
Flowchart for aCash Register Program
Structure Charts
Structure charts 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 programmer’s
native language and concentrates on the logic in a program—not 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
sum=0While More items do Input price sum=sum+priceEnd Whiletax=sum x 0.0725total=sum+taxOutput sum, tax, total
Pseudocode for aCash Register Program
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.
Analyze the problem
Design the solution algorithm
Design the user interface
Write the code
Test and debug the program
Complete the documentation
The Program Development Cycle
Levels of Programming Languages
Machine language Assembly Language High Level Languages Fourth Generation Languages (4GL)
Machine Languages different for each computer processor
0100001101 100000 001101 11000100101 10001 1000001110111001. . .
Assembly Languages different for each computer processor
main proc paymov ax, dsegmov ax, 0b00hadd ax, dxmov a1, b1mul b1, axmov b1, 04h
High-Level Languages
Higher Level LanguagesUse traditional programming logic where the
programming instructions tell the computer what to do and how to perform the required operations.
4GLsUse high-level English-like instructions to specify what
to do, not how to do it .
Interpreter vs Compiler
InterpreterTranslates instructions to machine code line-by-line.
CompilerTranslates 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 languagesSmalltalkC++Ada 95
Event-driven languagesVisual Basicmost Visual languages
Programmer’s 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
Programmer’s Lingo
Source Code (code) - program you write using a programming language
Interpreter - translates and executes source code statement by statement
Programmer’s Lingo
Interpreter Process
Programmer’s Lingo
Compiler Process