Chapter Two: Program Design Process and Logic

Similar documents
FLOW CHART AND PSEUDO CODE

SNS COLLEGE OF ENGINEERING

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

IDENTIFY WAYS OF REPRESENTING ALGORITHMS.

UNDERSTANDING PROBLEMS AND HOW TO SOLVE THEM BY USING COMPUTERS

CHAPTER 2 PROBLEM SOLVING TECHNIQUES. Mr Mohd Hatta Bin Hj Mohamed Ali Computer Programming BFC2042

PROBLEM SOLVING AND OFFICE AUTOMATION. A Program consists of a series of instruction that a computer processes to perform the required operation.

CS112 Lecture: Repetition Statements

CS 199 Computer Programming. Spring 2018 Lecture 2 Problem Solving

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

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

Final Examination Semester 2 / Year 2010

Fundamental of Programming (C)

Fundamentals of Programming

Computer Fundamentals: Pradeep K. Sinha & Priti Sinha

IT 1033: Fundamentals of Programming Loops

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

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

PROBLEM SOLVING AND PYTHON PROGRAMMING

CSC 121 Spring 2017 Howard Rosenthal

Stepwise Refinement. Lecture 12 COP 3014 Spring February 2, 2017

ALGORITHMS AND FLOWCHARTS

CS111: PROGRAMMING LANGUAGE1. Lecture 2: Algorithmic Problem Solving

Pseudocode. ARITHMETIC OPERATORS: In pseudocode arithmetic operators are used to perform arithmetic operations. These operators are listed below:

Introduction to Flowcharting

Chapter 3 Structured Program Development in C Part II

Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today.

5. Selection: If and Switch Controls

Looping Subtasks. We will examine some basic algorithms that use the while and if constructs. These subtasks include

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

LOOPS. Repetition using the while statement

Fundamentals of Programming. Lecture 6: Structured Development (part one)

Algorithm Discovery and Design. Why are Algorithms Important? Representing Algorithms. Chapter 2 Topics: What language to use?

SNS COLLEGE OF ENGINEERING,

OBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 1

Chapter 1 INTRODUCTION TO COMPUTER AND PROGRAMMING

Chapter 1: An Overview of Computers and Logic

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Unit 1 Lesson 4. Introduction to Control Statements

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Class 8 ALGORITHMS AND FLOWCHARTS. The City School

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Chapter 3 Structured Program Development

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Repetition Algorithms

International Diploma in Computer Studies

Course Outline. Introduction to java

TABLE OF CONTENTS 2 CHAPTER 1 3 CHAPTER 2 4 CHAPTER 3. Algorithm Design & Problem Solving. Programming. Databases

REPETITION CONTROL STRUCTURE LOGO

Introduction to Computer Programming/Handout 01 Page 1 of 13

(I m not printing out these notes! Take your own.)

Chapter 3 Problem Solving and the Computer

Final Examination Semester 3 / Year 2010

Introduction. C provides two styles of flow control:

CS112 Lecture: Loops

EKT 120/4 Computer Programming KOLEJ UNIVERSITI KEJURUTERAAN UTARA MALAYSIA

Chapter 4 The If Then Statement

3 The L oop Control Structure

Computer System and programming in C

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

BIL101E: Introduction to Computers and Information systems Lecture 8

Algorithms and Problem Solving

Meeting 1 Introduction to Functions. Part 1 Graphing Points on a Plane (REVIEW) Part 2 What is a function?

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

1. Introduction to Programming

Steps to program development

Previously. Iteration. Date and time structures. Modularisation.

[Page 177 (continued)] a. if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl";

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

Full file at

Unit II. (i) Computer Programming Languages

You will have mastered the material in this chapter when you can:

Simple Java Programming Constructs 4

Chapter 4 Introduction to Control Statements

Programming Logic and Design Sixth Edition

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Algorithms and Flowcharts

Boolean Logic & Branching Lab Conditional Tests

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Lecture Transcript While and Do While Statements in C++

Loops (while and for)

C Programming for Engineers Structured Program

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

CS101 Introduction to computing Problem Solving (Computing)

LOOPS. 1- Write a program that prompts user to enter an integer N and determines and prints the sum of cubes from 5 to N (i.e. sum of 5 3 to N 3 ).

Structure Array 1 / 50

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Structured Program Development in C

STUDENT LESSON A12 Iterations

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection)

Course Outline Introduction to C-Programming

PROBLEM SOLVING TECHNIQUES

FLOWCHARTS A flowchart is a graphical representation of the steps to be followed for solving problem. It consists of a set of symbols.

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

Transcription:

