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

Similar documents
Unit II. (i) Computer Programming Languages

FLOW CHART AND PSEUDO CODE

Notes By: Shailesh Bdr. Pandey, TA, Computer Engineering Department, Nepal Engineering College

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

A Quick Review of Chapter 1

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

Algorithms: The recipe for computation

SNS COLLEGE OF ENGINEERING,

PROBLEM SOLVING AND PYTHON PROGRAMMING

The diagram below is only partially complete. Use the terms in the word list to complete the empty boxes. Make dinner

Grade 7 Math LESSON 14: MORE PROBLEMS INVOLVING REAL NUMBERS TEACHING GUIDE

Chapter 1 INTRODUCTION TO COMPUTER AND PROGRAMMING

Chapter 1: An Introduction to Computer Science

Graded Project. HTML Coding

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

depicts pictorially schematic representation of an algorithm document algorithms. used in designing or documenting

Everyday Algorithms. Algorithms and Introduction to Programming. bake a cake. start. mix sugar and butter. stir in 2 eggs. stir in flour.

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

Two figures that have the exact same shape, but not necessarily the exact same size, are called similar

Computer System and programming in C

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

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

Chapter 2 - Problem Solving

Chapter 1: An Introduction to Computer Science. Invitation to Computer Science, C++ Version, 6-th Edition

INTRODUCTION TO ALGORITHMS

COMPUTATIONAL THINKING

CSE 142, Summer 2015

CSIS 104 Introduction to Computer Science


A Unicorn Named Sparkle Word Search. A New Friend for Sparkle Coloring Sheet. A Unicorn Named Sparkle s First Christmas Coloring Sheet

CSE 142, Summer 2014

Lecture 1: Introduction

SOEE1160: Computers and Programming in Geosciences Semester /08. Dr. Sebastian Rost

Algorithms, Part 2 of 3. Topics Problem Solving Examples Pseudocode Control Structures

CSc 110, Autumn 2016 Lecture 6: Parameters. Adapted from slides by Marty Stepp and Stuart Reges

High-level software (Ch.9) Algorithms and data structures. Low-level software. Components Circuits Gates Transistors

LECTURE 5 Control Structures Part 2

Algorithms ~ Introduction to Algorithms. R K Shyamasundar

COMP 102: Computers and Computing

Introduction to Computing Lecture 00: Part 2 Introduction to Algorithms and Flowcharts

Lesson 166 (Pages 27-29)

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

USER S GUIDE. Model 8300

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

Python - Week 1. Mohammad Shokoohi-Yekta

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

The Further Mathematics Support Programme

1. Introduction to Programming

Java Programming. What is a program? Programs Recipes. Programs as Recipes 8/16/12. Pancakes In one bowl. mix: 1½ cup flour

CISC 110 Day 1. Hardware, Algorithms, and Programming

CSC 121 Spring 2017 Howard Rosenthal

SNS COLLEGE OF ENGINEERING

clicker question Comments Using comments Topic 3 static Methods and Structured Programming

UNDERSTANDING PROBLEMS AND HOW TO SOLVE THEM BY USING COMPUTERS

Visual Basic Course Pack

Building Java Programs

Building Java Programs

Problem Solving 101. DEFN An is a group of instructions (often expressed informally) for performing some task.

Steps to program development

BIL101E: Introduction to Computers and Information systems Lecture 8

Chapter 1: Problem Solving Skills Introduction to Programming GENG 200

Flowchart Structure 25th October 2018

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #01 Introduction: The Process of Programming

A Beginner s Guide to Programming Logic, Introductory. Chapter 2 Working with Data, Creating Modules, and Designing High-Quality Programs

Building Java Programs

IDENTIFY WAYS OF REPRESENTING ALGORITHMS.

CS187 - Science Gateway Seminar for CS and Math

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

Chapter Two: Program Design Process and Logic

EECS1012. Net-centric Introduction to Computing. Lecture 7 Computational Thinking. Fall 2018, EECS York University. M.S. Brown and Amir H.

Algorithms and Flowcharts

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

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

Adult Computer and Employment Skills

Problem Solving Footer Text 10/30/2015 1

UNIT-3 PROBLEM SOLVING AND OFFICE AUTOMATION

Algorithms, Part 2 of 3. Problem Solving. Problem Solving (con t) Topics Problem Solving Examples Pseudocode Control Structures

