Bu Naim Dasprog - Pertemuan1

78
DASAR PEMROGRAMAN . Anita Qoiriah

description

Materi Dasar Pemrograman C++

Transcript of Bu Naim Dasprog - Pertemuan1

Page 1: Bu Naim Dasprog - Pertemuan1

DASAR PEMROGRAMAN

.

Anita Qoiriah

Page 2: Bu Naim Dasprog - Pertemuan1

Program

kumpulan langkah-langkah instruksi yang

mengatur komputer untuk mengerjakan tugas

yang diinginkan dan menghasilkan hasil yang

diinginkan.

Page 3: Bu Naim Dasprog - Pertemuan1

Bahasa Pemrograman Bahasa pemrograman

adalah sekumpulan aturan untuk memberitahu komputer, operasi apa yang harus dilakukan.

Page 4: Bu Naim Dasprog - Pertemuan1

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

Page 5: Bu Naim Dasprog - Pertemuan1

Sequence Control Structures

Sequence control structures mengatur urutan instruksi program.

Satu instruksi mengikuti instruksi yang lain(dalam rangkaian) menentukan control dan urutan operasi.

Page 6: Bu Naim Dasprog - Pertemuan1

Calculate

Sebuah program dapat memberi instruksi sebuah komputer untuk melakukan operasi matematika.

Add 1 to

Counter

Page 7: Bu Naim Dasprog - Pertemuan1

Store

A program will often instruct a computer to store intermediate results.

Place 1 in

Counter

Page 8: Bu Naim Dasprog - Pertemuan1

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

Page 9: Bu Naim Dasprog - Pertemuan1

Program Control Flow (cont.)

Sequential execution only handles some situations Algorithms provide for conditional and iterative

situations So should programs

Page 10: Bu Naim Dasprog - Pertemuan1

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

Page 11: Bu Naim Dasprog - Pertemuan1

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

Page 12: Bu Naim Dasprog - Pertemuan1

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

Page 13: Bu Naim Dasprog - Pertemuan1

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

Page 14: Bu Naim Dasprog - Pertemuan1

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

Page 15: Bu Naim Dasprog - Pertemuan1

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.

Page 16: Bu Naim Dasprog - Pertemuan1

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

Page 17: Bu Naim Dasprog - Pertemuan1

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

Page 18: Bu Naim Dasprog - Pertemuan1

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

Page 19: Bu Naim Dasprog - Pertemuan1

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

Page 20: Bu Naim Dasprog - Pertemuan1

IF-THEN

Test condition p

false true

Entry

ExitTrue

statement a

Page 21: Bu Naim Dasprog - Pertemuan1

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”);

Page 22: Bu Naim Dasprog - Pertemuan1

Action

The executable statement is executed if the boolean expression has a value of true.

Otherwise the program skips to the next statement

Page 23: Bu Naim Dasprog - Pertemuan1

IF-THEN-ELSE

false true

Entry

Exit

Test condition p

“true” statement a

“false” statement a

Page 24: Bu Naim Dasprog - Pertemuan1

Syntax

Form 2 -- carry out one of two mutually exclusive actions

if (boolean expression)

executable statement 1;

else

executable statement 2;

Page 25: Bu Naim Dasprog - Pertemuan1

A simple IF-ELSE statement:

if (average >= 6)

printf( “You have passed this course.\n”);

else

printf( “You did not pass this course.\n”);

Page 26: Bu Naim Dasprog - Pertemuan1

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!

Page 27: Bu Naim Dasprog - Pertemuan1

Comments

The boolean expression can involve any combination of relational and logical operators.

The boolean expression can involve any type of variables or data.

Page 28: Bu Naim Dasprog - Pertemuan1

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

Page 29: Bu Naim Dasprog - Pertemuan1

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’;

Page 30: Bu Naim Dasprog - Pertemuan1

Iterate

A program loop is a form of iteration. A computer can be instructed to repeat instructions under certain conditions.

No

Page 31: Bu Naim Dasprog - Pertemuan1

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!

Page 32: Bu Naim Dasprog - Pertemuan1

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

Page 33: Bu Naim Dasprog - Pertemuan1

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

Page 34: Bu Naim Dasprog - Pertemuan1

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

Page 35: Bu Naim Dasprog - Pertemuan1

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

Page 36: Bu Naim Dasprog - Pertemuan1

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.

Page 37: Bu Naim Dasprog - Pertemuan1

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.

Page 38: Bu Naim Dasprog - Pertemuan1

Another way of classifying repetitions

q Counting loops q Sentinel (event)-controlled loops

Page 39: Bu Naim Dasprog - Pertemuan1

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

Page 40: Bu Naim Dasprog - Pertemuan1

Examples:

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

Page 41: Bu Naim Dasprog - Pertemuan1

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?

