Download presentation
1
Programming Section 3
2
WHAT IS AN ALGORITHM? An algorithm is a sequence of precise instructions for solving a problem in a finite number of steps. Properties/Characteristics: Algorithms must: be precise, be unambiguous, be logically sequenced, give the correct solution an all cases, and eventually end.
3
Algorithmic structure
Header : Algorithm’s name or title Declaration : Brief description of algorithm and variables used. i.e. A statement of purpose as well as the initialization of variables Body : Sequence of steps Terminator : An end statement
4
ALGORITHMIC STRUCTURE
Problem: Write an algorithm that prompts a student to enter his/her name and age, accepts the name and age and then display a welcoming message on the screen such as “hello Michael! You are 16 years old!” Write the algorithm identifying the header, declaration, body and terminator.
5
ALGORITHMIC STRUCTURE
Algorithm Student data {Header} This algorithm displays a student’s name and age on the screen. {declaration} Start Display “Enter your name:” Accept Name Display “Enter your age:” Accept Age Display “Hello”, Name Display “You are”, Age, “years old” Stop {Terminator} {Body}
6
EXAMPLE Write an algorithm that will read the radius of a circle and calculate and display its perimeter. Input Processing Output radius Accept radius Calculate circumference Store results in circumference Display circumference circumference Step 1: start Step 2: read radius Step 3: circumference 2 * 3.14* radius Step 4: write circumference Step 5: stop
7
EXAMPLE Write an algorithm that displays the area of a rectangle by accepting length and width from the user. Input Processing Output length, width Accept length, width Calculate area Store results in area Display area Area Step 1: start Step 2: read length, width Step 3: area length * width Step 4: write area Step 5: stop
8
EXAMPLE Write an algorithm to read three numbers and find their product. Input Processing Output Three numbers (num1, num2,num3) Accept numbers Calculate product Store results in product Display product Product Step 1: start Step 2: read num1, num2, num3 Step 3: product num1*num2*num3 Step 4: write product Step 5: stop
9
FLOWCHARTS VERSUS PSEUDOCODE
Pseudocode is more concise, closely resembles programming language Flowchart gives good view of the structure and flow of the logic Beginners tend to follow the logic easier when using flowcharts rather than pseudocode Longer, more complex solutions are better represented using pseudocode.
10
FLOWCHARTS VERSUS PSEUDOCODE
Usage is a matter of preference for experienced programmers Students should be asked to use both flowcharts as well as pseudocode to represent algorithms Flowcharts must use special geometrical objects that designate the basic steps of a program: Flow of Control Processing/ Assignment Start/ Stop Input/Output Decision
11
PSEUDOCODE AND FLOWCHART
Start Get num1, num2, num3 Average (num1 + num2 + num3)/3 Print Average Stop Start Read num1, num2, num3 Average (num1+num2+num3)/3 Print Average Stop
12
Draw flowcharts for the following programs:
Program to accept the price of an item and calculate its VAT at 15%. start read price vat price *.15 write vat stop
13
Example start read us write ec
Program to accept money in US dollars and convert it to its equivalent local currency. read us ec us *2.71 write ec stop start
14
Distinguish between variables and constants;
Variable = the name identifies what the value represents. Constant = A value (Alphabetical/numerical) that never changes during processing. (Eg. the value of PI)
15
Use appropriate data types
Examples String “Hello”, “Carl” “New York” “Mary” Character a,e,i,o,f,h,j,k,h Real or Floating point 2.3, 45.6, 36.3, 88.1, 3.5, Boolean Yes, No, True, False, Integer/Whole numbers 1,4,988,99,88,66,
16
Control Structures That are commonly used in programming languages.
Sequencing- Execute one single instruction, in a section of program, after another. Selection- Choose, depending on a tested condition, between two, or more pathways through a section of a program. Repetition/Looping- Executing a single instruction, or group of instructions, one or more times.
17
EXAMPLE OF CONTROL STRUCTURES
Sequence
18
SELECTION STRUCTURES IF … THEN … ELSE construct syntax:
IF (expression) THEN {Statements} executed only if condition is TRUE ELSE {Statements} executed only if condition is FALSE ENDIF Only one group of statements could be executed each time the program is executed.
19
SELECTION STRUCTURES Get Mark
IF Mark >= 50 THEN PRINT “ Well done” ELSE PRINT “Must do better” ENDIF Stop “Well done” will be printed should the student’s mark be 50 or greater. If the mark is less than 50 then the statement “Must do better” would be printed.
20
REPETITION STRUCTURES
Repetition or Loop or Iteration structures allow statements to be repeated a fixed number of times or until some condition evaluates to false. There are three repetition constructs: FOR Loop - counted loop REPEAT Loop - conditional loop WHILE Loop - conditional loop
21
The basic structure of the loop is:
Initialise a variable to a star value (usually determines whether or not the loop is executed) Test variable against condition Execute the body of the loop Update the value of the start variable
22
Loop Statement There are two types of loop statements: Indefinite: This refers to when you do not know beforehand how many times to repeat the loop. (WHILE and REPEAT loops) General Form of the WHILE-DO loop WHILE (condition) Statement Example. Age = 16 WHILE (age <21) DO BEGIN Output "You cannot drink" Age = age + 1 END Output "The loop has ended"
23
REPEAT LOOP
24
Definite This refers to when you know beforehand how many times to repeat the loop. (FOR loop)
25
Note: i. The symbols := must go together ii. Variable must be in order so it can be counted. iii. Variable begins with start value. iv. Loop variable is increased every time the loop goes around. v. The loop will terminate/end when the counter reaches the value of the final expression
26
INITIALIZATION OF VARIABLES
Variables that are used as counters or used to store totals should always be assigned an initial value of 0 before they are incremented.This is called initialization Counters This is the process of counting the number of times a value is entered or a statement is carried out. You can also allow your counter to begin at 0 and then increment (increase accordingly). E.g. Counter <--- 0 Counter <---- Counter + 1 In the example above, counter is initially set at 0, which means that every time the assignment statement is executed, the value of the counter variable is increased by 1. Initialization may appear to be a trivial step, but it is very important. Many programs fail to work correctly, simply because the programmer forgot to initialize a counting variable.
27
Draw flowcharts for the following
. Algorithm: Set the number = 1 Set the total = 0 While (number <= 100) total = total + number number = number + 1 End While Display total
28
While Loop Start Set number = 1 Set total = 0 No number <= 100 Yes
total + number number = number + 1 Display total End No Yes
29
Use of relational operators:
The following relational operators are used: Table 1 Relational Operators Operator Name Symbol Description Equal = Returns true if both sides are equal. Greater than > Returns true if the variable on the left is greater than the variable on the right. Less than < Returns true if the variable on the left is less than the variable on the right. Greater than or equal to >= Returns true if the variable on the left is greater than or equal to the value of the variable on the right. Less than or equal to <= Returns true if the variable on the left is less than or equal to the value of the variable on the right. Not equal to <> Returns true if both sides are not equal.
30
example Operator Symbol Example (Assume A = 20, B = 15) True when
Table 2 truth table for relational operators Operator Symbol Example (Assume A = 20, B = 15) True when False when Result = A = B A and B are same or equal A and B are different False > A > B A is greater than B A is not greater than B True < A < B A is less than B A is not less than B >= A >= B A is greater than or equal to B B is greater than A <= A <= B A is less than or equal to B B is less than A <> A <> B A is not equal to B
31
Logical Operators The logical operators are used for Boolean expressions. A Boolean expression can be in one of two states: True or False. Depending on the state of the expression. The three basic types of logical operators are: NOT, AND, OR
32
NOT OPERATOR NOT is a unary operator — it is applied to only one value and inverts it: · not true = false · not false = true
33
· FALSE and FALSE - FALSE
AND OPERATOR AND yields TRUE ONLY if both values are TRUE: · TRUE and FALSE = FALSE · TRUE and TRUE = TRUE · FALSE and TRUE = FALSE · FALSE and FALSE - FALSE
34
· TRUE or FALSE = TRUE · FALSE or TRUE = TRUE · FALSE or FALSE = FALSE
OR OPERATOR OR yields TRUE if at least one value is TRUE: · TRUE or TRUE = TRUE · TRUE or FALSE = TRUE · FALSE or TRUE = TRUE · FALSE or FALSE = FALSE
35
EXAMPLE A = 10, B = 12, C = 14, D = 11 1. A = B (FALSE)
3. (A < C) AND (B < D) (FALSE) 4. (A>B) OR (A < 5 (FALSE) )5. (D>A) AND (C > D) ( TRUE) 6. (A>B) OR ((A+B)<(A *B)) (TRUE) 10>12 (f) 0R 10+12<10*12 7. NOT (B>D) (TRUE) 22 120
36
Arithmetic Operations
Some arithmetic operations offered by Darwin. Operation Symbol Example Result addition + 101+27 128 subtraction - 15-3 12 multiplication * 5*3 15 division / 6/2 3
37
test algorithms for correctness
We use a trace table which is one that is completed by tracing the instruction in the algorithm with appropriate data to arrive at solutions. The column headings of a trace table record the names of all the variables used in the algorithm. The rows record the state of the variables after every instruction execution.
38
Copy the following trace table
Copy the following trace table. Complete the trace table, given that the number 4 is the input value for X. Read X For M = 1 to X do Y = X – M Z = 5 * Y – M END Print Z What does the algorithm prints? 3 14 2 2 3 1 2 4 -4 Z= 14,8,2,-4 The algorithm prints -4
39
test algorithms for correctness;
6 3*2 3 2+1 1-1 -1 18 6*3 3 3+0 0-1
40
use the top-down design approach to problem solving.
Top-Down Design Approach or Modular Programming as it is sometimes called involves breaking a problem into a set of smaller problems, called sub-problems or modules, followed by breaking each sub-program into a set of tasks, then breaking each task into a set of actions. This is called stepwise refinement General Rule in modular programming is that a module should be comprised of statements that contribute to a single, specific task. .
41
Steps in Modularization:
1. Define the problem 2. From the processing section, identify the tasks that will determine the modules that will make up the program. Each non-trivial task should constitute a module. 3. Construct a hierarchy chart showing the modules and the relationship between them. 4. Formulate the algorithm for the main module in either pseudocode or flowchart. 5. Develop sub-algorithms for each module. 6. Test the algorithm for correctness.
42
Advantages of the Top-Down Design Method:
1. It makes the problem solution more manageable. It is easier to comprehend the solution of a smaller and less complicated problem that to grasp the solution of a large and complex problem. 2. It is easier to test segments of solutions, rather than the entire solution at once. 3. A simplified solution takes less time to develop and will be more readable. 4. The program will be easier to maintain.
43
A Hierarchy chart or structure chart is a tree-like structure that shows visually the relationships between the modules of a program
44
EXAMPLE 1.1: Given a list of students test scores, find the highest and lowest score as well as the average score. Four sub-problems can be identified here: 1. Sub-problem 1: read list of test scores 2. Sub-problem 2: find_the_highest_score 3. Sub-problem 3: find_the_lowest_score 4. Sub-problem 4: find_the_average
45
A Hierarchy chart
46
Flowchart for the above algorithm is:
47
distinguish between low-level and high-level programming languages;
Low level languages- These are languages which are machine dependent; that is, when a code is written on a particular machine, it can only be understood by that machine. High level languages- These are languages that are machine independent; that is, when a code is written on a particular machine, it is not limited to execution on that machine only but can also run on other similar machines.
48
distinguish among the differe generations of programming languages
First Generation Language- These are also called machine languages and are characterized by ones and zeros, which make up a binary code. A sample instruction might be Second-generation language- These are also called assembly languages and are characterized by abbreviated words, called mnemonics. A sample code might be ‘Add 12,8’
49
Cont’d Third- generation Languages- These are designed
so that it is easier for the programmer to understand. A compile converts the statements of a specific language into machine language. Fourth generation language (4Gls)- These are designed to be closer to natural language than a 3GL. Languages for accessing databases are often described as 4GLs. *A sample instruction might be EXTRACT ALL CUSTOMERS WHERE 'PREVIOUS PURCHASES' TOTAL MORE THAN $1000.
50
Fifth Generation- Programming that uses a visual or graphical development interface to create the source code. They are often described as very high level language.
51
To get the object code from the source code,
We use a translator programme. Three types of such programmes are interpreters, compilers and assemblers. Interpreter- Translates the source code, line by line. If an error is detected, translation is stopped. Compiler-Translates all instructions at once and produces a stand-alone object code that can be executed. Assembler-Translates mnemonic-type instructions [Assembly Language] to machine code.
52
List the sequence of steps associated with implementing a program;
Creating source code Compiling Linking Executing Maintaining.
53
Difference between Sources codes are programmes written in high-level or assembly-level language Object codes are machine codes which have been converted to machine language by the compile
54
Compilers-A compiler is a computer programme which translates source codes to machine language. It does so, first, by converting the codes of the high-level language and storing it as object codes. Source Code------Compiler------Object Code
55
explain commonly used terms and concepts in programming;
Logic errors occur when the programmer makes mistakes in the sequence of the program statements such using the wrong formula or function. Syntax errors occur when a mistake is made in the programming language rules . For example if a keyword such as input or print is spelt incorrectly or an endif was left out. Run-time errors occur as the program compiles or runs. These errors are usually due to unexpected events such as division by zero or lack of memory for the computer to manipulate the data or a loop with no end. Example: for x = 1 to 3
56
Debugging is the process of finding errors in the source code (detection), understanding why they occurred (diagnosis) and correcting them. Testing-As you complete your program, you must ensure that it works for any correct input data that the user gives it. The testing phase is to detect errors or problems in the program. Test data: the values that are used to test or check the correctness of the program. The test data should include a wide range of sample data including extreme values and inputs that are not valid.
57
Executing the program If you have translated the program to its object code without errors, you can now execute the program and see the results. The final two terms commonly used with program execution are: Program loading: Copying of a programme from the hard disk of the computer to memory so it can be used. Linking: Combining various parts of a programme to produce a single executable file.
58
Declare variables It is important to declare our variables when writing out programmes because they occupy space in memory that we can use to assign values and the compiler needs to know, in advance, the type of data that will be stored in it. These types include: Integer - stores whole numbers Real - stores fractional numbers in the decimal format Character - stores a single character such as a letter String - stores a collection of characters
59
Declare constants;
60
The assignment statement
The assignment statement is used to store a value in a variable after the operation (i.e. +,-,*, or /) has been performed. VARIABLE = Expression (i.e. what is to be calculated) Examples of assignment statements are: 1. NUM1 = 5 (i.e. Store the value 5 in the variable NUM1) 2. SUM = NUM (i.e. Add 50 to the value stored in NUM1, then store the total in the variable name sum) 3. Product = NUM1*SUM(i.e. Multiply the content of NUM1 by the content of SUM)
61
The input statement The input statement is used to fetch data from some external source and store the data in a variable. The data stored in the variable can then be manipulated by the pseudocode. Examples of input statement used by pseudocode developers are: Read Input Fetch Get
62
Pseudocode example one
Write a pseudocode to read two numbers into variable A and B. Solution Read A Read B
63
Pseudocode example two
Write a pseudocode to read the name and score for three persons. For this question, we need to store six pieces of data, three names and three test grades, respectively. Hence, six variables are needed. Our variable will be called: NAME1, NAME2, NAME3, GRADE1, GRADE2 and GRADE3.
64
Pascal Write('Macintosh '); Write('Computer.'); Write('Hello');
Writeln (pronounced as "write-line") statement displays the data on screen and then moves the cursor to the next new line. while Write statement does not. examples of Writeln Write Writeln('a'); Writeln('Hello'); Writeln('How are you ?'); Writeln; Writeln('a', 'b', 'c'); Write('Macintosh '); Write('Computer.'); Write('Hello');
65
Read/Readln Readln statement will cause the computer to advance (move) the cursor to the beginning of the next line after execution while read statement will not. Example of Readln Read Readln(a,b); Readln(c,d); Readln(e,f); Read;
66
ARRAY An Array is a powerful data structure that stores variable data having the same data type.
67
DECLARE an Array Var myArray : Array[1..20] of Integer;
<arrayName> : Array[n..m] of <Data Type>;
68
Assigning values to array?
To assign values to a particular integer of an array, we do it like this: myArray[5] := 10; myArray[1] := 25; <arrayName>[index] := <relevant data>
69
Reading array Reading a value from an array is done as follows: Var
myVar : Integer; myArray : Array[1..5] of Integer; Begin myArray[2] := 25; myVar := myArray[2]; End.
70
Just like ordinary variables, arrays should be initialised, otherwise scrap data will remain stored in them. If we want to intialise 2 whole 20-sized integer and boolean arrays to 0 and false respectively, we do it like this: Var i : Integer; myIntArray : Array[1..20] of Integer; myBoolArray : Array[1..20] of Boolean; Begin For i := 1 to 20 do myIntArray[i] := 0; myBoolArray[i] := false; End; End.
71
Introducing User-Defined Data Types
Built-in data types are the ones we used lately, such as Integer, Boolean and String. Now we will learn how to specify our own customised data types and this is just how it is done: Type <myDataType> = <particularDataType>;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.