43
Algorithm - a finite set of instructions that specify a sequence of operations to be carried out in order to solve a specific problem or class of problems. Flowchart - a common method for defining the logical steps of flow within a program by using a series of symbols to identify the basic input, Process and Output (IPO’s) function within a program. Advantages and limitations of flowcharts Advantages: 1. They can be learned and applied without formal knowledge of a programming language. 2. It enforces users to give attention to significant matters over the less significant ones. 3. It provides an alternative to the usual narrative description of a system or program. 4. Flowcharts are easier to understand than a program written in a particular programming language. Limitations: 1. Flowcharts do not represent a programming language and are more of a person-to-person than a person to

Algorithm (Full)

  • Upload
    zing-ko

  • View
    214

  • Download
    0

Embed Size (px)

DESCRIPTION

ALGO

Citation preview

Page 1: Algorithm (Full)

Algorithm- a finite set of instructions that specify a sequence of operations

to be carried out in order to solve a specific problem or class of problems.

Flowchart- a common method for defining the logical steps of flow within a

program by using a series of symbols to identify the basic input, Process and Output (IPO’s) function within a program.

Advantages and limitations of flowchartsAdvantages:

1. They can be learned and applied without formal knowledge of a programming language.

2. It enforces users to give attention to significant matters over the less significant ones.

3. It provides an alternative to the usual narrative description of a system or program.

4. Flowcharts are easier to understand than a program written in a particular programming language.

Limitations:1. Flowcharts do not represent a programming language and are

more of a person-to-person than a person to computer means of communication. A computer cannot accept a program described in flowcharting form.

2. Since thinking in graphic terms is not normal, flowcharts cannot be viewed as a natural means of communication.

3. It does not convey why a given set of operations is made. Flowcharts only portray how.

Page 2: Algorithm (Full)

4. Flowcharts do not highlight the important details since each step receives as much attention in a flowchart as any others.

Types of FlowchartsSystem Flowchart

A system flowchart is a graphic representation of the procedures involved in converting data on input media to data in output form. It illustrates which data is used or produced at various points in a sequence of operations. System flowcharts portray the interaction among data, hardware, and personnel. The emphasis is on the media used and the work stations through which the data passes. Since it illustrates more on the components of the system used, little is shown about how processing will be accomplished.

Systems flowcharts are graphic illustrations of the physical flow of information through the entire accounting system.  A systems flowchart is commonly used in analysis and design.  Flowlines represent the sequences of processes, and other symbols represent the inputs and outputs to a process.  Accountants use system flowcharts to describe the computerized processes, manual operations, and inputs and outputs of an application system.  Auditors use system flowcharts to identify key control points in an accounting system’s internal control structure. 

Program Flowchart

Page 3: Algorithm (Full)

A program flowchart describes graphically in detail the logical operations and steps within a program and the sequence in which these steps are to be executed for the transformation of data to produce the needed output.A system flowchart describes the flow of data through all parts of a system. A program flowchart describes what takes place in a program; it displays specific operations and decisions, and their sequences within the program run or phrase.

A system flowchart represent an application in which data provided by source media is converted to final media. Therefore, emphasis is place on the media involved and on the work stations through which they pass. The actual operations that must be performed are described briefly.

Symbols depicting these documents and operations are designed so that when used in a system flowchart they are meaningful without comment or text. When text is placed within the symbol, the flowchart takes on a specific application meaning.

Page 4: Algorithm (Full)

Basic Symbols in Flowcharting

Symbols What it represents

Page 5: Algorithm (Full)

Terminal

Used to signify the beginning and end of flowchart.

Preparation/Initialization

Signifies the preparation of a variable.Used to select initial conditionsUsed to represent instructions or group of instructions that will alter or modify a program’s course of execution.

Input/Output

Shows input and output. Data are to be read into the computer memory from an input device or data are to be passed from the memory to an output device.

Processing

Performs any calculations that are to be done

DECISION

Signifies any decisions that are to be doneTwo alternative execution paths are possible. The path to be followed is selected during the execution by testing whether or not the condition specified within the outline is fulfilled.Shows the entry or exit point of the flowchartA non-processing symbol used to connect one part of a flowchart to

