1 / 77

Introduction to Algorithms and Programming

Learn basic problem-solving techniques, understand inputs and outputs, grasp the concept of variables, develop algorithms through top-down refinement, and convert algorithms to pseudocode and flowcharts.

Download Presentation

Introduction to Algorithms and Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MIS 131Introduction to Algorithms and Programming2018/2019 Fall- Chapter 1 –Algorithms, Pseudocodes and Flowcharts 1

  2. Objectives • In this chapter, you will learn: • To understand basic problem solving techniques. • Inputs and outputs of a proglem • Concept of variables • To be able to develop algorithms through the process of top-down, stepwise refinement. • To be able to convert the algorithm to pseudocode and flowcharts

  3. 2.1 Introduction • Before writing a program: • Have a thorough understanding of the problem • Carefully plan an approach for solving it • The program should be carifully designed • While writing a program: • Know what “building blocks” are available • Use good programming principles

  4. 2.2 Algorithms • Computing problems • All can be solved by executing a series of actions in a specific order • Algorithm: procedure in terms of • Actions to be executed • The order in which these actions are to be executed • Program control • Specify order in which statements are to be executed

  5. Dack of Cards • In a game - dack of cards • each player pull a card at the top of the dack • read the task written on it • perform the task • then pull the next card on the top of the dack

  6. Example 2.1 Registration • A real life example • Describe steps of registration to an universty • step by step description of how a new commer is to register to an universty

  7. Example 2.1. Registering to an University Algorithm • 1 Obtain required forms • 2 Fill out the forms • 3 Other required materials are prepaired • identification, diploms • 4 Registration fee is paid • 5 forms are submited to the relevent person • 6 if something is mising • goto step 2 • 7 Sign the agrement • 8 Registration is complete

  8. Notice that • When each step is compleated • next step is passed • it is also possible to branch a previous or later step • in this example from step 6 to srep 2 • The action in each step may depend on a condition • in step 6 if everything is OK continue otherwise branch to step 2 • Each of these steps may consists of sub steps • ex: step 2 fill out forms: there may be three different forms • each of which may be a sub step of step 2 • 2a : a from for registration office • 2b : a form for university hospital • 2c : a form for university library

  9. Example 2.2 Calculating area of a regtangle • Calcuating area of a rectangle • Algortihm: • 1- Start • 2- Get value of hight • 3- Get value of width • 4- Multiply hight by width to obtain area • 5- Display the resulting area to the screen • 6- Stop

  10. Note • Without performing steps 2 and 3 • Step 4 can not be performed • Similarly • Without performing steps 4 • Step 5 can not be performed • But • Steps 2 and 3 can be interchanged

  11. Exercis 2.1 • Pick up a real life situation that interest you • for example: • driveing a car • cooking egg or cake • Construct the algorithm to explain step by step description of the actions to someone who does not have any idea obout that situation

  12. 2.3 Pseudocode • Pseudocode • Artificial, informal language that helps us develop programs • One step closer to programming languages • Similar to everyday English on one side and programming languages on the other side • Not actually executed on computers • Helps us “think out” a program before writing it • Easy to convert into a corresponding C program • Consists only of executable statements

  13. Pseudocode for Example 2.2 1 Start 2 a Display “Enter height of the rectange” 2 b Input heigth 3 a Display “Enter width of the rectange” 3 b Input width 4 Set area = height * width 5 Display “The area of the regtanle” , area 6 Stop or end

  14. Note That In the algorithm :in step 2 Getting the height from the user In the pseudocode first write a message to be displayed in the screen informing the user what to enter as an input Then let the user enter a real number and press ENTER key The number entered by the user is stored in the variable heigth Similarly for getting width of the rectangle – in step 3 14

  15. When the pseudocode is implemented in any programming languare such as Java, C# or Python The user first see the message “Enter height of the rectange ” in the computers screen The user is expected to enter real number for the height end press ENTER key The Input heigth statement obtains the chacters entered by the user converts into a numerical variable named height to be used in subsequent steps of the pseudocode or program 15

  16. Building Blocks • Input output transfer • Calculations in between - processing • Decision making • Iteration • Variables • Store data in memory • different types in different languages • İntegers, real, character, string .logical,,.. • Input: obtain a value from the user and store in a variable • enter a value for radius of a circle to compute its area • enter your name lastname id number • make a choice Yes/No to save or not

  17. Variables • Store data in memory • different types in different languages • Integers, real, character, string, logical (true or false) ... • numerical variables • heigth, width, age, totalSales, numer of children • Strings : • Name, last name, address, e-mail • “Bertan” , “Badur”, “badur@boun.edu.tr” • usually presented in quats “.....”

  18. Variable in daily iife • what is your name? • stored in your memory as a string • what is your age or weight • you know the meaning of age or weight • stroded as an integer or real and changes over time • What is your GPA • you know wht GPA is but not yet has a value as a new studeent • What is your garbay score • this does not make a sense to you • no such think in your memory • when asked you are supprised or hesitate to answer • BUT A COMPUTER PRGRAM FAİLS

  19. Outtput • Output: display the results of the problem • some variables • display area • constant messages • Display “welcome to Java” • Display “you failed to register” • expressions • Display pi*r2 • or a mixture of them • Display “the area is:“, area • E.g.: displays when the value of area is 200 • the area is: 200

  20. Calculations - processing • Calculations • aritmetic and logical computations • intermediate resulst are also in variables • E.g.: • Set area = hight*width • area is the product of hight and width • E.g.: • Set valueAddedTax = taxRate*basePayment • E.g.: • Set total = total + new grade • add new grade to the total

  21. 2.4 Control Structures • Sequential execution • Statements executed one after the other in the order written • Transfer of control • When the next statement executed is not the next one in sequence • Overuse of goto statements led to many problems • Bohm and Jacopini • All programs written in terms of 3 control structures • Sequence structures: Built into Java. Programs executed sequentially by default • Selection structures: Java has three types: if, if…else, and switch • Repetition structures: Java has three types: while, do…while and for

  22. Simple Building Blocks • We will start with • input • get data from the user • store in variables • process or calculation • Store the results in (new) variables • output • dsiplay message and/or variables to the screen • Variables of different types • Stored in memory • Referen by a name in our pseudocodes, and programs

  23. 2.3Flowcharts • Flowchart • Graphical representation of an algorithm • Drawn using certain special-purpose symbols connected by arrows called flowlines • Rectangle symbol (action symbol): • Indicates any type of action • Oval symbol: • Indicates the beginning or end of a program or a section of code • Single-entry/single-exit control structures • Connect exit point of one control structure to entry point of the next (control-structure stacking) • Makes programs easy to build

  24. Flowchart Symbols start or end calculation flow decision making output input

  25. Example 2.3 Foreign Exchange Problem • The amount of $ in your hand makes how meny TL • 1 $ 6.20 TL • Inputs:: • amount of dollar in your hand • Output: • How much does the dollar worth in terms of TL • :Limitations • 1 dolar is 6.20 TL forex rate is constant • just convert to TL

  26. Ex 2.3 Algorithm of exchange rate calculation 1 Start 2 Define the forex rate 3 Get dollar amount 4 TL correspondence of the dollar is computed TL = dollar * exchage rate 5 dsiplay TL 6 Stop or End What variables are needed? dollar, TL exchange rate? 26

  27. Pseudocode 1 Start 2 Set forexRate = 6.20 3a Display “Enter dollar in your hand” 3b Input dollar 4 Set tl = dollar * forexRate 5 Display “your”, dollar , “worths”, tl 6 Stop or End 27

  28. Variables ForexRate a real number set at the begining fixed it does not change dollar dollar in the hand of the user real input every run of the program has a different value tl calculated TL amout for the dollar with the dixed forexRate 28

  29. Limitations and Extensions Limitations: every time a new $ is given the algorithme start from begining if the user enters a negative value it prints a negative NTL if the user enters a character it fails to compute Note: should the exchange rate be asekd as a second input or is it fixed As it is not chaning very often but it may change hourly Exercise: Modify the algorithm when the for ex rate change as well Extension of the problem given NTL the user mey want to chose the forex ohter then dollar to purchase 29

  30. Ex 2.4. Length conversion • What is the equivanent of a given inch in term of cm • Inputs: • inch • Output:: • cm • Limitations: • just between inch and cm • Note: relation between c.m. and inch is constant and 1 inch is 2.54 cm

  31. Ex 2.5. Area and circunference of circle • Given a radius of a circle calcualte its area and circunference • Inputs: • radius • Output: • area and circkunference • Note has two outputs • Limitations: • only for circle • Note:Pi is a universal constant as well 3.14159

  32. Area and Circunference of circle 1 Start 2 Set the value of pi = 3.1416 2 Get radius 4 Compute area and circunference 4.a area = pi * (radius)2 4b circunf. = 2 * pi * radius 5 display area and circunference to the screen 6 Stop or end What are variables? radius, area, circunference What about pi its value does not change – universan constant What are the limitations of the algorithm? 32

  33. Pseudocode for Cirlcle 1 Start 2 Set pi = 3.14 3a Display “Enter radius” 3b Input radius 4a Set area = pi * radius2 4b Set circunference = 2 * pi * radius 5a Display “Area of the circle is” , area 5b Display “Circunference of the circle is”, circunference 6 Stop 33

  34. Ex 2.7 Display a Fixed message • Display your signiture to the screen • when run always displays your name, last name, address and e-mail to the screen • Limitation: only one signiture for you • No input, no variables • Output Name: Bertan Last name: Badur Address: Bogazici University E-male: badur@boun.edu.tr

  35. Ex 2.8 Asking and displaying your personal information • Task: ask name lastname and age • dispay to the screeen • Inputs : name, lastName – String • age - integer • Output: A messge that change according to your name last name and age but has some fixed characters • Example output • Name: İrem Last Name : Badur • Age: 12

  36. Algorithm • 1 Start • 2 Ask and get name, last name and age of a person • 2a ask and get neme • 2b ask and get last name • 2c ask and get age • 3 Dispay personal information in a forfmated way to the screen • 3a dispay name • 3b dispay last name • 3c dispay age • 4 Stop

  37. Pseudocode • 1 Start • 2a i Display “Enter your name” • 2a ii Input name • 2b i Display “Enter your last name” • 2b ii Input lastName • 2c i Display “Enter your age” • 2c ii Input age • 3a Display “Name:” , name • 3b Display “Last Name:”, lastName • 3c Display “Age:”, age • 4 Stop

  38. Variables • name , lastName • String – set of characters • age • integer your age

  39. Flowchart • Draw the flowchart

  40. Ex 2.9. Exam grades • Computes exam statistics • Inputs: • student grades • Outputs: • avgerage, min, max, letter grades, ... • Limits: • only for one exam

  41. A Simple Grade Average Calculation Problem • Task: There are only three students in a class • Ali, Ahmet and Nazlı. Get their exam grades from the user and calculate and display the class average to the screen.

  42. Algorithm A class consisting of three students: Ali,Ahmet, Nazlı 1 Start 2 Get Ali’s grade 3 Get Ahmet’s grade 4 Get Nazlı’s grade 5 Compute the average grade Average grade = (Ali’s grade + Ahmet’s grade + Nazlı’s grade)/3 6 Display the average grade 7 End Variables: Ali’s grade, Ahmet’s grade, Nazlı’s grade, average grade 42

  43. Pseudocode and variables 1 Start 2a Declare Integer alisGrade 2b Declare Integer ahmetsGrade 2c Declare Integer nazlisGrade 2d Declare Real average 3a Display “Enter Ali’s grade” 3b Input alisGrade 4a Display “Enter Ahmet’s grade” 4b Input ahmetsGrade 5a Display “Enter Nazli’s grade” 5b Input nazlisGrade

  44. Pseudocode and variables (cont.) 6 Set average = (alisGrade + ahmetsGrade + nazlisGrade)/3 7 Display “the class average” , average • End Variables alisGrade, ahmetsGrede and nazlisGrade are declared as integers average is declared as Real Note that: if this pseudocode is implemented in Java or C programming languages sum of three integers is an integer dividing by 3 you may lose the remainder because of ineger division

  45. Solution • Declare the student grades as Real variables average = ( 10.0 + 9.0 + 9.0) / 3 here average is 9.33333 • if grades are declared as integers average = (10 + 9 + 9) / 3 here average is 9.00000

  46. Another Important feature • In step 6 of the pseudocode • average can be computed in one asignment statement • or it can be computed is steps as follows 6a Set sum = alisGrade 6b Set sum = sum + ahmetsGrade 6c Set sum = sum + nazlisGrade 6d average = sum / 3 How do you get rid of the information lose due to integer division ?

  47. Ex 2.10. Purchase • what is total payment after a sale • Inputs: • products SKU and amounts • Outut: • invoice total payment value added tax • Note prices of goods are not inputs

  48. Purchase Problem tasl two products apple and pair prices are given not chaning Value added tax tax rate is constant Input: AmoutApple, AmountPair – asked to user Output: netPay, VAT, grossPay – calculated and printed Variables: PriceApple, PricePair – fixed AmoutApple, AmountPair – asked to user VAT Rate – fixed netPay, VAT, grossPay – calculated and printed 48

  49. Purchase Problem Algorithm 1 Start 2a define prices for the two goods PriceApple = 4, PricePair = 5 2b define value added tax rate VATRate = 0.18 3 get amount of apple and pair purchased from the user 4 Calculate net payment netPay = PriceApple*AmountApple + PricePair*AmountPair 5 Calculate VAT VAT ? netPay*VATRate 6 Calculate gross payment grossPay = netPay + VAT 7 print net psyment, VATand total payment to screen 8 End 49

  50. pseudocode flowchart Exercise to you Note if you are sure that value of a variable will not change through out the program, you can declare them a constants many programming languages including Java has a syntax for constants any attempt to change the value of a constant is a syntax error Examples of well known constants pi = 3.1416, e = 2.713 speed of light, Avagadro number 50

More Related