Recap: Structure of a Java program CS 112 Introduction to Programming. A Foundation for Programming Why Introduce Static Methods?

CS 112 Introduction to Programming

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

Unit 1: Introduction to Algorithms

Chapter 3: Program Statements

MAS115: R programming Lecture 2: Pseudocode Lab Class and Technical Material: Matrices, Factors, Data frames, Lists

PROGRAM DESIGN TOOLS. Algorithms, Flow Charts, Pseudo codes and Decision Tables. Designed by Parul Khurana, LIECA.

Principles of Computer Science I

CSc 110, Spring Lecture 2: Functions. Adapted from slides by Marty Stepp and Stuart Reges

Programming Logic and Design Sixth Edition Chapter 2 Working with Data, Creating Modules, and Designing High-Quality Programs

Chapter 1 - An Introduction to Computers and Problem Solving

Statistics Case Study 2000 M. J. Clancy and M. C. Linn

Writing a Basic Program in Python

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Chapter Twelve. Systems Design and Development

Harvard-MIT Division of Health Sciences and Technology HST.952: Computing for Biomedical Scientists HST 952. Computing for Biomedical Scientists

1. The first step that programmers follow when they solve problems is to plan the algorithm.

Building Java Programs

3. Introduction to Algorithm and Flowchart

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Announcements Tues., Aug and 2. to call them ( ) ! For next time, read Learning Computing with Robots, chs.

Programmable Control. Name Class Teacher. Ellon Academy Technical Faculty

Transcription:

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

Lecture 02: Algorithms Readings: Not Covered in Textbook

Problem Solving Process System Design: Find a set of sub-problems such that each sub-problem is easy to solve; and the desired problem can be solved by solving them Algorithm Design: Find solution to each sub-problem Programming: Translate algorithms into codes Bhaskar Shrestha 3

Algorithms Computing problems Solved by executing a series of actions in a specific order Algorithm is a procedure determining Actions to be executed Order to be executed Example: recipe Program control Specifies the order in which statements are executed Bhaskar Shrestha 4

Algorithm: Definition An algorithm is a precise specification of a sequence of instructions to be carried out in order to solve a given problem Each instruction tells what task is to be done Specification of a sequence of instructions to do a job is used in many fields A cooking recipe, The rules of how to play a game, VCR instructions, Description of a martial arts technique, Directions for driving from A to B, A knitting pattern, A car repair manual Bhaskar Shrestha 5

Recipe: Chocolate Chip Cookies (1/2) Ingredients: 2 ¼ cups flour, 1 tsp salt, 1 tsp baking soda, 2 eggs, ¾ cup brown sugar, 1 tsp vanilla extract, ¾ cup granulated sugar, 1 cup soft butter, 12 oz. semi-sweet chocolate chips Steps: 1. Preheat oven to 375 degrees 2. Combine flour, salt, baking soda, in bowl. Set mixture aside. 3. Combine sugars, butter, vanilla and beat until creamy. 4. Add eggs and beat. 5. Add dry mixture and mix well. 6. Stir in chocolate chips. 7. Drop mixture by teaspoons onto ungreased cookie sheet. 8. Bake 8 to 10 minutes Bhaskar Shrestha 6

Recipe: Chocolate Chip Cookies (2/2) Although the recipe given in the previous slide does not technically qualify as an algorithm but is similar to algorithm It is a sequence of instructions to be carried out to solve the problem of making chocolate chip cookies It begins with a list of ingredients which is the input The sequence of instructions specify the actions to be carried out with the input to produce the cake which is the output It takes a finite time to execute the instructions and stop Bhaskar Shrestha 7

A Wrong Algorithm What is wrong with this so called algorithm? Directions: (From the back of a shampoo bottle.) Wet hair. Apply a small amount of shampoo, lather, rinse, repeat. If you follow this algorithm, you will never finish washing your hair! Bhaskar Shrestha 8

Properties of Algorithms (1/2) Inputs: A number of quantities are provided to an algorithm initially before the algorithm begins. These quantities are the inputs which are processed by the algorithm. Definiteness: The processing rules specified in the algorithm must be precise, unambiguous and lead to a specific action. Effectiveness: Each instruction must be sufficiently basic such that it can, in principle, be carried out in a finite time by a person with paper and pencil. Bhaskar Shrestha 9

