how to program

77
How to Program Damian Gordon

Upload: damian-gordon

Post on 29-Nov-2014

302 views

Category:

Education


7 download

DESCRIPTION

 

TRANSCRIPT

Page 1: How to Program

How to Program

Damian Gordon

Page 2: How to Program

Ozymandias

I met a traveler from an antique land Who said: Two vast and trunkless legs of stone Stand in the desert . . . Near them, on the sand, Half sunk, a shattered visage lies, whose frown,

And wrinkled lip, and sneer of cold command Tell that its sculptor well those passions read

Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed.

And on the pedestal these words appear: "My name is Ozymandias, king of kings:

Look on my works, ye Mighty, and despair!"

Nothing beside remains. Round the decay Of that colossal wreck, boundless and bare The lone and level sands stretch far away.

Page 3: How to Program

Characteristics of a System

Page 4: How to Program

Characteristics of a Computer System

UserDefined Programs

CPU Peripherals NetworksOperating System

(O/S)Applications

Page 5: How to Program

ALGORITHMS

Page 6: How to Program

Algorithms

An Algorithm is a series of instructions Examples of algorithms include

– Musical scores

– Knitting patterns Row 1: SL 1, K8, K2 tog, K1, turn

– Recipes

Page 7: How to Program

Algorithms

In computers we typically design an algorithm before we convert it into a computer program, and execute it.

Page 8: How to Program

Algorithms

Problem Solving– Analyse Problem (Analysis)– Develop Algorithm (Design)– Convert into programming language

(Development)

Page 9: How to Program

Example

Making a Cup of Tea Utilities

– Cup, tea bag, kettle, water, power supply, sugar, user, milk, spoon/fork.

Page 10: How to Program

Example

Steps1. Organise everything together2. Plug in kettle3. Put teabag in cup4. Put water into kettle5. Turn on kettle6. Wait for kettle to boil7. Add water to cup8. Remove teabag with spoon/fork9. Add milk and/or sugar10. Serve

Page 11: How to Program

Example : Step-wise Refinement

Step-wise refinement of step 4 (Put water into kettle)

4.1 Bring kettle to tap

4.2 Put kettle under water

4.3 Turn on tap

4.4 Wait for kettle to be full

4.5 Turn off tap

Page 12: How to Program

Control Statements

Page 13: How to Program

Example : Conditional Statement

Conditional Statement

soIf Sugar required then add sugar to teaendif

If <Condition> { <Statements>}

Page 14: How to Program

or

Example : Conditional Statement

If <Condition> { <Statements1> } else { <Statements2> }

Page 15: How to Program

Nested IF Statements

If <Condition> thenif <Condition> then

<Statements>endif

elseif <Condition>

<Statements>endif

endif

Page 16: How to Program

Program Correctness I

Syntax : Rules which define a correct structure

– The cat sat on the mat (legal)– Sat the on the cat mat (illegal)

Page 17: How to Program

Semantics : Rules which attach meaning to symbols

– The mat sat on the cat (syntactically correct, but semantically incorrect)

– Choose a number 1 to 14, call this number N, write down the Nth month of the year (syntactically correct, but semantically incorrect)

Program Correctness II

Page 18: How to Program

Logical : Correct & complete description of an operation

• Circumference = PI * radius• Syntax = correct• Semantics = correct• Logically = incorrect

Program Correctness III

Circumference = PI * radius * radius

Page 19: How to Program

Iteration : WHILE Loop

Consider filling the kettle

WHILE kettle not full

DO keep filling kettle

ENDWHILE;

So this will keep looping while the kettle is not full, as soon as it’s full, the loop finishes.

Page 20: How to Program

Iteration : WHILE Loop

Consider the problem of searching for an entry in a phone book with only condition :

Get first entry

If this is the required entry

Then write down phone number

Else get next entry

If this is the correct entry

then write done entry

else get next entry

if this is the correct entry

…………….

Page 21: How to Program

Iteration : WHILE Loop

We may rewrite this as follows:get first entry;

call this entry N;

WHILE N is NOT the required entry

DO Get next entry;

call this entry N;

ENDWHILE;

Page 22: How to Program

Iteration : WHILE Loop

