CPS120 Introduction to Computer Science Programming & Debugging Lecture 6.

Slides:



Advertisements
Similar presentations
How Are Algorithms Developed?
Advertisements

Programming Types of Testing.
CHAPTER 1: AN OVERVIEW OF COMPUTERS AND LOGIC. Objectives 2  Understand computer components and operations  Describe the steps involved in the programming.
Flow Control if, while, do-while Juan Marquez (03_flow_control.ppt)
Introduction to Programming
زبانهای برنامه سازی برنامه سازی پیشرفته ارائه دهنده دکتر سيد امين حسيني E.mail: Home page:
Computer Programming Rattapoom Waranusast Department of Electrical and Computer Engineering Faculty of Engineering, Naresuan University.
Introduction to C Programming
ITEC113 Algorithms and Programming Techniques
Program Design and Development
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Programming Logic and Design, Introductory, Fourth Edition1 Understanding Computer Components and Operations (continued) A program must be free of syntax.
Chapter 1 Program Design
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
Introduction to C Programming
Chapter 3 Planning Your Solution
The Program Design Phases
PRE-PROGRAMMING PHASE
Debugging Logic Errors CPS120 Introduction to Computer Science Lecture 6.
Fundamentals of Python: From First Programs Through Data Structures
Programming Languages CPS120: Introduction to Computer Science Lecture 5.
Fundamentals of Python: First Programs
CPS 120: Introduction to Computer Science
Simple Program Design Third Edition A Step-by-Step Approach
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Chapter 2 - Algorithms and Design
PROGRAMMING LANGUAGES Prof. Lani Cantonjos. PROGRAM - set of step-by-step instructions that tells or directs the computer what to do. PROGRAMMING LANGUAGE.
Computer Programming TCP1224 Chapter 3 Completing the Problem-Solving Process and Getting Started with C++
CPS120: Introduction to Computer Science Compiling Your Programs Using Visual C++
Input, Output, and Processing
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
© 2011 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Stewart Venit ~ Elizabeth Drake Developing a Program.
Problem Solving Techniques. Compiler n Is a computer program whose purpose is to take a description of a desired program coded in a programming language.
CPS120: Introduction to Computer Science Decision Making in Programs.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
CPS120: Introduction to Computer Science Compiling Your First Program.
Pseudocode Simple Program Design Third Edition A Step-by-Step Approach 2.
Algorithms & Flowchart
Control Structures CPS120: Introduction to Computer Science Lecture 5.
The Software Development Process
How Are Computers Programmed? CPS120: Introduction to Computer Science Lecture 5.
Debugging Logic Errors CPS120 Introduction to Computer Science.
CPS120: Introduction to Computer Science Introduction to C++
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
CPS120: Introduction to Computer Science Compiling Your First Program.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
How Are Computers Programmed? CPS120: Introduction to Computer Science Lecture 5.
Algorithms and Pseudocode
The Debugging Process Syntax Errors CPS120 Introduction to Computer Science Lecture 4.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
CPS120 Introduction to Computer Science Exam Review.
CPS120: Introduction to Computer Science Session 5.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
CHAPTER 3 COMPLETING THE PROBLEM- SOLVING PROCESS AND GETTING STARTED WITH C++ An Introduction to Programming with C++ Fifth Edition.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Programming Logic and Design Seventh Edition Chapter 1 An Overview of Computers and Programming.
Algorithms and Flowcharts
CSC201: Computer Programming
The Selection Structure
Lecture 2 Introduction to Programming
Introduction To Flowcharting
Designing and Debugging Batch and Interactive COBOL Programs
Unit# 9: Computer Program Development
Introduction to C++ Programming
T. Jumana Abu Shmais – AOU - Riyadh
How Are Algorithms Developed?
An Introduction to Debugging
CHAPTER 6 Testing and Debugging.
Programming Logic and Design Eighth Edition
Presentation transcript:

CPS120 Introduction to Computer Science Programming & Debugging Lecture 6

Introduction to Programming

The Program Development Cycle

What Can a Program Do?  A program can only instruct a computer to: –Read Input –Sequence –Calculate –Store data –Compare and branch –Iterate or Loop –Write Output

Fundamental Programming Concepts  Assignment of values to a variable  Iteration (Looping) –Over a set of set of statements –With respect to a logical expressions (conditions)  Delegation of sub-tasks to functions / procedures

The Structure Theorem The Structure Theorem states that any algorithm can be built from three basic control structures.  One-after-another (Sequence)  Decision-making (Selection) –Making choices between 2 or more alternatives  Repetition (Iteration) –Concerned with repetitive tasks (and the termination conditions of loops)

