You are on page 1of 60

IKI 10200

DasarDasar-Dasar Pemrograman Semester 1 - 2011/2012


1.1

Chapter 1 Introduction to Computers and Programming

1.2

What is a computer?
A computer is a machine that stores data (numbers, words, pictures), i t d i t ) interacts with d i t ith devices (th monitor (the it screen, the sound system, the printer), and executes programs. programs A computer program is a sequence of instructions and p decisions that the computer carries out to achieve a task. Programs describe specific actions. A computer executes very simple instructions. A computer executes instructions very rapidly. A computer is a general purpose machine.

1.3

What is a computer?
A computer must be programmed to perform tasks. Different tasks require different programs. Diff tt k i diff t A computer program consists of a finite sequence of basic operations operations. A typical operation may be one of the following:
put a red dot onto a certain screen position send the letter B to the printer g get a number from a certain location in memory y add up two numbers if this value is negative, stop the program repeat this instruction ten times

1.4

Hardware and Software


Hardware
the physical, tangible parts of a computer keyboard, monitor, disks, wires, chips, etc.

Software
programs and data a program is a sequence of instructions

A computer requires both hardware and software Each is essentially useless without the other

1.5

CPU and Main Memory


Chip that executes program commands e.g. e g Intel Core i7

Central Processing g Unit

Primary storage area for programs and data that are in active use Synonymous with RAM

Main Memory

1.6

Secondary Memory Devices


Secondary memory devices provide long-term storage Information is moved between main memory d d and secondary memory as needed

Central Processing g Unit

Hard disks Floppy disks Flash disks Writable CDs Tapes

Main Memory

Hard Disk

Flash Disk
1.7

Input / Output Devices


Monitor Keyboard I/O devices facilitate user interaction

Central Processing g Unit

Monitor screen Keyboard K b d Mouse Joystick Bar code scanner Touch screen

Main Memory

Hard Disk

Flash Disk
1.8

Anatomy of a computer
At the heart of the computer lies the central processing unit (CPU) it (CPU). The CPU locates and executes the program instructions; it carries out arithmetic operations such as addition addition, subtraction, multiplication, and division; it fetches data from external memory or devices or stores data back.

1.9

Anatomy of a computer
CPU continuously follows the fetch-decode-execute

cycle: l

Retrieve an instruction from main memory

fetch f t h execute
Carry out the instruction

decode
Determine what the instruction is
1.10

Anatomy of a computer
The CPU contains:
Performs calculations and makes decisions Coordinates processing steps Small storage areas

Arithmetic / Logic Unit

Control Unit

Registers

1.11

Anatomy of a computer
The speed of a CPU is controlled by the system clock The system clock generates an electronic pulse at regular intervals g The pulses coordinate the activities of the CPU The speed is measured in megahertz (MHz) or gigahertz (GHz)

1.12

Anatomy of a computer
The computer keeps data and programs in storage. There are two kinds of storage:
primary storage, also called random-access memory (RAM) or simply memory memory. secondary storage, usually a hard disk.

Primary storage loses all its data when the power is turned off. Secondary storage persists without electricity. Most computers have removable storage devices: floppy p g ppy disks, tapes, compact discs (CDs), flashdisks.

1.13

Anatomy of a computer
To interact with a human user, a computer requires peripheral d i i h l devices.
input devices: keyboard, mouse. output devices: display screen printer screen, printer.

The CPU, the RAM and the electronics controlling the CPU RAM, hard disk and other devices are interconnected through a set of electrical lines called a bus.

1.14

Computer System
Five logical units of a computer system
Input unit: Mouse, keyboard Output unit: Printer, monitor, audio speakers Primary Storage unit (Memory unit): RAM Central processing unit (CPU)
supervises operation of other devices contains Arithmetic and Logic Unit (ALU) ALU performs calculations

Secondary storage unit


Hard-disk drives, floppy-disk drives, CD drives

1.15

Central Processing Unit

1.16

RAM Chips

1.17

A Hard Disk

1.18

What is programming?
A computer program tells a computer, in very detail, the sequence of steps that are needed t f lfill a t k f t th t d d to fulfill task. The act of designing and implementing these programs is called computer programming programming. Programmers develop computer programs to make computers perform new tasks. tasks A professional computer scientist or software engineer does a great deal of programming programming. The activity of programming is an important part of co pu e science. computer sc e ce

1.19

Java
A programming language specifies the words and symbols th t we can use t write a program b l that to it p g g g g p y A programming language employs a set of rules that dictate how the words and symbols can be put together to form valid program statements The Java programming language was created by James Gos g Sun c osyste s, c Gosling at Su Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since It is an object-oriented language
1.20

Java Program Structure


In the Java programming language:
A program is made up of one or more classes A class contains one or more methods A method contains program statements

These terms will be explored in detail throughout the course A Java application always contains a method called main Example:

1.21

//******************************************************************** // Programku.java // // Demonstrates the basic structure of a Java application. //******************************************************************** public class Programku { //----------------------------------------------------------------// Prints messages. //----------------------------------------------------------------public static void main (String[] args) { System.out.println ("Selamat Belajar Java."); System.out.println ("Whatever you are, be a good one. [Lincoln]"); } }

1.22

Compiling and Running


Type program with a text editor (e.g. edit, notepad, wordpad) d d) Save into a file with name, for example, Programku.java Programku java Open command shell C Compile i t b t codes il into byte d javac Programku.java Execute byte codes java Programku
output: Selamat Belajar Java. Whatever you are, be a good one. [Lincoln]
1.23

