III. Check if the divisors add up to the number. Now we may consider each of these tasks separately, assuming the others will be taken care of

Similar documents
Top Down Design. 2. Design Methodology

Chapter 2. C++ Syntax and Semantics, and the Program Development Process. Dale/Weems 1

Chapter 2. C++ Syntax and Semantics, and the Program Development Process. Dale/Weems 1

Programming II (CS300)

Outline. Program development cycle. Algorithms development and representation. Examples.

C++ Programming Language Lecture 2 Problem Analysis and Solution Representation

Foundations, Reasoning About Algorithms, and Design By Contract CMPSC 122

Programming Logic and Design Seventh Edition Chapter 2 Elements of High-Quality Programs

Lecture 3 Notes Arrays

15-122: Principles of Imperative Computation (Section G)

Chapter 9. Introduction to High-Level Language Programming. INVITATION TO Computer Science

Formal Methods. CITS5501 Software Testing and Quality Assurance

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

6. C++ Subprograms David Keil CS I slides 7/03 1

Cambridge Assessment International Education Cambridge International Advanced Subsidiary and Advanced Level. Published

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Algorithms 1 / 24. Algorithms Sequential Search

Chapter 3. Describing Syntax and Semantics

Lecture Notes on Arrays

Errors and Exceptions. EECS 230 Winter 2018

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM

Algorithms. Abdelghani Bellaachia, CSCI 1121 Page: 1

Arithmetic Expressions in C

Lecture Notes for Chapter 2: Getting Started

INTRODUCTION TO ALGORITHMS

CS112 Lecture: Working with Numbers

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Semantics. There is no single widely acceptable notation or formalism for describing semantics Operational Semantics

CSc 10200! Introduction to Computing. Lecture 1 Edgardo Molina Fall 2013 City College of New York

Algorithm: 1. Introduction

Have examined process Creating program Have developed program Written in C Source code

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

SNS COLLEGE OF ENGINEERING,

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Hardware versus software

COP 1220 Introduction to Programming in C++ Course Justification

Spark verification features

CS 370 The Pseudocode Programming Process D R. M I C H A E L J. R E A L E F A L L

Steps to program development

Assertions & Verification Example Exam Questions

Problem Solving with C++

Part II. Hoare Logic and Program Verification. Why specify programs? Specification and Verification. Code Verification. Why verify programs?

Shared Variables and Interference

Darshan Institute of Engineering & Technology for Diploma Studies

8 Algorithms 8.1. Foundations of Computer Science Cengage Learning

Outline and Reading. Analysis of Algorithms 1

An algorithm may be expressed in a number of ways:

Lecture Notes on Linear Search

Information Science 1

Analysis of Software Artifacts

Checking Program Properties with ESC/Java

Basic Verification Strategy

Information Science 1

CS 2604 Minor Project 1 DRAFT Fall 2000

TABLE OF CONTENTS 2 CHAPTER 1 3 CHAPTER 2 4 CHAPTER 3 5 CHAPTER 4. Algorithm Design & Problem Solving. Data Representation.

Assertions, pre/postconditions

Absolute C++ Walter Savitch

Overview of the Course. What is an Algorithm? .. Cal Poly CSC 349: Design and Analyis of Algorithms Alexander Dekhtyar..

Announcements. Written Assignment 2 due today at 5:00PM. Programming Project 2 due Friday at 11:59PM. Please contact us with questions!

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Assertions & Verification & Example Loop Invariants Example Exam Questions

Variable A variable is a value that can change during the execution of a program.

Halting Measures and Termination Arguments

Chapter 6 : Modularity Using Functions (pp )

Chapter 5. Algorithms Pearson Addison-Wesley. All rights reserved

Chapter 2 C++ Fundamentals

Lectures 20, 21: Axiomatic Semantics

Shared Variables and Interference

Assignment 2: Welcome to Java!

CSE 230 Computer Science II (Data Structure) Introduction

Chapter 1: Principles of Programming and Software Engineering

CS2104 Prog. Lang. Concepts

Algorithms. Chapter 8. Objectives After studying this chapter, students should be able to:

Lab 7 Macros, Modules, Data Access Pages and Internet Summary Macros: How to Create and Run Modules vs. Macros 1. Jumping to Internet

Axiomatic Specification. Al-Said, Apcar, Jerejian

Repetition Through Recursion