General Form of WHILE

While <Condition>

{

<Statements>

}

Page 23: How to Program

Variables

We can create a container to store values, we call these variables.

A number variable can be declared as follows;– int x;

This means there a container created that is called ‘x’ and is of type ‘int’ (integer)

If we wanted to declare a container for a single character it would be

– char y;

Page 24: How to Program

Variables

To insert a value into a variable, we called this “assignment”, and we use the “=“ symbol, so

– x = 5;

Which reads as “the integer variable x is assigned the value 5”

For the character y– y = “H”

Which reads as “the character variable y is assigned the value H”

Page 25: How to Program

Increment

If we do– int x;– x=5;

To add one onto X, we can do the following;– x = x + 1;

Which means x gets a new value, which is the old value of x but with one added to it.

We can also just do;int x = 5;

Page 26: How to Program

Check if number is prime

How do we check if a number is prime ? If the number is X then it is prime if only 1

and X divide evenly into it. Or to restate, if the numbers 2 to X-1 do not

divide evenly into X, then it is prime. Thus our program has to count from 2 to

X-1 and divide that value by X, if the answer is a whole number X is not prime.

Page 27: How to Program

Check if number is prime

N = 2;

WHILE Prime > (N – 1) {

IF (Prime % N eq 0){

Print “The Number is Not Prime”

}

N = N +1;

}

Page 28: How to Program

Features of Algorithms

Sequence Statement 1 Statement 2 Statement 3

Selection if (condition) { seq-of-stmts; }

Iteration while (condition) { seq-of-stmts; }

Page 29: How to Program

EXAMPLES OF ALGORITHMS

Page 30: How to Program

Double Number

Page 31: How to Program

Double Number

Program DoubleNumber:

{

get number;

print number * 2;

}

Page 32: How to Program

Double Number (Alternative)

Program DoubleNumber:

{

get number;

answer = number * 2;

print answer;

}

Page 33: How to Program

Triple Number

Page 34: How to Program

Triple Number

Program TripleNumber:

{

get number;

answer = number * 3;

print answer;

}

Page 35: How to Program

Check for Odd/Even

Page 36: How to Program

Check for Odd/Even

Program IsOddOrEven:

{

get number;

IF(number /2 gives no remainder)

THEN print “It’s Even”;

ELSE print “It’s Odd”;

EndIf;

}

Page 37: How to Program

Count Next Ten

Page 38: How to Program

Count Next Ten

Program CountToTen:

{

get number;

StopNumber = number + 10;

WHILE (StopNumber > Number)

DO print number;

number = number + 1;

ENDWHILE;

print “I’m Finished”;

}

Page 39: How to Program

Sum Numbers 1 to 10

Page 40: How to Program

Sum Numbers 1 to 10

Program SumNos1to10:

{

Total = 0;

Number = 1;

WHILE (10 > Number)

DO Total = Total + Number;

Number = Number + 1;

ENDWHILE;

print Total;

}

Page 41: How to Program

Check if Number is Prime

Page 42: How to Program

Check if number is prime

How do we check if a number is prime ? If the number is X then it is prime if only 1

and X divide evenly into it. Or to restate, if the numbers 2 to X-1 do not

divide evenly into X, then it is prime. Thus our program has to count from 2 to

X-1 and divide that value by X, if the answer is a whole number X is not prime.

Page 43: How to Program

Check if number is prime

N = 2;

WHILE Prime > (N – 1) {

IF (Prime % N eq 0) {Print “The Number is Not Prime”;

}

N = N +1;

}

Page 44: How to Program

JAVA Keywords

Page 45: How to Program

JAVA Keywords

abstract double int strictfp

boolean else interface super

break extends long switch

byte final native synchronized

case finally new this

catch float package throw

char for private throws

class goto protected transient

const if public try

continue implements return void

default import short volatile

do instanceof static while

Page 46: How to Program

Variables

According to the syntax rules of Java, a name is a sequences of one or more characters. It must begin with a letter and must consist entirely of letters, digits, and the underscore character '_'. For example, here are some legal names:

N n rate x15 quite_a_long_name HelloWorld