Properties of Algorithms (2/2) Finiteness: The total time to carry out all the steps in the algorithm must be finite. An algorithm may contain instructions to repetitively carry out a group of instructions. This requirement implies that the number repetitions must be finite Outputs: An algorithm must have one or more output Correctness: Correct set of output must be produced from the set of inputs. For the same input data, it must always produce the same output Bhaskar Shrestha 10

Origin of word Algorithm Named after famous Persian mathematician Abu Jafar Mohammad ibn Musa al-khowarizmi, who wrote the book Kitab al jabr Walmuqabla (Rules of restoration and reduction) around 825 A.D. The last part of his name get corrupted to algorithm The word algorism originally referred only to the rules of performing arithmetic using Arabic numerals but evolved into algorithm by the 18th century The first case of an algorithm written for a computer was Ada Byron s notes on the analytical engine written in 1842, for which she is considered by many to be the world s first programmer Bhaskar Shrestha 11

Writing Algorithms There are various techniques that can be used to write algorithms: in English (e.g. enrolment guide) by diagrams (e.g. instructions for assembling kitset furniture) by Flowcharts in pseudocode in a computer programming language in some other more-or-less formal language (e.g. knitting pattern) Bhaskar Shrestha 12

A Simple Example Fahrenheit to Celsius Conversion Step 1: Read the temperature in Fahrenheit from the keyboard Step 2: Calculate its Celsius equivalent as (F-32) 5/9, where F is the inputted Fahrenheit value Step 3: Print the calculated Celsius value on the screen Bhaskar Shrestha 13

Another Example (1/2) An algorithm to pick the largest tender from a set of tenders Step 1: Read the first tender and note down its value as the maximum tender value so far encountered. Note down the tender identification number Step 2: As long as tenders are not exhausted do Steps 3 and 4. Go to Step 5 when tenders are exhausted Step 3: Read the next tender and compare the tender with the current maximum tender value Bhaskar Shrestha 14

Another Example (2/2) Step 4: If this tender value is greater than that previously noted down as maximum tender then erase the previous maximum value noted and replace it by this new value. Replace the previously noted tender identification number by this identification number. Else do not do anything Step 5: Print the final value of maximum tender and its identification noted down in Step 4 Bhaskar Shrestha 15

Pseudocode Pseudocode is a written statement of an algorithm using a restricted and well-defined vocabulary It is, as the name suggests, cannot be executed on a real computer, but models and resembles real programming code, and is written at roughly the same level of detail It is very much like a 3GL and is therefore more easily translated into programming language For many programmers and program designers is the preferred way to state algorithms and program specifications No standard rules for writing Bhaskar Shrestha 16

Writing Algorithms in Pseudocode Pseudocode contains two main elements, the first being keywords These keywords often resemble programming commands and often occur as pairs of words When writing a keyword in pseudocode we would often write it in UPPERCASE and may even highlight it using boldface The second element is that pseudocode relies on indenting to show structure This enables the person working with the algorithm to easily see the flow of logic through the algorithm Bhaskar Shrestha 17

Example Computing area of a rectangle Input: length and breadth of the rectangle Output: Area of the rectangle Step 1. READ length Step 2. READ breadth Step 3. COMPUTE length * breadth GIVING area Step 4. PRINT area Bhaskar Shrestha 18

Values and Variables Values Represent quantities, amounts or measurements May be numerical or alphabetical (or other things) Often have a unit related to their purpose Example: Recipe ingredients Variables Are containers for values places to store values Variable This jar can contain Values 10 cookies 50 grams of sugar 3 slices of cake etc. Bhaskar Shrestha 19

Components of an Algorithm Values and Variables Instruction (a.k.a. primitive) Some action that is simple and unambiguous Sequence (of instructions) A series of instructions to be carried out one after the other Selection (between instructions) An instruction that decides which of two possible sequences is executed The decision is based on a single true/false condition Repetition (of instructions) Repeat an instruction. while (or maybe until) some true or false condition occurs Test the condition each time before repeating the instruction Bhaskar Shrestha 20

Writing Pseudcodes Group Key words Example Input/Output INPUT, READ Used to get values from a data source, a keyboard for instance INPUT counter DISPLAY new_value Processing DISPLAY, PRINT Used to output values to a data sink, a screen or printer for instance ADD SUBTRACT COMPUTE SET ADD 3 TO count SUBTRACT 5 FROM count SET count TO 12 COMPUTE 10 + count GIVING new_count Bhaskar Shrestha 21

