module 10 programming ___tell computers what to do problem solving with computers – problem →...

47
Module 10 Programming ___tell computers what to do Problem solving with computers – Problem → Solution → Algorithm → Programming → Execution • Problems: mean, median, mode, max, min, search • Generations of programming languages – Machine, assembly high level, very high level, natural – Examples of program languages • Programming techniques – procedure oriented programming – object-oriented programming – Programming examples

Post on 19-Dec-2015

222 views

Category:

Documents


1 download

TRANSCRIPT

Module 10 Programming ___tell computers what to do

• Problem solving with computers– Problem → Solution → Algorithm → Programming → Execution

• Problems: mean, median, mode, max, min, search

• Generations of programming languages– Machine, assembly high level, very high level, natural– Examples of program languages

• Programming techniques– procedure oriented programming– object-oriented programming– Programming examples

2

Programming

• Program – a set of detailed, step-by-step instructions that directs the computer to do what you want it to do

• Programming language – a set of rules that provides a way of telling the computer what operations to perform

3

Problem Solving with Programming

• Main steps– Defining the problem– Planning the solution– Designing an algorithm– Coding the program– Testing and executing the program– Maintaining and documenting the program

4

Defining the Problem• Develop a written agreement that

specifies:– The input data– The desired output

• Example:Input: a list of numbersOutput: the mean of the numbers

5

Planning the Solution

• Find out a solution to the problem• Algorithm – a detailed, step-by-step solution to the

problem

• Flow chart or pseudo code can be used as a tool

• Check the solution– Carry out each step of the algorithm with pencil and paper

• Example: Given a[1], a[2], ……, a[100] n = 100

s ← 0, s ← s+a[1], s ← s+a[2], …, s ← s+a[100] mean = s/n;

6

Planning Tools• Flowchart – a pictorial

representation of the algorithm

• Pseudo code – English-like language

e.g. Input: a[i], i = 1, …, 100 s ← 0 for i from 1 to 100 do s ← s + a[i] output: s / n

Start

read a[i]i=1, …, 100

s = 0i =1

s = s +a[i]

i = 100?

Stop

s / i

Yes

No

i == i +1

7

Algorithm Implementation / Program Coding

• Translating the algorithm from the planning stage into a program in a formal programming language

• All languages have syntax rules (grammar)– Similar to grammatical rules– The computer will reject a program with even a minor

syntax error

• Programs can be keyed into the computer by using a text editor

• See examples: calculate 1 + 2 + … + 100

8

Testing the Program

• Two phases of testing the program– Translation

• Converting the program you wrote into the binary instructions the CPU understands

– Debugging• Identifying and correcting logic errors in the

program

9

Translation / execution

• Compiler translates the program (source module) into a machine language version (object module)– If the compiler detects syntax errors, it will

produce messages describing those errors– If no syntax errors exist, the object module will be

linked to create a load module– Load module is executed by the computer

• Run the program to get the output

10

11

Maintaining and Documenting• Update the program to meet new requirement• Record materials are generated at each part

of the process• Common examples of documentation

– Flowchart and/or pseudocode– Comments within the source code– Testing procedures– Layouts of input and output records– A narrative description of the program

12

Levels of Languages

• Lower-level languages – more like the 0s and 1s the computer itself uses

• Higher-level languages – more like the languages people use

• Divided into five generations

13

Five Generations of Languages

• Machine language

• Assembly languages

• High-level languages

• Very high-level languages

• Natural languages

14

Machine Language

• Programs and memory locations are written in strings of 0s and 1s

• 000000 10001 10010 01000 00000 100000Add the numbers in registers s1 and s2 and put the result in t0

• Problems with machine languages– Programs are difficult to write and debug– Each computer has its own machine language

• Only option available to early programmers

15

Assembly Languages

• Substitute mnemonic codes for 0s and 1s – For example

000000 10001 10010 01000 00000 100000 => add $t0, $s1, $s2.– Use names rather than binary addresses for

memory locations

• Require an assembler to translate the program into machine language

• Still used for programming chips and writing utility programs

16

High-Level Languages (HLL)

• Transformed programming– Programmers could focus on solving problems rather than

manipulating hardware– Programs could be written and debugged much more

quickly

