Docsity

Algorithms II: Building Blocks, Pseudo Code, and Flowcharts, Slides of Introduction to Computing

Partial preview of the text

Download Algorithms II: Building Blocks, Pseudo Code, and Flowcharts and more Slides Introduction to Computing in PDF only on Docsity!

CS101 Introduction to Computing

Lecture 17

Algorithms II

Focus of the last lecture was on Algorithms

Became familiar with the concept of algorithms:

  • What they are? (SEQUENCE OF STEPS)
  • What is their use?
  • What are their types?
  • What are the techniques used for representing them? - Pseudo code - Flowcharts - Actual code

Algorithm Building Blocks

All problems can be solved by employing any one of the following building blocks or their combinations

  1. Sequences
  2. Conditionals
  3. Loops

5

Start or stop

Process

Input or output

Connector

Decision

Flow line

Off-page connector

Review of

Flowchart

Elements

Sequences

A sequence of instructions that are executed in the precise order they are written in:

statement block 1 statement block 2 statement block 3

7

statement block 1

statement block 2

statement block 3

Conditionals

Select between alternate courses of action depending upon the evaluation of a condition

If ( condition = true )

statement block 1

Else

statement block 2

End if

8

statement block 1

condition

True False

statement block 2

We will now present the algorithm for a problem whose solution is familiar to us

We will first go through the problem statement and then present the algorithm in three different formats:

  1. Pseudo code
  2. Flowchart
  3. Actual code

Problem Statement

Convert a decimal number into binary

We did write down the pseudo code for this problem last time

Lets do it again, and in a slightly more formal way

Solution in Pseudo Code

  1. Let the decimal number be an integer x, x > 0
  2. Let the binary equivalent be an empty string y
  3. Repeat while x > 0 {

Determine the quotient & remainder of x ÷ 2 y = CONCATENATE( remainder, y ) x = quotient }

  1. Print y
  2. Stop

Tips on Writing Good Pseudo Code

  • Use indention for improved clarity
  • Do not put “code” in pseudo code – make your pseudo code language independent
  • Don’t write pseudo code for yourself – write it in an unambiguous fashion so that anyone with a reasonable knowledge can understand and implement it
  • Be consistent
  • Prefer formulas over English language descriptions

17

Start

Find quotient & remainder of x ÷ 2

Get x

x >0?

Print y

Stop

y = CONC(remainder, x ) x = quotient

x is the decimal number y is the binary equivalent

Flowchart of Decimal to Binary Conversion

Yes

No

(^19)

Decimal to Binary Conversion in JavaScript

NOTE: Don’t worry if you don’t understand this code for now; you will - later!Docsity.com

Another Example: Sorting

Sort the following objects w.r.t. their heights