Docsity

Introduction to Algorithms and Flowcharts in Computer Science, Cheat Sheet of Computer Science

Partial preview of the text

Download Introduction to Algorithms and Flowcharts in Computer Science and more Cheat Sheet Computer Science in PDF only on Docsity!

Introduction to computer science (^1)

Chapter 1

INTRODUCTION TO ALGORITHMS

AND FLOWCHARTS

Chapter 1  Algorithms  Using Flowchart to describe Algorithm  Algorithm in pseudo-code  Branching in Algorithms  Loop in Algorithms

  1. Using Flowchart to describe algorithm Terminal Input/output Process Flowlines Decision Connector Predefined process Fig 1. Flowchart symbols

Example 2.1. Calculate the payment of an employee

Start Input Name, Hours, Rate Calculate Pay  Hours  Rate Dislay Name, Pay End Note: Name, Hours and Pay are variables in the program. Fig. 2.

Example 2.3: How to compute profit and loss. Fig. 4.

8

  1. Algorithms in pseudo-code  You also can use English-like phrases to describe an algorithm. In this case, the description is called pseudocode.  Example: The pseudocode for the program with the flowchart in Fig. 2. Input the three values into the variables Name, Hours, Rate.

Calculate Pay = Hours  Rate.

Display Name and Pay. Start Input Name, Hours, Rate Calculate Pay  Hours  Rate Dislay Name, Pay End

Example 2. Pseudo-code of the program: Input A if A > 0 then calculate B = sqrt(A) print B else Print “ A is negative” endif

Branching Example 4.2: Solving the quadratic equation: ax 2

  • bx +c = 0 Pseudo-code of the program: Input a, b, c Calculate del = b2 + 4.a.c if del >0 then x1 = (-b + sqrt(del)/(2.a) x2 = (-b - sqrt(del)/(2.a) print x1, x else if del =0 then x = - b/(2.a) else print “No solution” endif

Example 5.1 (^) Note: NUM  NUM + 1 means old value of NUM + 1 becomes new value of NUM. Start NUM  4 SQNUM  NUM 2 Print NUM, SQNUM NUM  NUM + 1 NUM> 9? STOP No Yes The algorithm can be described in pseudocode as follows: NUM  4 do SQNUM NUM^2 Print NUM, SQNUM NUM  NUM + 1 while (NUM <= 9)

Example 5. Programming Fundamentals 14 The algorithm sums all the even numbers between 1 and 20 inclusive and then displays then sum.

Exercise Give the flowchart of the program which finds the largest among three different numbers. Write the pseudo-code for the flowchart.

Ans. Input a,b,c if a > b then if a > c then print a endif else if b > c then print b else print c endif endif