Uppercase and lowercase letters are considered to be different, so that HelloWorld, helloworld, HELLOWORLD, and hElloWorLD are all distinct names. Certain names are reserved for special uses in Java, and cannot be used by the programmer for other purposes. These are the reserved words.

Page 47: How to Program

Assignment (I)

In Java, the only way to get data into a variable -- that is, into the box that the variable names -- is with an assignment statement. An assignment statement takes the form:

variable = expression;

where expression represents anything that refers to or computes a data value. When the computer comes to an assignment statement in the course of executing a program, it evaluates the expression and puts the resulting data value into the variable. For example, consider the simple assignment statement

rate = 0.07;

Page 48: How to Program

Assignment (II)

The variable in this assignment statement is rate, and the expression is the number 0.07. The computer executes this assignment statement by putting the number 0.07 in the variable rate, replacing whatever was there before. Now, consider the following more complicated assignment statement, which might come later in the same program:

interest = rate * principal;

Page 49: How to Program

Declaring Variables (I)

A variable can be used in a program only if it has first been declared. A variable declaration statement is used to declare one or more variables and to give them names. When the computer executes a variable declaration, it sets aside memory for the variable and associates the variable's name with that memory. A simple variable declaration takes the form:

type-name variable-name-or-names;

The variable-name-or-names can be a single variable name or a list of variable names separated by commas. (We'll see later that variable declaration statements can actually be somewhat more complicated than this.)

Page 50: How to Program

Declaring Variables (II)

Good programming style is to declare only one variable in a declaration statement, unless the variables are closely related in some way. For example:

int numberOfStudents;String name;double x, y;boolean isFinished;char firstInitial, middleInitial, lastInitial;

Page 51: How to Program

Java Virtual Machine

Page 52: How to Program

Hello World Program

public class HelloWorld { // A program to display the message // "Hello World!" on standard output

public static void main(String[] args) { System.out.println("Hello World!"); } } // end of class HelloWorld

Page 53: How to Program

General Class Declaration

public class program-name { optional-variable-declarations-and-subroutines public static void main(String[] args) { statements } optional-variable-declarations-and-subroutines }

Page 54: How to Program

Bubblesort

Page 55: How to Program

Bubblesort

Sorting lists of data is an important thing to be able to do

Page 56: How to Program

Array

A list of variables is called an array.

Instead of;– int x1=0;– int x2=0;– int x3=0;– int x4=0;

We can do;– int x[4];

And then we can access the elements as follows;

– x[0]=0;– x[1]=0;– x[2]=0;– x[3]=0;

Page 57: How to Program

Comments

To add in a few text comments into a program, to help the reader understand it, enclose the comment in “/*” and “*/”

Page 58: How to Program

Swapping values

If x =5 and y=8, and we want to swap the two values, this will NOT work;– x = y;– y = x;

Because if we look at these statements, what we are saying one step at a time

– Before : x =5 and y=8– x = y– Now: x = 8 and y = 8– y = x;– So same thing; x = 8 and y = 8

Page 59: How to Program

Swapping values

So what we need to do is add another variable Z; Now if x =5 and y=8,

– z = x;– x = y;– y = z;

Because if we look at these statements, what we are saying one step at a time

– Before : x =5 and y=8 and z =0– z = x– Now: x = 5 and y = 8 and z=5– x = y;– Now: x = 8 and y = 8 and z=5– y = z;– Now: x = 8 and y = 5 and z=5

Page 60: How to Program

/* Program to sort an array of integers using the Bubblesort algorithm *//* Program Name : Bubblesort.java * Developer : Damian Gordon * Description : Implement the Bubblesort Algorithm */

public class bubblesort {

public static void main (String args []) {

/********************************************/ /* Declaration of variables */ /********************************************/

int myarray[] = {45, 56, 34, 78, 443453, 2}; // Unsorted array int outercount = 0; // Outer count int innercount = 0; // Inner count int swap_variable = 0; // Swap variable

/********************************************/

while (outercount < 36) // 36 is max number of swaps { while (innercount < 5) // count from 0 to 5 { if ( myarray[innercount] > myarray[innercount+1]) {

/* Do swap */ swap_variable = myarray[innercount]; myarray [innercount] = myarray [innercount+1]; myarray [innercount+1] = swap_variable;

} innercount = innercount +1; } innercount = 0; // reset inner count outercount = outercount + 1; // increment outer count }

Page 61: How to Program

Modularisation

Page 62: How to Program

Modularisation

If we review the Bubblesort program, it is clear that there are two main processes occurring in the program ;– Sort Array

– Print out solution

Page 63: How to Program

/* Program to sort an array of integers using the Bubblesort algorithm *//* Program Name : Bubblesort.java * Developer : Damian Gordon * Description : Implement the Bubblesort Algorithm */

public class bubblesort {

public static void main (String args []) {

/********************************************/ /* Declaration of variables */ /********************************************/

int myarray[] = {45, 56, 34, 78, 443453, 2}; // Unsorted array int outercount = 0; // Outer count int innercount = 0; // Inner count int swap_variable = 0; // Swap variable

/********************************************/

while (outercount < 36) // 36 is max number of swaps { while (innercount < 5) // count from 0 to 5 { if ( myarray[innercount] > myarray[innercount+1]) {

/* Do swap */ swap_variable = myarray[innercount]; myarray [innercount] = myarray [innercount+1]; myarray [innercount+1] = swap_variable;

} innercount = innercount +1; } innercount = 0; // reset inner count outercount = outercount + 1; // increment outer count }

Page 64: How to Program

System.out.println("The anwswer is : ");

outercount = 0; // reset outercount

/********************************************/ /* Print out sorted array */ /********************************************/

while (outercount < 6) { System.out.println(myarray[outercount]); outercount ++; }

/*********************************************/

} // End MAIN} // End CLASS