Java Program Structure


// { class header co e ts about t e c ass comments the class

public class Programku

class body

Comments can be placed almost anywhere }

1.24

Java Program Structure


// { // comments about the method co e ts about t e c ass comments the class

public class Programku

public static void main (String[] args) { method b d th d body } } method header

1.25

Comments
Comments in a program are called inline documentation They should be included to explain the purpose of the program and describe processing steps They do not affect how a program works Java comments can take three forms:
// this comment runs to the end of the line /* this comment runs to the terminating symbol, symbol even across line breaks */ /
1.26

*/

/ /** this is a javadoc comment j

Identifiers
Identifiers are the words a programmer uses in a program An identifier can be made up of letters, digits, the underscore character ( _ ) and the dollar sign ), Identifiers cannot begin with a digit Java is case sensitive - Total, total, and TOTAL are different identifiers By convention, Java programmers use different case styles for different types of identifiers, such as
title case for class names - Programku upper case for constants - MAXIMUM
1.27

Identifiers
Sometimes we choose identifiers ourselves when writing a program ( (such as Programku) h k ) Sometimes we are using another programmer's code, so programmer s we use the identifiers that they chose (such as println) Oft we use special identifiers called reserved words Often i l id tifi ll d d d that already have a predefined meaning in the language A reserved word cannot be used in any other way

1.28

Reserved Words
The Java reserved words:
abstract assert boolean b l break byte case catch char class const continue default do double else enum extends t d final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws th transient try void volatile while

1.29

White Space
Spaces, blank lines, and tabs are called white space White space is used to separate words and symbols in a program Extra white space is ignored A valid J lid Java program can b f be formatted i many ways tt d in Programs should be formatted to enhance readability, using consistent indentation

1.30

Running a Program
Programa sequence of instructions for a computer to follow

Program

Data (input for the program)

Computer

Output

1.31

Program Development
The mechanics of developing a program include several activities ti iti
writing the program in a specific programming language (such as Java, C++, etc ) Java C++ etc.) translating the program into a form that the computer can execute investigating and fixing various types of errors that can occur

Software tools can be used to help with all parts of this process

1.32

Language Levels
There are three programming language levels:
machine language assembly language high level language high-level

Each type of CPU has its own specific machine language The other levels were created to make it easier for a human being to read and write programs

1.33

Programming Languages
Machine language
N t l l Natural language of computer component f t t Machine dependent

Assembly language
English-like abbreviations represent computer operations Assembler converts it to machine language g g

High-level language
Allows for writing more English-like instructions
Contains commonly used mathematical operations

Compiler converts it to machine language I t Interpreter executes high-level l t t hi h l l language programs without ith t compilation

1.34

High-Level Language (HLL) closest to natural language words, numbers words numbers, and math symbols not directly understood by hardware portable source code (hardware independent)

Machine Language least natural language for humans, most natural language , g g for hardware just 0s and 1s directly understood by hardware not portable (hardware dependent)

1.35

Assembly Language (middle level)


a more or less human readable version of machine language words, abbreviations, words abbreviations letters and numbers replace 0s and 1s easily translated from human readable to machine executable code like machine code, not portable (hardware dependent)

1.36

Some High Level Languages


Java Haskell Fortran
FORmula TRANslator

COBOL
COmmon Business Oriented Language

Pascal, Modula BASIC Ada C++, C# C Prolog


1.37

Getting from Source-code to Machine-code SourceMachine A program must be translated into machine language before it can be executed on a particular t b f b t d ti l type of CPU f Each type of CPU executes only a p yp y particular machine language This can be accomplished in several ways A compiler is a software tool which translates source code into a specific target language Often that target language is the machine language for a Often, particular CPU type
1.38

C Compiling a program ili Compiler Compiler

translating from a high-level language source code to machine (object, or executable) code. a program that translates HLL source code to machine (object, or executable) code.

Compilers need to know the specific target hardware

Source Code

Compiler

Target Code (Machine Code)

1.39

Syntax and Semantics


The syntax rules of a language define how we can put together symbols, reserved words, and id tifi t th b l d d d identifiers t to make a valid program The semantics of a program statement define what that statement means (its purpose or role in a program) A program that is syntactically correct is not necessarily logically (semantically) correct A program will always do what we tell it to do, not what we meant t tell it t do t to t ll to d

1.40

Errors
A program can have three types of errors The compiler will find syntax errors and other basic p problems (compile-time errors) p
If compile-time errors exist, an executable version of the program is not created

A problem can occur during program execution, such as trying to divide by zero which causes a program to zero, terminate abnormally (run-time errors) A program may run, but produce incorrect results, perhaps using an incorrect formula (logic errors)
1.41

Syntax Errors
a grammatical error caught by compiler (compiler-time error) automatically found, usually the easiest to fix found cannot run code until all syntax errors are fixed error message may be misleading

Example:
Misspelling a command, f example t i t d of t Mi lli d for l rturn instead f return

1.42

RunRun-Time Errors
An execution error (during run-time) N t always so easy t fix Not l to fi Error message may or may not be helpful Example:
Division by zero - if your program attempts to divide an integer by zero it automatically terminates and prints an error message.

1.43

Logic Errors
Just b J t because it compiles and runs without getting an error message d il d ith t tti does not t mean the program is correct!

An error in the design (the algorithm) or its implementation code compiles without errors no run time error messages run-time but incorrect action or data occurs during execution Generally the most difficult to find and fix Need to be alert and test thoroughly think about test cases and predict results before executing the code Formal Method: use mathematics to develop software and prove its co ec ess correctness
1.44

Basic Program Development


Edit and save program

errors errors
Compile program

Execute program and evaluate results

Edit Compile Debug loop


1.45

Debug
Proses mencari errors dalam suatu program dan memperbaikinya b iki

1.46

Problem Solving
The purpose of writing a program is to solve a problem Solving a problem consists of multiple activities:
U d t d th problem Understand the bl Design a solution Consider alternatives and refine the solution Implement the solution Test the solution

1.47

A Solution needs an algorithm


Given a problem, find an appropriate algorithm. Algorithms are implemented as executable computer programs. Algorithm is an unambiguous, executable, and terminating specification of a way to solve a problem.

1.48

Algorithms
Unambiguous Executable Terminating

If you can't find an algorithm, the computer can't solve your problem.

1.49

Software Categories
Operating System
controls all machine activities provides the user interface to the computer manages resources such as the CPU and memory Windows, Unix, Linux, Mac OS

Application program
generic term for any other kind of software word processors, missile control systems games processors systems,

Most operating systems and application programs have a graphical user interface (GUI)

1.50

Analog vs. Digital


There are two basic ways to store and manage data: Analog
continuous, in direct proportion to the data represented music on a record album - a needle rides on ridges in the grooves that are directly proportional to the voltages sent to the speaker

Digital
the information is broken down into pieces, and each piece is represented separately music on a compact disc - the disc stores numbers representing specific voltage levels sampled at specific times

1.51

Digital Information
Computers store all information digitally:
numbers text graphics and images video audio program instructions

In some way all information is digitized - broken down way, into pieces and represented as numbers

1.52

Representing Text Digitally


For example, every character is stored as a number, including i l di spaces, di it and punctuation digits, d t ti p g pp p Corresponding upper and lower case letters are separate characters

Hi, Heather.

72 105 44 32 72 101 97 116 104 101 114 46

1.53

Binary Numbers
Once information is digitized, it is represented and stored in i memory using th bi i the binary number system b t A single binary digit ( or 1) is called a bit g y g (0 ) Devices that store and move information are cheaper and more reliable if they have to represent only two states A single bit can represent two possible states, like a light bulb that is either on (1) or off (0) Permutations of bits are used to store values

1.54

Bit Permutations
1 bit 0 1 2 bits 00 01 10 11 3 bits 000 001 010 011 100 101 110 111 4 bits 0000 1000 0001 1001 0010 1010 0011 1011 0100 1100 0101 1101 0110 1110 0111 1111

Each additional bit doubles the number of possible permutations

1.55

Bit Permutations
Each permutation can represent a particular item There are 2N permutations of N bits Therefore N bits are needed to represent 2N unique Therefore, items 1 bit ? How many items can be represented by 2 bits ? 3 bits ? 4 bits ? 5 bits ? 21 = 2 items
2 2 = 4 items

23 = 8 items 24 = 16 items 25 = 32 items


1.56

Memory

9278 9279 9280 9281 9282 9283 9284 9285 9286

Main memory is divided y into many memory locations (or cells)

Each memory cell has a numeric address, which uniquely identifies it

1.57

Storing Information

9278 9279 9280 9281 9282 9283 9284 9285 9286

10011010

Each memory cell stores a set number of bits (usually 8 bits, or one byte) Large values are stored in consecutive memory locations

1.58

Storage Capacity
Every memory device has a storage capacity, indicating the th number of bytes it can hold b fb t h ld Capacities are expressed in various units: p p Unit kilobyte megabyte gigabyte terabyte Symbol KB MB GB TB Number of Bytes 210 = 1024 220 (over 1 million) 230 (over 1 billion) 240 (over 1 trillion)
1.59

Memory
Main memory is volatile - stored information is lost if the electric power i removed l ti is d Secondary memory devices are nonvolatile y y Main memory and disks are direct access devices information can be reached directly The terms direct access and random access often are used i t h d interchangeably bl A magnetic tape is a sequential access device since its data is arranged in a linear order - you must get by the intervening data in order to access other information
1.60

You might also like