Program Design  Input Data Format  Output Data Format  Procedural Logic  Control Structure

Introduction to C++

C++ Usages & Conventions  C++ is absolutely case sensitive –For Instance: A is 97 in ASCII and a is 65 –Remember: in ASCII {, [, and ( are not equivalent  No keywords in ANSI standard are even partially uppercase –‘While’ is not a keyword, ‘while’ is –Be careful if you define new keywords  The most common practice in C+++ is to use small letters of the first part of a variable name and capitals for the rest of it

Characteristics of a C++ Program  Comments  Compiler Directives  Functions  Braces  Statements

A Simple C++ Program Comments //Simple C++ Program // // Purpose: To demonstrate the // parts of a simple C++ program Compiler Directive #include Main Functionmain ( ) Braces{ Statementscout << "This is a simple program "; return 0; }

Comments  Document what is happening, why it is happening and other issues  Commentary is ignored by the compiler  C++ has inline, block and documentary comments –Inline comments are within line of code Use the // symbols –Block comments are long comments delimited with /* and */

Compiler Directives  Instructions to the compiler rather than part of the C++ language –Most common directive is #include For Example: #include –A.h file is a header file. It serves as a link between program code and standard C++ code needed to make programs run

Functions  A function is a block of code that carries out a specific task  Every C++ program has a main function that executes when a program initiates –Includes open parenthesis to designate a function –Ends with a return 0; statement

Scope Delimiters  A symbol or pair of symbols used to define a region or area which is considered a locale  In programming, many structures need to have their scope defined because they should not affect the entire program –In C++, the symbols ‘{‘ and ‘}’ are used

Semicolons  There must be a semicolon after every statement –To tell the compiler that the statement is complete –Function definitions and compiler directives are exempt

Columns and White Space  Modern programming languages are free form with delimiters instead of columns to determine the end of instructions –The ; (semi-colon) is the delimiter used in C++  Use tabs, indents, and blank lines in any manner that makes code easier to understand  Many programming instructions become subordinate to other instructions due to scope and other restrictions. Formatting code to reflect this makes it easier to read

Uppercase or Lowercase  Be careful to use the same combination of uppercase or lowercase lettering when you enter source code  Commands and other reserved words are all lower case

Variables  Variables or identifiers are used to hold information –Usually mixed case with the first letters small and the rest starting with a capital –e.g. theWeight

Literals  Literals are system commands and other pieces of information that the compiler doesn’t understand, and therefore, takes your word for them  In C++, literals are enclosed in straight double quotes " " which is the shift of the apostrophe

C++ Control Structures 1. "Sequence statements" are imperatives 2. "Selection" is the "if then else" statement –AND, OR, NOT and parentheses ( ) can be used for compound conditions 3. "Iteration" is satisfied by a number of statements –"while" –" do " – "for" 4. The case-type statement is satisfied by the "switch" statement. –CASE statements are used for most non-trivial selection decisions

Program Design

Input Data Format Output Data Format Procedural Logic Control Structure INPUTINPUT OUTPUTOUTPUT Flowcharts Pseudocode Algorithms

Program Design - Input  Record Layout Table Field NamePositionLengthData Type EmpName1-2020String EmpID21-255String EmpAddr String BirthDate String

Program Design- Output  Report Sample Employee NameIDBirth Day Robert WilliamsA468704/08/1976 J356702/01/1983 K246707/04/1978 L890903/06/1966 Ronald Wilson Larry Jackson Mary Roosevelt

What is an Algorithm?  An algorithm is merely the sequence of steps taken to solve a problem –Two parts Actions to be executed Order in which those actions are to be done –Computational steps that transform the input data into useful output data.  Algorithms are not programs –They need to be coded in a programming language like C++

Pseudocode & Flowcharts are Important  Pseudocode – –Make a detailed description of your algorithm’s logic before worrying about C++ syntax and data layout. –An algorithm you develop using pseudocode should be capable of implementation in any procedural programming language Pseudocode is generally independent of the implementation language  Flowcharts – –A graphical layout of the algorithm is often very useful in spotting “illogical” logic!

Reasons Programmers Draw Flowcharts  Drawing a flowchart gives the programmer a good visual reference of what the program will do  Flowcharts serve as program documentation  Flowcharts allow a programmer to test alternative solution to a problem before coding  Flowcharts provide a method for easy desk checking

Terminator. Shows the starting and ending points of the program. A terminator has flow lines in only one direction, either in (a stop node) or out (a start node). Data Input or Output. Allows the user to input data and results to be displayed. Processing. Indicates an operation performed by the computer, such as a variable assignment or mathematical operation. With a heading – an internal subroutine Decision. The diamond indicates a decision structure. A diamond always has two flow lines out. One flow lineout is labeled the “yes” branch and the other is labeled the “no” branch. Predefined Process. One statement denotes a group of previously defined statements. Such as a function or a subroutine created externally Connector. Connectors avoid crossing flow lines, making the flowchart easier to read. Connectors indicate where flow lines are connected. Connectors come in pairs, one with a flow line in and the other with a flow line out. Off-page connector. Even fairly small programs can have flowcharts that extend several pages. The off-page connector indicates the continuation of the flowchart on another page. Just like connectors, off-page connectors come in pairs. Flow line. Flow lines connect the flowchart symbols and show the sequence of operations during the program execution. Common Flowchart Symbols

Rules for Drawing Flowcharts  Top to bottom and left to right –Draw the flowchart the way you like to read –Use arrowheads on flow lines whenever the flow is not top to bottom, left to right  Be neat ! Use graphics software  Avoid intersecting lines

Start Sum =0 Count =0 Input data Sum = Sum+data Count = Count+1 Count =3? NOYES A A Avg = Sum/Count Output Avg End Flowcharting Example

Program Design: Flowcharts Problem: Compute a Centigrade temperature from a Fahrenheit temperature, which has been entered through the keyboard. The Centigrade value is then output. A centigrade temperature is computed as 5/9 * (Fahrenheit temp -32). Start Get fC=5/9*(f-32)Output c End

Disadvantages to Flowcharts  Time consuming  A program flowchart shows how the input becomes output, but it does not show why a particular step is done  Flowcharts are subjective

Pseudocode  This device is not visual but is considered a “first draft” of the actual program.  Pseudocode is written in the programmer’s native language and concentrates on the logic in a program—not the syntax of a programming language.

General Rules for Pseudocode  There is no standard pseudocode  The rules of Pseudocode are generally straightforward –Should be easily read and understood by non- programmers –All statements showing "dependency" are to be indented. These include while, do, for, if, switch

Using Pseudocode Problem Solving Example: Write a program that allows the user to calculate the area of a rectangle as many times as they want. A) Input: length, width, continue/quit B) Restrictions: inputs must be positive C) Output: area D) Formula: area = length * width Pseudocode for algorithm (there are many different ways to write pseudocode, two are shown): Pseudocode Example 1Pseudocode Example 2 1. Ask user to input length1. Repeat until the user wants to stop 2. Read in length2. Repeat until the length is positive 3. If length is not positive, return to step 13. Ask user to input length 4. Ask user to input width4. Read in length 5. Read in width5. Repeat until the width is positive 6. If width is not positive, return to step 46. Ask user to input width 7. Calculate area 7. Read in width 8. Output area 8. Calculate area 9. Ask user if they want to do it again9. Output area 10. Read in answer10. Ask user it they want to do it again 11. If the answer is to continue, return to step 111. Read in user's response