Chapter Two: Program Design Process and Logic 2.1 Chapter objectives Describe the steps involved in the programming process Understand how to use flowchart symbols and pseudocode statements Use a sentinel, or dummy value, to end a program Use a connector symbol Assign values to variables 2.2 Introduction 2.3 Program development Lifecycle (PDLC) Program development Lifecycle (PDLC) refers to the steps programmers follow when building computer programs. There are six steps which include: Understand the problem Plan the logic Code the program Use software to translate the program to machine language Test the program Deploy the program into production 2.2.1 Understand the problem/analyze the problem It s the most difficult phase in program design since the users may not able to articulate their needs pretty well. Users need keep on changing. The process may force the programmers to learn the user s functional tasks. The programmer is supposed to meet with the system analysts and the users with an aim of understanding what the problem is. The programmer should also identify the programs input, output and processing components. Failure to understand the problem is the major cause of most project failures 2.2.2 Planning the logic During this stage, the programmer is supposed to plan the steps the program will take. At this stage, the program activities are grouped into modules. A solution algorithm for each phase is provided and tested. Programmers using some design tools which can be graphical or written description for each module. Tools such as algorithms, flowcharts and pseudocode are used to design the program logic. 16

2.2.3 Coding the program At this stage of program, the programmer selects the programming language based on the task at hand then writes instructions which implement the algorithms in step. 2.2.4 Translate the source code into machine language Programmers write instructions (source code) in English-like highlevel languages. This source codes have to be translated by translator program low-level machine language that can be executed. During the translation, syntax errors are indentified by the translator program 2.2.5 Testing the program During this stage, the programmer executes the program with sample data and checks the results then compare them with the user s requirements. During this phase logic errors are indentified and corrected. When choosing the sample data make sure you are careful to exercise all branches of the logic. 2.2.6 Putting the program into production This is done after testing is complete and all errors in the programs have been corrected. It may require coordination with other related activities or software. 2.2.7 Maintain the program The last activity of the PDLC is maintaining the program. Maintaining the program involves a number of activities such as Identifying the errors Indentify any enhancements Modifying existing programs to improve their functionality 2.4 Programming design and logic tools There are basic three program design techniques that programmers can use while designing a program; algorithms, flowcharts and pseudocode. Some are visual tools while others are English like statements representing the logic 2.5 Algorithms The term algorithm originally referred to any computation performed via a set of rules applied to numbers written in decimal form. We can define an algorithm as a set or list for list of instructions for solving a particular problem. Ideally, an algorithm is a representation of a solution to a problem. The language used to describe an algorithm to other people will be quite different from that which is used by the computer; however the actual algorithm will in essence be the same 17

If a problem can be defined as a difference between a desired situation and the current situation in which one is, then a problem solution is a procedure, or method, for transforming the current situation to the desired one. Algorithms can be designed using either flow charts or pseudocode. Example Write an algorithm that calculates the pay of employees based on the hours worked and the rate per hour 1. Start 2. Get hours_worked 3. Get rate_per_hour 4. Pay=hours_worked times rate_per_hour 5. Output the pay 6. Stop 2.6 Flow charts A flowchart is a diagrammatic/graphical representation that illustrates the sequence of operations to be performed to get the solution of a problem. It s a logical diagram that describes each step that the program must perform in order to arrive at a solution. It s a popular logic tool used for showing an algorithm in form of graphics They are generally drawn in the early stages of formulating computer solutions before coding. 2.4.1 Purpose of flowcharting Introduction to Programming 18 An aid in developing the logic of a program. Verification that all possible conditions have been considered in a program. Provides means of communication with others about the program. A guide in coding the program. Documentation for the program. 2.4.2 Flowcharting Symbols There are 6 basic symbols commonly used in drawing flow chart diagrams; Terminal, Process, input/output, Decision, Connector and Predefined Process. This is not a complete list of all the possible flowcharting symbols, it is the ones used most often in the structure of Assembly language programming. Symbol Name Function Process Decision Indicates any type of internal operation inside the Processor or Memory Used to make a decision which requires a boolean

value Used to invoke a Predefined process subroutine or an interrupt program. Connector A circle with a number or letter to identify the matching transfer location. Off the page Contains page number and connector a number of letter to identify the matching transfer location Denotes start/end of a Terminal program, process, or interrupt program Preparation Used in declaring and initializing identifiers or variables that will be used in the programs. Flow lines Shows flow of data Input/output Used for any Input / Output operation. Indicates that the computer is to obtain data or output results 2.4.3 Rules for flowcharting 1. All symbols of the flowchart are connected with Arrows. 2. Flowchart symbols have an entry point on the top of the symbol with no other entry points. The exit point for all flowchart symbols is on the bottom except for the Decision symbol. 3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side. 4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown as long as it does not exceed 3 symbols. 5. Connectors are used to connect breaks in the flowchart. Examples are: From one page to another page. From the bottom of the page to the top of the same page. An upward flow of more than 3 symbols 19

