how to program
DESCRIPTION
TRANSCRIPT
How to Program
Damian Gordon
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.
Characteristics of a System
Characteristics of a Computer System
UserDefined Programs
CPU Peripherals NetworksOperating System
(O/S)Applications
ALGORITHMS
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
Algorithms
In computers we typically design an algorithm before we convert it into a computer program, and execute it.
Algorithms
Problem Solving– Analyse Problem (Analysis)– Develop Algorithm (Design)– Convert into programming language
(Development)
Example
Making a Cup of Tea Utilities
– Cup, tea bag, kettle, water, power supply, sugar, user, milk, spoon/fork.
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
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
Control Statements
Example : Conditional Statement
Conditional Statement
soIf Sugar required then add sugar to teaendif
If <Condition> { <Statements>}
or
Example : Conditional Statement
If <Condition> { <Statements1> } else { <Statements2> }
Nested IF Statements
If <Condition> thenif <Condition> then
<Statements>endif
elseif <Condition>
<Statements>endif
endif
Program Correctness I
Syntax : Rules which define a correct structure
– The cat sat on the mat (legal)– Sat the on the cat mat (illegal)
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
Logical : Correct & complete description of an operation
• Circumference = PI * radius• Syntax = correct• Semantics = correct• Logically = incorrect
Program Correctness III
Circumference = PI * radius * radius
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.
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
…………….
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;
Iteration : WHILE Loop
General Form of WHILE
While <Condition>
{
<Statements>
}
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;
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”
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;
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.
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;
}
Features of Algorithms
Sequence Statement 1 Statement 2 Statement 3
Selection if (condition) { seq-of-stmts; }
Iteration while (condition) { seq-of-stmts; }
EXAMPLES OF ALGORITHMS
Double Number
Double Number
Program DoubleNumber:
{
get number;
print number * 2;
}
Double Number (Alternative)
Program DoubleNumber:
{
get number;
answer = number * 2;
print answer;
}
Triple Number
Triple Number
Program TripleNumber:
{
get number;
answer = number * 3;
print answer;
}
Check for Odd/Even
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;
}
Count Next Ten
Count Next Ten
Program CountToTen:
{
get number;
StopNumber = number + 10;
WHILE (StopNumber > Number)
DO print number;
number = number + 1;
ENDWHILE;
print “I’m Finished”;
}
Sum Numbers 1 to 10
Sum Numbers 1 to 10
Program SumNos1to10:
{
Total = 0;
Number = 1;
WHILE (10 > Number)
DO Total = Total + Number;
Number = Number + 1;
ENDWHILE;
print Total;
}
Check if Number is Prime
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.
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;
}
JAVA Keywords
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
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.
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;
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;
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.)
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;
Java Virtual Machine
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
General Class Declaration
public class program-name { optional-variable-declarations-and-subroutines public static void main(String[] args) { statements } optional-variable-declarations-and-subroutines }
Bubblesort
Bubblesort
Sorting lists of data is an important thing to be able to do
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;
Comments
To add in a few text comments into a program, to help the reader understand it, enclose the comment in “/*” and “*/”
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
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
/* 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 }
Modularisation
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
/* 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 }
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
Bubblesort - Modularised
main( ) {
sort_array;
print_out_solution;
}
List of Variables
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.
Bubblesort - Methods
Factorial
Find the index where a value X is stored
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
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.
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)
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
/* 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;
}