Pseudocode Statement Rules –Statements are written in a simple English-like language –Each instruction is started on a separate line –Logic-showing keywords are written in UPPER CASE or typed in BOLD UPPERCASE (e.g. IF, THEN, FOR, DO etc.) These are the only uppercase words in this form of pseudocode. –Indentation is used to show structure –Instructions are written from top to bottom, with only one entry point and one exit point –Logically related groups of instructions can be formed into modules and given a name

Rules for Pseudocode 1. Make the pseudocode language-independent 2. Indent lines for readability 3. Make key words stick out by showing them capitalized, in a different color or a different font 4. Punctuation is optional 5. End every IF with ENDIF 6. Begin loop with LOOP and end with ENDLOOP 7. Show MAINLINE first; all others follow 8. TERMINAE all routines with an END instruction

Compiling and Debugging

Compilation Process 1. Get the set of instructions from you 2. Review the instructions to see if they violate the rules (syntax) of the language 3. If all the rules are obeyed, create a working file in the language of the computer (machine language) 4. Attach to the working file full instructions for any shortcuts you may have used (linkage) 5. Assemble a final file in machine language

Compiling Source Code Compiler Object Code Linker Additional Code Executable Code

Compiling and Debugging  Executable code will not be created until you correct all of the syntax errors in your source code  Then the fun (with logic errors) begins

