350 likes | 1.11k Views
Programming Concepts. [Please switch off your phone]. Programming Languages. Earliest form of computer language In 1822, Charles Babbage designed a difference engine . The engine could be made to complete tasks only by changing the gears that executed the calculations.
E N D
Programming Concepts [Please switch off your phone]
Programming Languages • Earliest form of computer language • In 1822, Charles Babbage designed a difference engine. • The engine could be made to complete tasks only by changing the gears that executed the calculations. • This earliest form of computer language is based on physical motion. • The engine requires a series of instructions to perform a specific task. • This is known as a programming language. Demonstration for the Difference Engine I Created by Charles Babbage's son, Henry Babbage [Source: http://www.virtualtravelog.net/projects/ComputerHistory/index.html]
Programming Languages • Overview • Computer programs are written in programming languages. • If a program contains even a very small error, the computer cannot understand it. • A programming language is an artificial language based on a set of grammar rules. • We use a programming language to convert an algorithm into a computer program to enable the computer to solve the problem. • There are hundreds of programming languages: • - some are general-purpose • - some are specific-purpose, such as business programs or scientific programs (eg. APL) • - see more here: http://www-users.cs.york.ac.uk/~susan/cyc/p/prog.htm • Very often, more than one programming language may be suitable for a task.
Programming Languages Examples of program codes in C and Pascal
Programming Languages • Generations of Programming Languages • The development of programming languages is classified in "generation". • 1GL – machine language • 2GL – assembly language • 3GL – procedural language • 4GL – declarative language • First-generation language (1GL) • Machine language: a string of 0s and 1s. • Example, add EAX and EBX registers and store the result back to EAX: 03 C3 • Instructions in machine languages are numbers stored as bytes. • Can be understood by a computer at once. • But it is hard to read and understand by us. Difficult to learn. • Each type of computers understands its own machine language only: machine-dependent. • Therefore, the programs are not portable.
Programming Languages • Second-generation language (2GL) • Assembly language. • Stored as text. • Example: to add EAX and EBX registers and store the result back to EAX: add EAX, EBX • Each assembly instruction represents exactly one machine instruction. • Assembler is needed to convert assembly language programs into machine code so that they can be executed. • Each type of computers understands its own assembly language only. ie. also machine-dependent. • We may have to learn a new assembly language when we use another type of computer.
Programming Languages • Third-generation language (3GL) • Also called Procedural language: solves a problem by executing a sequence of steps (ie. how). • Examples: Java, C, Pascal • Fourth-generation language (4GL) • Also called declarative language: specifies what needs to be done without going into the details. • Often used to access databases. • Example: Structured Query Language (SQL) • SELECT * FROM RECORDS WHERE NAME = "CHAN" Question: Which generation does JavaScript belongs to?
Programming Languages • Low-level and High-level Programming Languages • Programming languages can also be classified as high-level and low-level. • Low-level programming languages: Machine language and Assembly language • High-level programming languages: 3GL and 4GL • Instructions are English-like. • A single instruction can be written to define many operations at the machine level. • Converted to machine languages before they can be executed. • Machine-independent. • Example: the same C program can be compiled to run in • (1) Personal computer running windows XP – using the compilers provided by some programming software like the Borland C and Microsoft Visual Studio etc.. • as well as • (2) Unix machine – using the Unix C compilers (eg. gcc, cc)
Programming Languages Microsoft Visual Studio Borland C
Programming Languages Microsoft Visual Basic
circle.c, square.c, etc. circle.obj, square.obj, etc. shape.exe Programming Languages • 3 types of translators: Assembler, Compiler, and Interpreter • Computers can only read their machine languages, so translators are required to convert programs into machine codes. • Assembler: • A special program that reads a text file with assembly instructions and converts them into machine codes. • Compiler: • A special program that converts the statements written in a high-level programming language and turns them into machine codes. • Typically, we type program code using an editor (eg. Microsoft Visual Studio). • The editor often has an Integrated Development Environment (IDE), which contains a compiler. • The file written by the programmer is called the source program. • A program may be composed of several source programs, eg. each stores some functions. • Each source program is compiledto form an object file (containing the machine codes). • The object files are then linked to form the final executable file. • The whole process is called building (including compilation and linking).
Programming Languages • Interpreter • A special program that translates and executes each source statement at run-time, before translating and executing the next statement. • Example: the web page browsers. • A program that relies on an interpreter to translate and run is called a script. The language is called scripting language. • Advantage of using interpreters (eg. for html / javascript) • After typing the source code, we can run the program at once. • Do not need to compile the whole source code into an executable file first. • If the language is recognized by webpage browsers, then it is very portable. • Advantage of using compilers (eg. for c, c++, java) • No source program is required during the execution of the program. • (We need not pass the source code to the user) • The program needs to be translated once only. Then it can be executed again and again. • Execution time is shorter (no translation is needed during run-time). • Syntax errors (eg. typing mistakes) are checked already during compilation. Less run-time mistakes will be made.
Problem Solving Concepts • Basic concepts on problem solving by programming • If a complicated task is to be handled by programming, we need a systematic way of problem solving. • Example: update all student records and print their reports • a lot of data • a lot of calculations • a lot of results to check • easy to get lost or miss out some jobs • Step by step of development of a program: • Keep track of what we have done • Keep track of what we are doing • To know what we still have to do • In addition, we need to pay attention to debugging and maintaining a program. • The one who debugs and maintains the program may not be the one who develops it. • Therefore, a program developed in a systematic way can help to make debugging maintenance easy afterwards.
Problem Identification Problem Analysis Algorithm Design Program Development Debugging and Testing Documentation Problem Solving Concepts Problem Solving Procedures: Identify what the problem actually is. Break down the problem into subproblems. Design the step-by-step procedures of solving a problem. Implement the algorithm as a computer program. Find out and remove all possible errors in the solution. Prepare documents that describe the solution.
Problem Solving Procedures • PROBLEM IDENTIFICATION • To clarify and define the problem so that we know exactly what should be done. Example: Check whether a student passes a subject, based on the rule: The final mark (exam + test, weighed 70% and 30%) should be at least 40. What is the problem? What do we need to solve? What should the program provide? Does any constraint affect the solution of the problem?
Problem Solving Procedures • 2. PROBLEM ANALYSIS • For a complicated problem, it is difficult to solve as a whole. • Therefore we need to analyze the problem and break it down into smaller parts. • Basically to find out the inputs, outputs, and processing of the problem. • Stepwise refinement is a common problem analysis method of breaking down a problem level-by-level. • Example: • First level refinement: • 1. Get scores • 2. Check whether the student obtains a pass or a fail • 3. Output result • Second level refinement: • 1. Get scores • 1.1 Get test score • 1.2 Get examination score • 2. Check whether the student obtains a pass or a fail • 2.1 Calculate the final score • 2.2 Check if the final score is sufficient for a pass or not • 3. Output result • The problem is divided to more easily handled sub-problems, • Each sub-problem can be developed and tested one at a time, or even by different people at the same time.
Pass or Fail level 0 1 Get Scores 2 Check Pass/Fail 3 Output Result level 1 refinement 1.1 Get Test Score 1.2 Get Exam Score 2.1 Calculate Final Score 2.2 Check Final Score Status level 2 refinement Problem Solving Procedures The refinements can also be shown with a structure diagram:
Problem Solving Procedures • 3. ALGORITHM DESIGN • An algorithm is a set of step-by-step procedures which solves a specific problem. • We can also apply stepwise refinement to design an algorithm. • Example: Previous 2.2 Check Final Score Status can be refined as the steps below: • if FinalScore >= 40 • Set Status to Pass • else • Set Status to Fail • The above English-like statements are called Pseudocode, that can be translated to program statements in next stage. • The complete pseudocode of the algorithm: • Input TestScore • Input ExamScore • FinalScore = TestScore x 0.3 + ExamScore x 0.7 • If Finalscore >= 40 • Set Status to Pass • else • Set Status to Fail • Output Status Exercise: Design an algorithm that generates 100 random numbers (0-99999) and outputs 5 largest values among them.
Beginning / End of Algorithm Process / Assignment Selection Input / Output Flow Status = "Pass" Status = "Fail" Problem Solving Procedures • Flowchart • A graphical representation of an algorithm (c.f. pseudocode that's verbal in nature) Flowchart Symbols Explanation Example Start InputTestScore InputExamScore FinalScore = TestScore x 0.3 + ExamScore x 0.7 FinalScore >=40 True False • There must be : • one single Beginning point and • one single End point OutputStatus End
Problem Solving Procedures Flowchart Exercise 1: The following flowchart contains a loop. Study it and explain what it does. Start input n i = 1 False i<=n True End Outputi*i i = i+1
Start input n i = 1 False i<=n True End Outputi*i i = i+1 Problem Solving Procedures • Flowchart Exercise 2: • Revise the previous flowchart so that it checks whether the user inputs a valid value (1-100), • and repeat the input until it is valid.
Problem Solving Concepts • 4. PROGRAM DEVELOPMENT • After designing the algorithm, we realize the algorithm by practical means – programming. • In program development, lower level refinements (pseudo-codes, detailed structure diagrams, flowcharts) may be changed or added along. • Top down approach: • Develop the main code and major functions first. • These code may contain statements that call lower-level functions that do not exist yet. • The lower-level functions may be developed later. • At the moment of developing each function, the requirements are already very clear. • eg. what to pass as parameters and what to return, • what processing is needed (eg. need to check the input number is negative or not). • Bottom-up approach: • Develop the lower-level functions first so that they are available already when the higher-level functions are written and need to call the lower-level ones. • Bottom-up approach is often used when the detailed requirements of each function are obtained with confidence in the design stage. Eg. Week 10 Lect Ex (Q2) (1) Finish the onclick handler (2) Finish showPrimeNumbers(start,end) (3) Finish isPrime(n) Eg. makeDotHtml => makeLineHtml => makeHouseHtml
Problem Solving Concepts • 5. DEBUGGING AND TESTING • Debugging means detecting, tracing, and correcting errors (bugs) in a program. • There are 3 types of programming errors: • Syntax error: An error occurs when an instruction that does not follow the syntax rules of the programming language. • Example: wrong spelling of keywords, eg. if If • Easy to identify -- the computer just refuses to run the statement and gives out message about the program statement. • Run-time error: An error occurs only when a program statement is running. • Example: The statement attempts to use a property of an html element that doesn't exist. • var id="applle"; • … • document.getElementById(id).innerHTML • The statement causing the run-time error may not be the source of error. • Logic error: An error is caused by the logic design of the program. • Example: Q1 of week 10 lecture exercise (The wrong isPrime function)
Problem Solving Concepts • Testing is the process of showing the presence of errors, not their absence. • "even a program has passed many test cases, nobody can conclude that there is no error". • White-box testing • Test all cases such that every program statement is tested. • The term white box indicates that testing is done with a knowledge of the code used to execute certain functionality. For this reason, a programmer is usually required to perform white box tests. • Black-box testing • The tester test runs the program according to the available features visible to him (or told in the user manual) • The code of the program is not examined by the tester. For this reason black box testing is not normally carried out by the programmer.
Problem Solving Concepts • Notes on Debugging • - Debugging time probably more than writing first version of your program • - Solve errors: NOT by trial-and-error • Should be based on clear understanding of what the code is supposed to do!! • - Look into why the program runs incorrectly for some unsuccessful test cases. But not to look into why it works for some successful cases. • - Focus on the simplest unsuccessful test case first. • You should learn from each chance of debugging: • Should have clear idea of why it was wrong and the correct approach to fix it. Then your programming skill will be improved significantly.
Problem Solving Concepts • 6. DOCUMENTATION • Program documentation consists of: • - A user's guide • - A hard copy of a sample test run of the program • - A source program listing • - A concise requirement specification • - Descriptions of problem inputs, expected outputs, formula, special conditions, processing steps • - Structure diagram / step-wise refinement results • - Pseudocodes or flowcharts • Documentation of a program is important. Because: • - We are likely to use the program again sometime in the future. • - We should provide documentation to the client as he or she will need information about it. • - Other programmers may be assigned to maintain the program or make additions to it. • - We may eventually discover some errors and need to correct them.
Summary • Introduction to programming languages • 1GL to 4GL • 3 types of translators: Assembler, Compiler, and Interpreter • Problem Solving Procedures