Page 6: Algorithm (Full)

On-page connectoranother without drawing flowlines.Conserves space by keeping related blocks near one another, reduced the number of flowlines in complex programs, and eliminated cross lines from taking place.

Off-page connector

Designates entry or exit from one page when a flowchart requires more than one page.

Flowlines

Signifies the process that is to be executed next

The following are some guidelines in flowcharting:

a. In drawing a proper flowchart, all necessary requirements should be listed out in logical order.

b. The flowchart should be clear, neat and easy to follow. There should not be any room for ambiguity in understanding the flowchart.

c. The usual direction of the flow of a procedure or system is from left to right or top to bottom.

d. Only one flow line should come out from a process symbol.

  or       

e. 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.

Page 7: Algorithm (Full)

             

f. Only one flow line is used in conjunction with terminal symbol.

                

g. Write within standard symbols briefly. As necessary, you can use the annotation symbol to describe data or computational steps more clearly.

h. If the flowchart becomes complex, it is better to use connector symbols to reduce the number of flow lines. Avoid the intersection of flow lines if you want to make it more effective and better way of communication.

i. Ensure that the flowchart has a logical start and finish. j. It is useful to test the validity of the flowchart by passing

through it with a simple test data.

 Notations Commonly Used in Flowcharting

Notation Meaning Notation Meaning+ Addition = or EQ Equal to- Subtraction > or GT Greater than

Page 8: Algorithm (Full)

* Multiplication < or LT Less than/ Division <> or = or NE Not equal to