Writing Pseudocodes Group Keywords Example Repetition REPEAT statement UNTIL <condition> DOWHILE <condition> statement END DOWHILE FOR <var> = <start value> to <stop value> ENDFOR SET count_value TO 0 REPEAT DISPLAY count_value ADD 1 TO count_value; UNTIL count_value > 10 DOWHILE count_value < 10 DISPLAY count_value count_value = count_value + 1 END DOWHILE FOR count = 1 to 10 DISPLAY count + count ENDFOR Bhaskar Shrestha 22

Writing Pseudocodes Group Keywords Example Decision IF <condition> THEN statement ENDIF IF <condition> THEN statement ELSE statement ENDIF IF count > 10 THEN DISPLAY count ENDIF IF count > 10 THEN DISPLAY 'count > 10' ADD 4 to sum ELSE DISPLAY 'count <= 10' ADD 3 to sum ENDIF Bhaskar Shrestha 23

Using Operators Although the processing group are very useful most program designers tend to prefer to use operators like: + add - subtract * multiply / divide = assign These are the arithmetic operators These are more intuitive since we use them in arithmetical expressions and they are easier to write, for instance: count = count + 22 x = count / 12 sum = sum - count x = count * sum Bhaskar Shrestha 24

Relational Operators Operator Example Description == equal to IF count == 32 THEN... This decision states that if the variable count contains 32 execute the statement following THEN. <= less than or equal to >= greater than or equal to <> not equal to DOWHILE count <= 50... END DOWHILE REPEAT... UNTIL count > 12 The statements in the while loop will execute while the value of count is 50 or less. The statements in the repeat loop will execute until the value of count exceeds 12. IF count <> total THEN... If the value of count is not the same as the value of total execute the statement following THEN. Bhaskar Shrestha 25

Logical Operators Operator Example Description AND OR NOT IF (x = = 32) AND (y = = 7) THEN sumxy = x + y IF (letter = = 'A') OR (letter = = 'E') THEN DISPLAY 'Vowel' IF NOT (letter = = 'A') THEN DISPLAY 'Not letter A' if it is true that x == 32 AND it is also true that y == 7 then add x and y together and store the result in variable sumxy. if the variable letter contains either 'A' or 'B' then display the word vowel on the output device If it is true that letter is equal to 'A', the NOT operator in NOT (letter = 'A') will give a value of FALSE. Bhaskar Shrestha 26

Example 1 Finding largest of two numbers 1. READ num1 2. READ num2 3. IF num1 > num2 THEN 4. PRINT num1 is larger 5. ELSE 6. PRINT num2 is larger 8. ENDIF Bhaskar Shrestha 27

Example 2 Sum of first n natural numbers 1. READ n 2. counter = 1 3. sum = 0 4. DOWHILE counter <= n 5 sum = sum + counter 6. counter = counter + 1 7. END DOWHILE 8. DISPLAY sum Bhaskar Shrestha 28

Developing an Algorithm Understand the problem (Do problem by hand. Note the steps) Devise a plan (look for familiarity and patterns) Carry out the plan (trace) Review the plan (refinement) Bhaskar Shrestha 29

Problem Example (1/5) Find the average from a given set of numbers 1. Understanding the problem: (i) Write down some numbers on paper and find the average manually, noting each step carefully. e.g. Given a list say: 5, 3, 25, 0, 9 (ii) Count numbers, i.e. How many? 5 (iii) Add them up, i.e. 5 + 3 + 25 + 0 + 9 = 42 (iv) Divide result by numbers counted, i.e. 42/5 = 8.4 Bhaskar Shrestha 30

Problem Example (2/5) 2. Devising a plan: Make note of not what you did in steps (i) through (iv), but how you did it. In doing so, you will begin to develop the algorithm. e.g. How do we count the numbers? Starting at 0 i.e. set COUNTER to 0 Look at 1st number, add 1 to COUNTER Look at 2nd number, add 1 to COUNTER and so on, until you reach the end of the list Bhaskar Shrestha 31

Problem Example (3/5) How do we add numbers? Let SUM be the sum of numbers in list. Set SUM to 0 Look at 1st number, add number to SUM Look at 2nd number, add number to SUM and so on, until we reach end of list How do we compute the average? Let AVE be the average then AVE = total sum of items/ number of items, i.e. SUM/COUNTER Bhaskar Shrestha 32