6. All flow charts start with a Terminal or Predefined Process (for interrupt programs or subroutines) symbol. 7. All flowcharts end with a terminal or a contentious loop. Example Design an algorithm and the corresponding flowchart for finding the sum of four numbers. Write an algorithm that calculates the pay of employees based on the hours worked and the rate per hour 2.7 Pseudocode Flowcharts were the first design tool to be widely used, but unfortunately they do not very well reflect some of the concepts of structured programming. Pseudocode, on the other hand, is a newer tool and has features that make it more reflective of the structured concepts. Unfortunately, the narrative presentation is not as easy to understand and follow. Pseudocode is a generic way of describing an algorithm without use of any specific programming language syntax. They cannot be executed on a real computer, but it models and resembles real programming code, and is written at roughly the same level of detail. Introduction to Programming 20 A pseudocode is a detailed yet a readable description of what a computer program or algorithm must do expressed in a formallystyled natural language rather than in a programming language. It uses English word. It s sometimes used as a detailed step in the process of developing a program. It allows designers/programmers to express the design in great detail and provides programmers a detailed template for the next step of writing code in a specific programming language. Pseudocode language Keyword ` Accept/input Close/stop Compute Declare Display/print/output Entry/start Exit If Move Perform Function allow data terminating a program mathematical computation defining various identifiers displaying contents marking the beginning marking the end comparing contents to copy or moved data perform procedure

For example a pseudocode to get the square of a number would be written as follows Another example of a pseudo-code which input three numbers from the keyboard and output the result. start Use variables: sum, number1, number2, number3 of type integer Accept number1, number2, number3 Sum = number1 + number2 + number3 Print sum Use variables:number,square of type integer Start Get number Compute squareno * 2 Print Stop End program 2.8 Control Structures/Logical Structures The key to better algorithm design and thus to programming lies in limiting the control structure to only three constructs. These are illustrated below: 2.8.1 The sequence structure This structure is the most elementary structure whereby algorithms are constructed in such a way that, no condition step is required. The sequence structure is the logical equivalent of a straight line. For example, suppose you are required to design an algorithm for finding the average of six numbers, and the sum of the numbers is given. 2.8.2 Decision Structure /Selection Structure This type of a case where the algorithm has to make a choice of two alternatives by making decision depending on a given condition. We can also refer to them as cases selection structures when there are two or more alternatives to choose from. This general structure can be illustrated in a flowchart as follows F Task a Cond ition Task b T 21

The corresponding in pseudocode form is as follows If condition=true then Do task b Do task a End if Making Choices There are many occasions in program when making choices is required. Sometimes you may need to take a given action based on the user choice. All computer programming languages provide a means of selection usually it is in the form of If statement. For example, the following statement combines if statement together with logical operators to test for true or false as depicted below. If a = b print a = b The statement a=b is only printed when the condition tests true. The table below summarizes the logical operators used in pseudocode are Logical operator purpose = is equal to > is greater than < is less than <> is not equal to <= is less than or equal >= is greater than or equal Example The following shows how the selection control structure is used in a program where a user chooses the options for multiplying, adding or subtracting the numbers The corresponding pseudocode is as follows Use variables: choice, of the type character ans, number1, number2, of type integer display choose one of the following display m for multiply display a for add display s for subtract accept choice display input two numbers you want to use accept number1, number2 if choice = m then ans= number1 * number2 if choice = a then ans= number1 + number2 if choice = s then ans= number1 - number2 22

display ans Compound Logical Operators There are many occasions when we need to extend the conditions that are to be tested. It s possible to link conditions. For example in everyday language we say things like If I had the time and the money I would go on holiday. The and means that both conditions must be true before we take an action. We might also say I am happy to go to the theatre or the cinema. The logical link this time is or. Conditions in if statements are linked in the same way. Conditions linked with and only result in an action when all conditions are true. On the other side, conditions linked with an or lead to an action when either or both are true. Example The program is to input an examination mark and test it for the award of a grade. The mark is a whole number between 1 and 100. Grades are awarded according to the following criteria: Student score Grade >= 70 and <=100 First class honours >= 60 and <=69 Second class honours >= 50 and <=59 Second lower class >= 40 and <=59 pass >=0 and <=39 Fail Required Write the appropriate pseudocode for the above program logic Use variable: score of type real Display input student score Accept score If score>=70 AND marks<=100 Display first class honours If score>=60 AND marks<=69 Display display second class honours If score>=50 AND marks<=59 Display display lower class If score>=40 AND marks<=49 Display pass If score>=0 AND marks<=39 Display pass Display invalid score End if 23

The case statement Repeating the if else statements a number of times can be somewhat confusing. An alternative method known as the case statement is usually provided in a number of languages statement. The following example program segment outputs a message to the monitor screen describing the insurance available according to a category input by the user. Use variables: category of type character Display input category Accept category If category = U Display insurance is not available If category = A then Display insurance is double If category = B then Display insurance is normal If category = M then Display insurance is medically dependent Display entry invalid This can be expressed in a case statement as follows: Use variables: category of type character Display input category Accept category DO case of category CASE category = U Display insurance not available CASE category = A Display insurance is double CASE category = B Display insurance is normal CASE category = M Display insurance is medically dependent OTHERWISE Display entry is invalid ENDCASE Instead of using the word otherwise, one can use else. 2.8.3 Repetition/Iteration Structure 24

This kind of structure causes certain steps to be executed repeatedly until a certain condition has been met. Iterative structure can be implemented in three ways namely Repeat Until Loop The While Loop The For Loop Any program instruction that repeats some statement or sequence of statements a number of times is called iteration or a loop. The commands used to create iterations or loops are all based on logical tests. There three constructs for iterations or loops in our pseudocode. The Repeat Until loop. Its syntax is as follows REPEAT A statement or block of statements UNTIL a true condition For example a survey has been carried out to discover the most popular sport. The results will be typed into the computer for analysis. Write a pseudocode to accomplish this. REPEAT DISPLAY Type in the letter chosen or Q to finish DISPLAY A: Athletics DISPLAY S: Swimming DISPLAY F: Football DISPLAY B: Badminton DISPLAY Enter data ACCEPT letter If letter = A then Athletics = athletics + 1 If letter = S then Swimming = Swimming + 1 If letter = F then Football = Football + 1 If letter = B then Badminton = Badminton + 1 UNTIL letter = Q DISLAY Athletics scored, athletics, votes DISLAY Swimming scored, swimming, votes DISLAY Football scored, football, votes DISLAY Badminton scored, Badminton, votes The WHILE loop 25

It s a conditional loop which test for the condition first before executing any set of instructions.no action is performed at all if the first test causes the terminating condition to evaluate as false. Its syntax is as follows WHILE(a condition is true) ENDWHILE Example A statement or block of statements Write a pseudocode for a program that will output the square root of any number input until the number input is zero. In some cases, a variable has to be initialised before execution of the loop as shown in the following example. Use variable: number, square of type real DISPLAY Type in a number or zero to stop ACCEPT number WHILE number <> 0 Square = number * number DISPLAY The square of the number is, square DISPLAY Type in a number or zero to stop ACCEPT number ENDWHILE Introduction to Programming The FOR Loop 26 Usually used to execute statatements repeatedly for a specified number of times. It s the simplest form, initializing the variable as a starting point, a stop condition depending on the value of the variable. The variable is incremented on each iteration until it reaches the required value. The pseudo-code syntax will be: FOR(starting state, stopping condition, increment) Statements ENDFOR Example 13. FOR (n = 1, n <= 4, n + 1) DISPLAY loop, n ENDFOR The fragment of code will produce the output In the example, n is usually referred as the loop variable, or counting variable, or index of the loop. The loop variable can be used in any statement of the loop. The variable should not be assigned a new value within the loop, which may change the behaviour of the loop. For example, write a pseudocode for a program to calculate the sum and average of a series of numbers.

Use variables: n, count of the type integer Sum, number, average of the type real DISPLAY How many numbers do you want to input ACCEPT count SUM = 0 FOR (n = 1, n <= count, n + 1) DISPLAY Input the number from your list ACCEPT number SUM = sum + number ENDFOR Average = sum / count DISPLAY The sum of the numbers is, sum DISPLAY Average of the numbers is, average time-and-a-half for all hours worked over 40. Pseudo-code the task of computing gross pay given pay rate and hours worked. 3. Design an algorithm and the corresponding flowchart for finding the sum of n numbers. 4. 2.9 Chapter summary 2.10 Chapter exercise 1. Design an algorithm and the corresponding flowchart for adding the test scores as given below 30, 50, 39, 40 2. Mr. Patel pays his employees salary on weekly basis. The gross pay depends on the pay rate and the number of hours worked per week. However, if you work more than 40 hours, you get paid 27