1 / 71

Programming

Programming. Section 3. 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,

joann
Télécharger la présentation

Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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. 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. 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. 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. write vat stop start read price vat  price *.15 Draw flowcharts for the following programs: • Program to accept the price of an item and calculate its VAT at 15%.

  13. start read us ec  us *2.71 write ec stop Example • Program to accept money in US dollars and convert it to its equivalent local currency.

  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

  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)

  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 <--- 0Counter <---- 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.

  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. Start Set number = 1 Set total = 0 No number <= 100 Yes Display total total = total + number End number = number + 1 While Loop

  29. Use of relational operators: The following relational operators are used:

  30. example

  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. 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. 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) • 2.  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) 120 22

  36. Arithmetic Operations

  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. 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 0 -4 Z= 14,8,2,-4 The algorithm prints -4

  39. test algorithms for correctness; 6 3*2 2+1 1-1 0 3 -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 problem2. 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 scores2. Sub-problem 2: find_the_highest_score3. Sub-problem 3: find_the_lowest_score4. 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 differegenerations 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 100111000 01100110 • 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.

More Related