Problem Example (4/5) 3. Identifying patterns, repetitions and familiar tasks. Familiarity: Unknown number of items? i.e. n item Patterns : look at each number in the list Repetitions: Look at a number Add number to sum Add 1 to counter Bhaskar Shrestha 33

Problem Example (5/5) 4. Carrying out the plan Check each step Consider special cases Check result Check boundary conditions: i.e. what if the list is empty? Division by 0? Are all numbers within the specified range? In this example, no range is specified - No special cases. Check result by tracing the algorithm with a list of numbers e.g. 7, 12, 1, 5,13 Bhaskar Shrestha 34

Complete Pseudocode 1. total = 0 2. average = 0 3. count = 0 4. READ n 5. DOWHILE count < n 6. READ number 7. total = total + number 8. count = count + 1 9. END DOWHILE 10. average = total/count 11. PRINT average Bhaskar Shrestha 35

Flowcharts Graphical representation of an algorithm that illustrates the sequence of operations to be performed using special-purpose symbols connected by arrows Flowcharts typically show a program s logic Generally drawn in the early stages of formulating computer solution Facilitate communication between programmers and business people These flowcharts play a vital role in the programming of a problem and are quite helpful in understanding the logic of complicated and lengthy problems Bhaskar Shrestha 36

Flowchart Symbols Start or end of the program Computational steps or processing function of a program Input or output operation Decision making and branching Connector or joining of two parts of program Flow lines Annotations Bhaskar Shrestha 37

Guidelines In drawing a proper flowchart, all necessary requirements should be listed out in logical order. The flowchart should be clear, neat and easy to follow There should not be any room for ambiguity in understanding the flowchart. The usual direction of the flow of a procedure or system is from left to right or top to bottom. Only one flow line should come out from a process symbol or Bhaskar Shrestha 38

Guidelines Only one flow line should enter a decision symbol, but two or three flow lines, one for each possible answer, should leave the decision symbol Only one flow line is used in conjunction with terminal symbol Bhaskar Shrestha 39

Example 1: Larger of two numbers START READ num1 READ num2 True Is num1 > num2? False PRINT num1 PRINT num2 END Bhaskar Shrestha 40

Example 2: Sum of first n natural numbers START READ n counter = 1 Sum = 0 Is counter <= n? True sum = sum + counter counter = counter + 1 False PRINT sum Bhaskar Shrestha 41 END

Some rules for flow charts Every flow chart has a START symbol and a STOP symbol The flow of sequence is generally from the top of the page to the bottom of the page. This can vary with loops which need to flow back to an entry point. Use arrow-heads on connectors where flow direction may not be obvious. There is only one flow chart per page A page should have a page number and a title A flow chart on one page should not break and jump to another page A flow chart should have no more than around 15 symbols (not including START and STOP) Bhaskar Shrestha 42

Advantages of Flowcharts Communication: Flowcharts are better way of communicating the logic of a system to all concerned Effective analysis: With the help of flowchart, problem can be analyzed in more effective way Proper documentation: Program flowcharts serve as a good program documentation, which is needed for various purposes Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and program development phase Proper Debugging: The flowchart helps in debugging process Efficient Program Maintenance: The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part Bhaskar Shrestha 43

Disadvantages of Flowcharts Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes complex and clumsy. Alterations and Modifications: If alterations are required the flowchart may require re-drawing completely. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem. The essentials of what is done can easily be lost in the technical details of how it is done Bhaskar Shrestha 44

System Flowchart System flowchart describes the data flow for a data processing system It provides a logical diagram of how the system operates. It represents the flow of documents, the operations performed in data processing system It also reflects the relationship between inputs, processing and outputs Following are the features of system flowcharts: the sources from which data is generated and device used for this purpose various processing steps involved the intermediate and final output prepared and the devices used for their storage Bhaskar Shrestha 45

Example Bhaskar Shrestha 46

Program Flowchart A program flowchart represents, in detail, the various steps to be performed within the system for transforming the input into output The various steps are logical/ arithmetic operations, algorithms etc It serves as the basis for discussions and communication between the system analysts and the programmers Program flowcharts are quite helpful to programmers in organizing their programming efforts These flowcharts constitute an important component of documentation for an application Bhaskar Shrestha 47

Example Bhaskar Shrestha 48