Syntax & Logic Errors  A syntax error is simply the violation of the rules of a language; misuse of structure and form in programming or a violation of the compiler’s rules. These errors are detected by the compiler –Also know as 'fatal compilation errors'  A logic error is a mistake that complies with the rules of the compiler that causes the program to generate incorrect output

Error Prevention & Testing  Use good design and programming style –Don't use global variables  Study your code before typing and running it –Have someone else look at it  Make your program self-documented  Program defensively – put in assertions and self-checking code and comment them out  Test your code at boundary values for variables  Log your bugs  Test code in pieces using "stubs"  Consider – correctness, reliability, utility and performance

Semantic Error Detection  Use the tracing method to display the value of critical variables  Make the error reproducible  Get a stack trace of function calls to verify sequencing  Correct the error immediately when you find it and check if you made it somewhere else  Examine your last code changes for errors  Ensure that you have saved and run the corrected programs

Debugging  Debugging is the process of locating and fixing or bypassing bugs (errors) in computer program code or the engineering of a hardware device.bugs  To debug a program is to start with a problem, isolate the source of the problem, and then fix it.

Debugging Steps 1. Proofread before compiling 2. Compile 3. Correct all the obvious errors Start at the beginning of the list of errors and warnings A single syntax error may cause the compiler to believe numerous other syntax errors are occurring Look at the error lines and if you see the error, fix it. Otherwise, leave it for later. It may vanish when you fix something else Don’t worry if more errors appear. Some errors mask other errors 4. Recompile when you have fixed what you recognize

Debugging Steps 5. Repeat 3 & 4 until no further errors are obvious 6. Attempt to solve the remaining errors in a top-down fashion 7. Solve whatever errors you can without spending long periods of time on any given error 8. Recompile whenever you feel you don’t see any further solutions

A Debugging Mindset  Assume your syntax is wrong. Look it up! Add working comments as you change things  If you are 100% sure a line is correct, then search for a syntax error in the lines ABOVE that line –Start with the immediately previous line and work backward  Never make a change you can’t explain

Debugging Checklist 1. Visually verify the spelling and case of keywords and identifiers -- Remember, in the editor, keywords are blue, literals are black and comments are green -- Look for problems with l and 1 and o and 0 2. Verify syntax with a reference book, not just visually -- Don’t trust your eyes; you see what is supposed to be there 3. Try to find an example in the reference book that does something similar and compare the code 4. Verify that the necessary delimiters used for that line are there -- Check the lines above and below as well

Debugging Checklist 5. Without looking at your source code or notes, rewrite the instruction on a piece of paper and then compare it to your actual code; don’t cheat 6. Verify that the line is really the source of the error by commenting the line using // a)Don’t worry about other errors that result from this b)If the error disappears, it probably results from the line you are working on c)If it moves to the next line it is probably caused earlier in the code d)Remember that the compiler cannot be trusted to pinpoint lines

Warnings  Even though an executable has been generated, you may not be done with syntax errors  Compilers generate syntax warning messages which are not fatal errors but represent special error checking functions for certain common programming errors

Linker Errors  Not all syntax errors are detectable by the compiler –These errors do not become apparent until files are put together to create an executable –These errors are not linked to a specific line of code Look for the name of the variable and see what lines of code it occurs on using EDIT and FIND –LNIK2001: unresolved external –LNK1120: unresolved externals

Logic/Semantic Errors  If the data is good and a program does not do what it is supposed to do, there must be at least one logic error present –The syntax rules of C++ have been correctly followed, but the meaning of the code is incorrect

Semantic Errors  A semantic error is a violation of the rules of meaning of a programming language –E.g. My refrigerator just drove a car to Chicago –Overt logic errors Something is obviously wrong even though the program is running –Covert logic errors Not so obvious something is wrong Run things various ways to highlight these errors

Approaches to Correction  Desk-checking  Inserting Tracing Statements –Used when program "crashes" –Runs to completion with incorrect output  Using an interactive debugger

Common Semantic Errors 1. Infinite Loop –Created when a loop in which the expression tested never becomes false 2. Misunderstanding operator precedence 3. Dangling else 4. Off-By-One Error –Loop that iterates one fewer or one more than is correct 5. Code inside a loop that doesn’t belong there 6. Not using a compound statement when one is required 7. Array index bounds error

Color Coding in Visual C++ Editor  Comments are green and are ignored by the compiler  All ANSI keywords are coded in blue  Other code is in plain black –Compiler keywords like cin and cout are also shown in black

C2065: Undeclared Identifier 1.Several things may produce this error Misspelling a keyword Misspelling a programmer defined name (identifier) Misuse of case in a keyword or identifier Failure to declare an identifier