Page 42: Bu Naim Dasprog - Pertemuan1

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

Page 43: Bu Naim Dasprog - Pertemuan1

Examples:

read (letter); while (letter <> ‘ ‘) read (letter); repeat read (letter); until (letter = ‘ ‘);

Page 44: Bu Naim Dasprog - Pertemuan1

DO WHILE Loop

No

Yes

Entry

Exit

Test condition p

Loop statement a

Page 45: Bu Naim Dasprog - Pertemuan1

Limitations

q None, really q Some situations may be handled more elegantly with another type of loop, but that’s really not a limitation

Page 46: Bu Naim Dasprog - Pertemuan1

Generic Syntax

q while (boolean-valued expression) statement; q for(init-cond;limit;step) statement;

Page 47: Bu Naim Dasprog - Pertemuan1

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; …. }

Page 48: Bu Naim Dasprog - Pertemuan1

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.

Page 49: Bu Naim Dasprog - Pertemuan1

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 }.

Page 50: Bu Naim Dasprog - Pertemuan1

Example #1

q Count controlled using an int value q count = 0; while (count < 10) { count++; printf(“Counter %d\n”, count); }

Page 51: Bu Naim Dasprog - Pertemuan1

Example #2

q Sentinel controlled using a char value getc(NextCh); while (NextCh != ‘Q’) getc( NextCh);

Page 52: Bu Naim Dasprog - Pertemuan1

Example #3

q Sentinel controlled, counts internally count = 0; getc( NextCh); while (NextCh != ‘Q’) { count++; getc( NextCh); }

Page 53: Bu Naim Dasprog - Pertemuan1

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!

Page 54: Bu Naim Dasprog - Pertemuan1

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

Page 55: Bu Naim Dasprog - Pertemuan1

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.

Page 56: Bu Naim Dasprog - Pertemuan1

DO UNTIL Loop/REPEAT UNTIL

Loop statement a

No Yes

Entry

Test condition p

Exit

Page 57: Bu Naim Dasprog - Pertemuan1

Programs are Solutionsto Problems

Programmers arrive at these solutions by using one or more of these devices:

Logic flowcharts Structure charts Pseudocode Structured Programming

Page 58: Bu Naim Dasprog - Pertemuan1

Logic Flowcharts

These represent the flow of logic in a program and help programmers “see” program design.

Page 59: Bu Naim Dasprog - Pertemuan1

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

Page 60: Bu Naim Dasprog - Pertemuan1

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

Page 61: Bu Naim Dasprog - Pertemuan1

Structure Charts

Structure charts illustrate the structure of a program by showing independent hierarchical steps.

Major divisions are subdivided into smaller pieces of information.

Page 62: Bu Naim Dasprog - Pertemuan1

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.

Page 63: Bu Naim Dasprog - Pertemuan1

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

Page 64: Bu Naim Dasprog - Pertemuan1

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

Page 65: Bu Naim Dasprog - Pertemuan1

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.

Page 66: Bu Naim Dasprog - Pertemuan1

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

Page 67: Bu Naim Dasprog - Pertemuan1

Levels of Programming Languages

Machine language Assembly Language High Level Languages Fourth Generation Languages (4GL)

Page 68: Bu Naim Dasprog - Pertemuan1

Machine Languages different for each computer processor

0100001101 100000 001101 11000100101 10001 1000001110111001. . .

Page 69: Bu Naim Dasprog - Pertemuan1

Assembly Languages different for each computer processor

main proc paymov ax, dsegmov ax, 0b00hadd ax, dxmov a1, b1mul b1, axmov b1, 04h

Page 70: Bu Naim Dasprog - Pertemuan1

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 .

Page 71: Bu Naim Dasprog - Pertemuan1

Interpreter vs Compiler

InterpreterTranslates instructions to machine code line-by-line.

CompilerTranslates the entire program to machine code before

running it.

Page 72: Bu Naim Dasprog - Pertemuan1

Types of Programming Languages

Machine language Procedure-oriented languages Object-oriented languages Event-driven languages

Page 73: Bu Naim Dasprog - Pertemuan1

Procedure-Oriented Languages

FORTRAN COBOL Pascal C Ada

Page 74: Bu Naim Dasprog - Pertemuan1

OOED Languages

Object-oriented languagesSmalltalkC++Ada 95

Event-driven languagesVisual Basicmost Visual languages

Page 75: Bu Naim Dasprog - Pertemuan1

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

Page 76: Bu Naim Dasprog - Pertemuan1

Programmer’s Lingo

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

Interpreter - translates and executes source code statement by statement

Page 77: Bu Naim Dasprog - Pertemuan1

Programmer’s Lingo

Interpreter Process

Page 78: Bu Naim Dasprog - Pertemuan1

Programmer’s Lingo

Compiler Process