• Requires a compiler to convert the statements into assembly /machine language– Each computer has its own version of a compiler for each

language

17

Very High-Level Languages

• Also called fourth-generation languages (4GLs)

• Considered nonprocedural languages– The programmer specifies the desired results,

and the language develops the solution– Programmers can be about 10 times more

productive using a fourth-generation language than a third-generation language

18

Natural Languages

• Resemble written or spoken English– Programs can be written in a natural syntax,

rather than in the syntax rules of a programming language

• The language translates the instructions into code the computer can execute

19

Examples of High Level Programming Languages

• FORTRAN• COBOL• BASIC• C• Java

20

FORTRAN

• The first high-level language• Stands for FORmula TRANslator• Used primarily for engineering, mathematical,

and scientific tasks• Good for numerical computation

21

COBOL

• Stands for COmmon Business-Oriented Language

• Used primarily for business requirements– Processes large data files– Produces well-formatted reports

22

BASIC

• Stands for Beginners’ All-Purpose Symbolic Instruction Code

• Developed to teach programming to college students

• Became very popular with the introduction of the microcomputer

23

C

• Originally designed to write systems software– Offers the ease of use of a high-level language with

the efficiency of an assembly language

• Very portable – can be used with virtually every combination of computer and operating system

24

Java

• A network-friendly programming language that permits a piece of software to run directly on many different platforms– Allows programmers to write one version of the

program, rather than a separate version of each platform

• Very useful for Internet development– Java applets can run in the user’s Web browser

25

Algorithm Designs

• The algorithm must be correct. – Can stop in reasonable amount time– Give the correction answer / solution– Robust

• The algorithm should be efficient– Use less amount of time to complete the

computation– Use less amount of memory space to carry

out the compute

26

Program Design Structured Programming

• Get input:– from keyboard, file, generate automatically

• Computation on the input by the algorithm– the core of the program implementing an

algorithm

• Output the result– to screen, file, in certain format

27

Procedure Oriented Programming

• Features: linear style, the program has a main stream

• Fortran, basic, C are languages for POP

• Common features– Data type and variable: integer, floating point, list, etc– Modular: routine, procedure, function and library– Programming constructs:

• serial, selection/branch, repetition/loop

28

Program constructsThere are basic three programming constructs1. Sequential

– do things one by one in sequence

2. Selection: – do one thing under a condition; do another thing under

another condition– If statement

3. Repetition: – do the same thing for many times– For loop

• A program consists of a combination of the three construct

29

<script type = "text/javascript"><!--

var a = prompt("What is the value of 'a'? \n", "");var b = prompt("What is the value of 'b'? \n", "");var c = prompt("What is the value of 'c'? \n", "");

var denom = 2.0 * a;var det = b * b - 4.0 * a * c;

if (det >= 0){var root_part = Math.sqrt(det);var root1 = (-b + root_part) / denom;var root2 = (-b - root_part) / denom;document.write("The first root is: ", root1, "<br />");document.write("The second root is: ", root2, "<br />");}else { var root_part = Math.sqrt(-det);var real = -b / denom;var imagine = root_part / denom;document.write("The first root is: ", real,"+", imagine, "i", "<br />");document.write("The second root is: ", real, "-", imagine,"i", "<br />");}

--></script>

Sequential construct

Selection construct

30

<script type = "text/javascript">

<!--// Get input n

var n = prompt("What is the value of 'n'? \n", "");var sum =0;var i;

// compute the sumfor (i = 1; i<= n; i++) sum = sum + i; // display the resultdocument.write("The sum of 1 + 2 +...+", n, " = ",

sum, "<br />");

--></script>

Repetition construct

31

Four programming examples

1. Calculate the mean of a given data set

2. Find the max or min of a given data set

3. Sort the given data set in increasing order

4. Calculate the median

Question :

How do you find the mode of a given data set ?

32

Mean

• Input: a[0], …, a[n-1]• Output: (a[0]+…+a[n-1])/n• Pseudo code

sum = 0for i from 0 to n-1 do

sum ¬ sum + a[i]end for

mean = sum/noutput mean

33

<script type = "text/javascript"><!--// Input: data setvar data_set = new Array(1, 6, 4, 6, 3, 10);