Page 65: How to Program

Bubblesort - Modularised

main( ) {

sort_array;

print_out_solution;

}

Page 66: How to Program

List of Variables

Page 67: How to Program

Which variables are owned by which module?

myarray[] is shared by everyone; outercount, innercount and swap_variable

are used by sort_array a new count variable should be used to print

out variable values.

Page 68: How to Program

Bubblesort - Methods

Page 69: How to Program
Page 70: How to Program
Page 71: How to Program

Factorial

Page 72: How to Program

Find the index where a value X is stored

Page 73: How to Program

Find the index where a value X is stored

Assume vector is called A and is of length 10.FIND-X-IN-A

i = 0While A(i) not = X and i not =10

i = i + 1End-WhileIf i not = 10

Print X, " resides in vector element number ", ielse

Print X, " is not resident in vector A"End-if

END

Page 74: How to Program

Searching a sorted vector

Search sorted vector A of length n for value x.

ProcessFind the middle of the vector.

If the value x is greater than the middle element, search the top half of the vector.

If the value x is less than the middle element, search the bottom half of the vector.

If the value x is equal to the middle element, the value x has been found.

If the bottom of the vector = the top of the vectorthe element is not there.

Page 75: How to Program

Constructs

Subroutine which searches the vector, given the vector name, the vector top and bottom

boundaries and the value being sought.

In the subroutine:Test for empty vector

If vector is not empty:

when middle value = sought value, value is foundwhen middle value < sought value, search upper halfwhen middle value > sought value, search lower half

Call the subroutine.

Position = BINARY-SEARCH(P, Q, A, X)

Page 76: How to Program

BINARY-SEARCH (P, Q, A, X)

if P > Q position = 0

elsemiddle = (P+Q)/2Case TRUE ofX < A(middle):

position =BINARY-SEARCH(P, middle - 1, A, X)X > A(middle):

position =BINARY-SEARCH(middle + 1, Q, A, X)X = A(middle):

position = middleend-case

end-ifEND

Page 77: How to Program

/* program to take in an array and an element valueand find the element in the array */

#define N 10#include <stdio.h>main (){

int binary_search(int,int,int [],int);int a[N]= {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};int pos, x, start, end;

printf ("\nEnter the number you are looking for:");scanf ("%d",&x);start = 0;end = N-1;pos = binary_search(start, end, a, x);if (pos >= 0)

printf ("\nThe value %d is in position %d",x,pos);else

printf ("\nThe value %d is not in the array",x);return 0;

}