** or [ or Exponentiation >= or GE Greater than or equal to

: Comparison <= or LE Less than or equal to( ) Grouping Y Yes| Logical or N No& Logical and EOF End of fileb Blank

FEW EXAMPLES ON FLOWCHARTING

Now we shall present few examples on flowcharting for proper understanding of this technique. This will help in student in program development process at a later stage.

Example 1

Draw a flowchart to find the sum of first 50 natural numbers.

Page 9: Algorithm (Full)

 

Example 2

Draw a flowchart to find the largest of three numbers A,B, and C.

Page 10: Algorithm (Full)

Example 3

Draw a flowchart for computing factorial N (N!)

Page 11: Algorithm (Full)

Where N! = 1 ´ 2 ´ 3 ´ …… N .

 

Flowcharting Examples Using Sequential Structure1. Draw a flowchart for asking and inputting a number

Page 12: Algorithm (Full)

2. Draw a flowchart that will compute for the sum of three numbers.

3. Draw a flowchart that will compute for the average of two numbers.

Start

Read Num

Display Num

End

Start

Print SUM

End

SUM = A+B+C

Page 13: Algorithm (Full)

4. Draw a flowchart that will compute for the area of the circle when the user inputs the radius.

Start

Print AVE

End

AVE = (A+B)/2

Start

Print AREA

End

AREA = 3.14*R*R

Read R

Page 14: Algorithm (Full)

4. Draw a flowchart that will convert the inputted number in inches to its equivalent in feet.

Flowchart Examples Using Selection/Branching Structure1. Draw a flowchart that will input values for A and B. Compare two values inputted and print which of the values is higher including the remark “Higher”.

Start

Print I

End

I = F/12

Read F

Start

Input a, b

a>b

Print a, “Higher”

T

Print b, “Higher”

F

End

Page 15: Algorithm (Full)

2. Draw a flowchart that will input a grade of student and determine whether the grade is passed or failed. Print the grade and remarks.

3. Draw a flowchart that will determine if the number inputted by the user is positive or negative.

Start

Input grade

Grade>=60

Print grade, “Passed”

T

Print grade, “Failed”

F

End

Start

Input num

Num>0

Print “Positive”

T

Print “Negative”

F

End

Page 16: Algorithm (Full)

4. A company plans to give a year-end bonus to each of its employee. Draw a flowchart which will compute the bonus of an employee. Consider the following conditions: If the employee’s monthly salary is less than 2,000 pesos, the bonus is 50% of the salary; for employees with salaries greater than 2,000 pesos, the bonus is 1,500 pesos. Print the name and the corresponding bonus for each employee.

Start

Bonus = 0

Read Name, Salary

Salary< 2000

Bonus = 0.50* Salary

Print Name, Bonus

End

TF

Bonus = 1500

Page 17: Algorithm (Full)

5. Draw a flowchart that will input values for a and b. Compare two values inputted and print which of the values is higher including the remark “Lower”.

Flowchart Examples Using Repetition/Looping Structure1. Draw a flowchart that will count from 1 to 10 and print each number.

Start

Input a, b

a<b

Print a, “Lower”

T

Print b, “Lower”

F

End

Page 18: Algorithm (Full)

2. Draw a flowchart that will count from 5 to 1 and print each number.

Start

C = 0

C<10

C = C+1

Print C

T

FEnd

Page 19: Algorithm (Full)

3. Draw a flowchart that will count from 1 to 10 and get the sum of the numbers. Print each number and the sum of the numbers.

T

Start

C = 5

C = 0

C = C-1

Print C

FEnd

Page 20: Algorithm (Full)

3. Draw a flowchart that will count from 1 to 5 and get the average of the numbers. Print each number and the average of the numbers.

5. Draw a flowchart to find the sum of first 50 natural numbers.

Start

C = 0Sum = 0

C<10

C = C+1Sum = Sum +C

Print C

T

FEndPrin

t Sum

T

Start

C = 0, Sum = 0Ave = 0

C<10

C = C+1Sum = Sum +C

Print C

FEndPrin

t Ave

Ave = Sum/10

Page 21: Algorithm (Full)

Flowchart Examples Using Combination Structure

Page 22: Algorithm (Full)

1. Draw a flowchart to find the largest of three numbers A, B, and C.

2. The initial value of the radius (R) of a circle is equal to 1 unit and each succeeding radius is 1 unit greater than the value before it. Draw a flowchart to compute the area of the circle starting with R=1

Page 23: Algorithm (Full)

up to R=5, then print each radius and the corresponding area of a circle.

Start

Pi = 3.11416R = 1

Area = Pi*R*R

Print R, Area

R = R+1

R<=5

EndF

T

Page 24: Algorithm (Full)

3. Draw a flowchart that will compute for the sum of the odd numbers from 1 to 10.

Start

CTR = 1SUM = 0

CTR mod 2 = 1

CTR = CTR + 1N

YSUM = SUM + CTRCTR = CTR+1 CT

R=10

Print SUM

End

N

Y

A

A

Page 25: Algorithm (Full)

4. Draw a flowchart that will count the sum of all even numbers from 1 to 10.

Start

CTR = 1SUM = 0

CTR mod 2 = 1

CTR = CTR + 1Y

NSUM = SUM + CTRCTR = CTR+1 CT

R=10

Print SUM

End

N

Y

A

A

Page 26: Algorithm (Full)

5. Draw a flowchart that will read and print the names and individual scores of 100 students for a particular examination. Also, determine their average score, and print it out.

Start

CTR = 0SUM = 0

Read Name, Score

Print Name, Score

SUM = SUM + SCORE

CTR = 100

CTR = CTR + 1

A

AVE = SUM/CTR

Print AVE

END

A

Page 27: Algorithm (Full)

Loops and CountersFrequently a problem will require that a process be repeated a

certain number of times. One way to accomplish this repetition is for the algorithm to transfer control of logic flow from the end of the process back to its beginning. The flowchart of such an algorithm will contain a loop or a sequence of steps to be executed a specified number of times.

Looping is used when it is desired to make the same calculation on more than one set of data. It consists of repeating a program, or a section of a program, and substituting new data fir processing since they provide efficient means of processing various sets of data with the same program segment.

The most common mistakes in writing loops have to do with the first and last passes through the loop. The first set of data is skipped, the loop is terminated before the last operation is completed, or the loop is repeated too many times. To avoid these mistakes the programmer should check carefully the operations performed during the first and last passes through the loop.

It is important to have algorithms that do not get “hung up” in loops and iterated or pass through the loops indefinitely. A common problem in programming is the writing of loops that, with certain inputs, will cause the system to loop forever. This kind of error is more likely to occur when there are “nested loops” or loops contained within other loops.

Counters

Page 28: Algorithm (Full)

Somewhere in any loop a loop-terminating condition must reside, and the loop is then executed until the decision is made by the loop-terminating condition to exit from the loop.

A counter is set up in any program to keep track of the number of times the program segment is repeated. The program can then be terminated after the completion of a predetermined number of passes. Prior to the execution of counting, all counters should be initialized (usually to zero) before the loop is executed. For instance, if a program is supposed to read and print five data values, a counter may be set up in the program which counts the number of data values; after a data value is read and printed, the counter is increased by one. Before a new data value is allowed to be read, a conditional transfer may be used to determine whether or not the desired amount of data has been reached. If it has, the program is terminated; otherwise an unconditional transfer causes the computer to repeat the input/output and other processing operations.

Illustrative Problem.Given a set of 5 numbers that include both positive and negative

data values. Draw a to read in these values one at a time and count the number of positive values (including zero values) and the number of negative values found in the set. After the required values are determined, print out these counted values.

Page 29: Algorithm (Full)

Steps in Loop Control1. Initialization – the value of the counter used is initially

set equal to zero (or one). This process is always dome outside the loop.

2. Test for limit conditions – before logic flow gets out of a loop, a loop-terminating condition must first be satisfied. The process of testing is usually found either at the beginning or at the end of the loop.

3. Incrementation – after each loop is executed, 1 is added to the counter. Thus the counter reflects the number of

Start

NNEG = 0NPOS = 0

Read NO

NO<0

NPOS = NPOS + 1

B

NNEG = NNEG + 1

NVAL = NNEG + NPOS

NVAL=5

APrint NNEG, NPOS

End

B

NY

YN

Page 30: Algorithm (Full)

times the operation has been performed. Note that the process of incrementation is always done within the loop.

Loops and AccumulatorsIn many problems it would often be required to determine the

sum of certain numerical quantities that are read or calculated one at a time. This is accomplished by first choosing a variable, say SUM, and initializing it to zero. As the flow of logic through the flowchart loop is followed, a repetitive operation of adding each numerical quantity to the sum is performed until the loop is terminated. The variable used is thereby continuously accumulating the numerical quantities and is thus called an accumulator. The final value accumulated will be the sum of all the numerical quantities.

Illustrative Problem:Draw a flowchart to compute and print the sum of the squares

of positive integers from 1 to 100.

Start

K = 1SUM = 0

SUM = SUM + K2

K = K + 1

K<=100

AY N Print

SUM

End

A

Page 31: Algorithm (Full)

In the example, the test limit condition used is K>=100. prior to executing the looping process, the variable called SUM (the accumulator) is initialized to zero. Similarly, K, during the process of looping, represents the integers from 1 to 100. Determining the sum of the squares of integers starts when the value of K square is added to the initial value (zero) of the accumulator. The variable K is then incremented by one and before the same operation is repeated, a test is made to determine if K is less than or equal to 100, the limiting condition. The test is contained in a decision block which will have to be answered by either yes or no. As long as the value of K is less than or equal to 100, the process of looping continues. Consequently, the variable SUM also continuously accumulates. The process of looping back and accumulating only ends when the answer to the question in the decision box is no. Prior to program termination, the final value stored in the accumulator is printed out. To visualize the whole process of looping, accumulating, incrementing and testing for limit conditions, it is suggested that the student actually trace out the given flowchart. Switches

In some instances, an algorithm for a particular problem will require a change from one type of processing operation to another. Variables are set or inputted to at selected locations within a flowchart for the sole purposed of determining the path to be taken at another point. To perform this requirement, switches are used. A switch (or flag) is a selected location within a flowchart which causes a shift from one type of processing flow to another. Switches give the user or programmer the opportunity to direct the logic flow while the algorithm is being executed. Usually, the flow of processing is done alternately, depending on the value of the switch which is either zero or one.

Page 32: Algorithm (Full)

Illustrative ProblemWith the use of switches, draw a flowchart to determine and

print out the sum of all even and odd integers from 1 to 10.

The desired algorithm for the problem stated may be portrayed by the flowchart shown above. The algorithm starts by initializing to zero the switch (SW) and the accumulators for odd and even integers (SUMODD and SUMEVN). Since the first integer is 1, the value of NUM is set to 1. Note that when the loop terminates, the value of NUM should be 10.

Start

SW = 0

NUM = 1

SUMEVN = 0SUMODD = 0

SW = 0

SUMEVN = SUMEVN + NUM

SW = 0

A

SUMODD = SUMODD + NUM

SW = 1

NUM=10

Print SUMEVN, SUMODD

NUM = NUM + 1

B

A

AN

Y

N

Y

Page 33: Algorithm (Full)

As the flowchart is traced, it will be noted that during each looping process a shift from one type of processing flow to another is performed. The flow of processing is done alternately, depending on the value of SW which is either zero or one. Since SW is zero during the first pass, processing flow shifts towards the left and the accumulator for odd integers is incremented by the value of NUM or 1. The switch is then set to 1, and before the next loop is executed, a test is made to determine if the last value (10) has already been encountered. However, since the value initially encountered is 1, looping continues. Prior to the start of the next loop, the value of NUM is incremented by 1 to represent the next integer which is 2. The next pass through the loop directs processing flow towards the another path (towards the right) since the value of SW is no longer equal to zero. The new value of NUM, which is 2 (an even integer) is then added to the accumulator for even integers. Then the switch is set back to zero. The same process of looping which involves testing, incrementing and setting of switches to either one or zero is repeated until the value of NUM is equal to 10. The looping process is then terminated and the accumulated values of even and odd integers are printed out. If the flowchart is correctly traced out, the accumulators for odd and even integers should be printed out as 25 and 30, respectively.

Number SearchingMany problems in data processing require the searching of the

smallest (or largest) value in a set of numbers and then sorting it out in either ascending or descending order. Such problems are usually encountered in the preparation of student grades, examination reports, statistical analysis and etc. There are different ways by which sets of numbers are stored, searched, and sorted out.

Page 34: Algorithm (Full)

Since related values all need to be stored in memory, the usual approach is reading in values to one specific variable name will not be functional since there will be a need to recall later all values read. Values inputted in this manner results in only one value retained in memory – the last value stored. This type of problem requires reading in and storing an array, or group of locations required for each element read into memory is made available. Any value or array element read into memory can then be recalled from memory anytime when needed for processing.

Illustrative ProblemDraw a flowchart to read into memory a given set of numbers (one-dimensional array) and determine the smallest value in the set.

Start

I = 1

Define the A-array

Read N

Read A(I)

I = I+1

I>N

B

Y

33

N

B

I = 2AMIN = A(1)

AMIN<=A(I)

I = I + 1

I>N

Print AMIN

End

44

N

AMIN = A(I)

44

N

Page 35: Algorithm (Full)

A suitable flowchart to represent the required algorithm is shown above. The flowchart is divided into two portions. One portion defines the array and reads into memory all the elements of the array. The second portion determines the smallest value in the array. In the portrayed algorithm the number of array elements is defined by the variable N which is first read. This value is used as a limiting condition to control the first looping sequence. The process of reading each element is done within the loop until all values are read into memory. Note that the array elements read into memory are identified as subscripted variables. The subscripts are defined by the variable I which increments from 1 to N. The first element of the array is immediately assumed to be the smallest value and is then compared with the second element, the third and etc. This process of comparison is done to determine which of the two values is the smaller value. If a much smaller value is encountered during the process of comparison, that value is then designated as the new smaller value. This new value is again compared with the succeeding values left to determine if there would be another much smaller value. The whole process of comparison, which is performed within the loop, continues until there are no more values to compare with the assumed smallest value. The last value store into the variable called AMIN is then the smallest value which is also printed out prior to program termination.

Page 36: Algorithm (Full)