// computationn = data_set.length;sum = 0;for (i = 0; i<n; i++){ sum = sum + data_set[i];}

mean = sum/n;//outputdocument.write("<p>The mean of the data set is ", mean, "</p>");

// --></script>

34

Find maximum

• Input: a[0], …, a[n-1]

• Output: the maximum of a[0], …., a[n-1]

• Pseudo codemax = a[0]for i from 1 to n-1 do

if a[i] > max then max ¬ a[i]end foroutput max

35

<script type = "text/javascript"><!--// Input: data set

var data_set = new Array(33, 61, 71, 10, 23, 29, 99);// computation

length = data_set.length;

var current_max = data_set[0];

for (i = 1; i<length; i++){ if (data_set[i] > current_max) current_max = data_set[i];}//outputdocument.write("<p>The maxium element is: ", current_max, "</p>");

// --></script>

36

Sort (in increasing order)• Input: a[0], …, a[n-1]• Output: a list of a[0], …., a[n-1] in increasing order• Pseudo code

for i from 0 to n-1 do find a[j] minium amount a[i], … a[n-1] if j is not equal to I swap a[i] and a[j]

end for

output a[0]

37

<script type = "text/javascript"><!-- // Input: data setdata_set = new Array(10, 6, 4, 6, 3, 1, -2);// sorttingn = data_set.length;for (i = 0; i<n; i++){ min = data_set[i]; min_position = i;

for (j = i; j<n; j++){ if (data_set[j] < min){ min = data_set[j]; min_position = j; } } if (min_position != i) { data_set[min_position] = data_set[i]; data_set[i] = min; }} //outputfor (i=0; i<n; i++) document.write(data_set[i], ", ");//--></script>

38

Median• Input: a[0], …, a[n-1]• Output: the median of a[0], …., a[n-1]• Pseudo code

sort a[0], …., a[n-1]if n is odd ouput a[(n+1)/2]else output (a[n/2-1]+a[n/2])/2

39

data_set = new Array(10, 6, 4, 6, 3, 1);n = data_set.length;

for (i = 0; i<n; i++){ min = data_set[i]; min_position = i; for (var j = i; j<n; j++){ if (data_set[j] < min){ min = data_set[j]; min_position = j; } } if (min_position != i) { data_set[min_position] = data_set[i]; data_set[i] = min; }}

if (n % 2 == 0) median = (data_set[n/2-1]+data_set[n/2])/2;else median = data_set[(n-1)/2];

document.write("The median is ", median);

40

Object-Oriented Programming

• Object – a self-contained unit that contains both data and its related functions

• Key terms in object-oriented programming– Encapsulation – an object isolates both its data and

its related instructions– Attributes – facts that describe the object

• Also called properties

– Methods – instructions that tell the object to do something

– Messages – an outside stimulus that results in the change of the state of an object

41

Using Objects

• Programmers define classes of objects– The class contains all attributes that are unique

to objects of that class– An object is an instance (occurrence) of a class

• Objects are arranged hierarchically in classes and subclasses– Subclasses are derived from classes– Inheritance – a subclass possesses all attributes

of the class from which it is derived– Additional attributes can be coded in the

subclasses

42

Activating the Object

• A message is sent to the object, telling it to do something– The object’s methods tell it how to do it

• Polymorphism – each object has its own way to process the message– For example, the class may have a Move

method, but each subclass implements that method differently

43

Object-Oriented Languages

• C++

• Java

• C#

• Visual Basic

44

C++

• An enhancement of the C language– Includes all features of C – Adds support for object-oriented programming

• Can be used as simply an improvement of C, without the object-oriented features

45

Java

• A pure object-oriented program

• Used to create small programs called applets– Applets can be delivered over the Web and

run on any platform

46

C#

• Microsoft’s answer to Java

• Has the same advantages over C++ that Java has

• Designed to work within Microsoft’s .NET environment– .NET is designed for building, deploying, and

running Web-based applications

47

Visual Basic

• Allows programmer to create Windows-like user interfaces– Programmer drags a control (button, text box, etc.) onto the form– VB creates the code associated with that control

• VB is event-driven– The user controls the program

• Previous versions supported some object technology• The current version, VB.NET, is the first to support

inheritance and polymorphism– These two traits are required for a true object-oriented language