Computer Components. Software{ User Programs. Operating System. Hardware

Reasoning about programs

Difference Between Dates Case Study 2002 M. J. Clancy and M. C. Linn

Last time. Reasoning about programs. Coming up. Project Final Presentations. This Thursday, Nov 30: 4 th in-class exercise

1. Introduction to Programming

Testing! Prof. Leon Osterweil! CS 520/620! Spring 2013!

printf( Please enter another number: ); scanf( %d, &num2);

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Lecture Notes on Contracts

Scheme of work Cambridge International AS & A Level Computing (9691)

CIS 890: Safety Critical Systems

FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING UNIT III. 2 Marks PROBLEM SOLVING AND OFFICE AUTOMATION

SNS COLLEGE OF ENGINEERING

Language Fundamentals

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

It can be confusing when you type something like the expressions below and get an error message. a range variable definition a vector of sine values

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Chapter 4. Computation. Bjarne Stroustrup.

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning

Chapter 8 Algorithms 1

Transcription:

Top-Down Design 1 Top-Down Design: A solution method where the problem is broken down into smaller sub-problems, which in turn are broken down into smaller subproblems, continuing until each sub-problem can be solved in a few steps. (Also called: Divide and Conquer strategy) Problem: An integer N is "perfect" if N is equal to the sum of the positive integers K such that K < N and K is a divisor of N. Design an algorithm to determine if a given integer is "perfect". The top-level sub-problems (or tasks) appear to be: I. Get the number which is to be tested. II. Determine the divisors of the number. III. Check if the divisors add up to the number. Now we may consider each of these tasks separately, assuming the others will be taken care of Top-Down Analysis Example Continuing our analysis: I. Get the number which is to be tested. A. Output a prompt asking for the number. B. Input the number; call it N. C. Stop if N isn't positive. 2 II. III. Determine the divisors of the number. A. Set the divisor sum to 1. (Since 1 certainly divides N.) B. Check each integer, D, from 2... N/2 to see if D is a divisor of N. Check the results. A. If the divisor sum equals N Then i. N is perfect Else i. N is not perfect. Now we may consider what details need to be added to clarify the process enough to make it an algorithm.

Top-Down Analysis Example Continuing to add detail: I. Get the number which is to be tested. A. Output: "Please enter a positive integer: " B. Input the number; call it N. C. If N isn't positive i. Output: N " isn't perfect." ii. STOP. II. III. Determine the divisors of the number. A. Set the DivisorSum to 1. (Since 1 certainly divides N.) B. Set D to 2. C. While D is less than or equal to N / 2 i. If D is a divisor of N a. Add D to DivisorSum ii. Add 1 to D. Check the results. A. If DivisorSum equals N i. Output: N " is perfect." Else i. Output: N " isn't perfect." B. STOP. The outline format used here is a fairly simple way to express an algorithm design. It clarifies the ordering and grouping of actions, and doesn't require any special editing tools to create. 3 Why Practice Top-Down Design? 4 One of the most fundamental ideas in problem solving involves subdividing a problem into subproblems and solving each subproblem individually. Quite often, the attempt to solve a subproblem introduces new subproblems at a lower level. The subdivision of subproblems should continue until a subproblem can easily be solved. This is similar to the refining of an algorithm. In large projects, subproblems may be assigned to different programmers, or teams, who will be given precise guidelines about how that subproblem fits into the overall solution, but who will have relatively complete freedom in attacking the particular subproblem at hand. If there is a problem you can't solve, then there is an easier problem you can't solve: find it. G. Pólya

Representing Designs 5 Most common techniques: 1. Outlining (written decomposition) 2. Structure Chart (hierarchical tree diagram) 3. Pseudocode (mixture of English & programming constructs) Structure chart for the Perfect Number Algorithm: Perfect Number Algorithm Get the number N Determine the divisors of N Check the result Output a prompt Read N If N <= 1 Output N isn't perfect STOP Set Sum to 1 Set D to 2 While D <= N / 2 If D is a divisor of N Add D to Sum Add 1 to D If Sum equals N Output N is perfect else Output N isn't perfect Pseudocode Representation 6 Comment Get the value for N Output: Please enter a positive integer: Input: N If N <= 0 Then Output: N isn't a perfect number. STOP Endif Comment Initialize sum of the divisors & divison SumOfDivisors <-- 1 Candidate <-- 2 Comment Consider all possible divisors While Candidate <= N / 2 Do R <-- N - (Truncate ( N / Candidate ) )* Candidate If R = 0 Then SumOfDivisors <-- SumOfDivisors + Candidate Endif Candidate <-- Candidate + 1 Endwhile Comment Check the results If SumOfDivisors = N Then Output: N is a perfect number. Else Output: N isn't a perfect number. Endif Pseudocode is potentially clearer than either a structure chart or an outline. Unfortunately there is no universal pseudocode notation.

Proofs of Program Correctness 7 Program proof: Assertion: code analysis to achieve a formal verification of the correctness of a program's output. statement of a relationship between a program's variables and data. Every program statement can be preceded and succeeded by an assertion, (termed the precondition and postcondition respectively). Program proofs involve applying deductive logic to show that the precondition and postcondition assertions are true for all program statements Due to practical time considerations assertions are made and proven only for sequences of statements. Example: // Pre: N >= 0, M > 0 while (M > 0) M = M / N; // Post: N >= 0, M == 0 precondition postcondition Invariants loop invariants assertions that are true prior to loop execution and following each loop iteration. 8 Commonly composed of the boolean expression controlling the loop, its negation, ranges of loop variables, data structure states and file status. Derived by analyzing the setup and modifications of the loop variables. Example:... // Integer multiplication by repeated addition. // Calculates Multiplier * Multiplicand and stores result in // Product. // Pre: Multiplier >= 0, Multiplicand has been set Product = 0; Factor = Multiplier; // Invariants: Product == Multiplicand * (Multiplier - Factor) // Factor is in the range [0, Multiplier] while (Factor > 0) { Product = Product + Multiplicand; Factor = Factor - 1; } // Post: Product == Multiplier * Multiplicand // Factor == 0...

Program Documentation 9 The production of external program documentation prior to program implementation is a natural outgrowth of any good software development process. External documentation describes the purpose of a program and its data. External documentation may also describe the overall architecture of the program design. Internal documentation, in the form of in-line comments, as well as module documentation, is produced in conjunction with code development. The production of good documentation should be viewed as a necessary and useful part of the software development process, not merely as an afterthought to satisfy requirements. See the Elements of Programming Style in the appendices. Structure Chart 10 A structure chart is a documentation tool that enables the designer to keep track of the relationships among subproblems throughout this refinement process. The structure chart gives a detailed description of the original problem in terms of subproblems. This top-down description will make it easier to write a program to solve the original problem. We can solve each upper-level box in the structure chart by using a C++ function. A function is a grouping of statements into a single unit. This single unit can be invoked to solve its subproblem simply by activating it by means of a function call. Since the structure chart gives a pictorial mechanism for visualizing the solution to a problem and each of the pieces of the structure chart corresponds so a function, the solution to a problem is obtained by correctly invoking a series of functions. In order to solve problems, we need only solve all the subproblems by means of functions. Thus a C++ program is a collection of functions that solve a series of subproblems. This is the essence of top-down design.

Procedural Abstraction 11 The top-down approach to program design involves procedural abstraction. This enables us to associate meaningful names with more complicated algorithm steps, reference these steps by name, and defer their implementation details until later. Our programs are written using logically independent sections, similar to the manner in which we developed the solution algorithm (as logically independent steps). Using logically independent program sections enables the programmer to hide the details of subproblem implementations from one another. This concept, information hiding, is critical in all stages of the software development process. Categories of Programming Errors 12 Language syntax (compilation) errors: - Error is in the form of the statement: misspelled word, unmatched parenthesis, comma out of place, etc. - Error is detected by the compiler (at compile time). - Compiler cannot correct error, so no object file is generated. - Compiler prints error messages, but usually continues to compile. Linking errors: - Error is typically in the form of the declaration or implementation or call of a function. - Error may also result from including the wrong header file. - Error is detected by the linker (after the compiler has produced an object file). - Linker cannot correct error, so no executable file is generated. - Linker prints error messages, but usually continues link analysis.

Categories of Programming Errors 13 Execution (runtime) errors: - Error occurs while the program is running, causing the program to "crash" (terminate abnormally) and usually producing an error message from the operating system. - Error is frequently an illegal operation of some sort. The most common are arithmetic errors like an attempt to divide by zero, and access violations when the program tries to use some resource like a memory address that is not allocated to it. - Program source code compiles and links without errors no help there. - Unfortunately, some operating systems do not reliably detect and respond to some kinds of execution errors. In that case, an incorrect program may appear to function correctly on one computer but not on another. Logic errors: - Error occurs while the program is running, causing the production of incorrect results, but not necessarily a runtime "crash". - Program source code compiles and links without errors no help there. - Logic errors are detected by checking results computed by the program. - The cause(s) of the error must be determined by a logical analysis of the error and the source code. This must be done by the developer. This is the hardest type of error to deal with. The Program Development Process 14 Analyze the problem statement Design a solution Enter/edit source code Find error in source code check syntax Compile/link source code Compiler/Linker errors? no yes Find cause of runtime error check code check input data rethink analysis/design or Test the program Execution errors? no Results incorrect? yes yes no Find cause of logic error check code check input data rethink analysis/design Success! At least with this input. or