0% found this document useful (0 votes)
81 views44 pages

Algorithmic Problem Solving: Algorithmic Problems Algorithms Algorithm A Set of Instructions

The document discusses algorithmic problem solving and related concepts. It begins by defining an algorithm as a well-defined computational procedure that takes inputs and produces outputs. It then discusses different aspects of algorithms like data types, data structures, control structures, pseudo-code, and flowcharts. Examples are provided to illustrate concepts like finding the average of numbers, sorting integers, and calculating revenue from cable installations. The document provides a comprehensive overview of algorithms and problem solving.

Uploaded by

nanjil1984
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
81 views44 pages

Algorithmic Problem Solving: Algorithmic Problems Algorithms Algorithm A Set of Instructions

The document discusses algorithmic problem solving and related concepts. It begins by defining an algorithm as a well-defined computational procedure that takes inputs and produces outputs. It then discusses different aspects of algorithms like data types, data structures, control structures, pseudo-code, and flowcharts. Examples are provided to illustrate concepts like finding the average of numbers, sorting integers, and calculating revenue from cable installations. The document provides a comprehensive overview of algorithms and problem solving.

Uploaded by

nanjil1984
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 44

Algorithmic Problem Solving

In computing, we focus on the type of problems categorically known as algorithmic problems, where their solutions are expressible in the form of algorithms. An algorithm is a well-defined computational procedure consisting of a set of instructions, that takes some value or set of values, as input, and produces some value or set of values, as output. In other words, an algorithm is a procedure that accepts data, manipulate them following the prescribed steps, so as to eventually fill the required unknown with the desired values(s).
Input Algorithm Output

Algorithmic Problem Solving (cont)


An algorithm is a form that embeds the complete logic of the solution. Its formal written version is called a program, or code. Thus, algorithmic problem solving actually comes in two phases: derivation of an algorithm that solves the problem, and conversion of the algorithm into code. The conversion of the algorithm into code is comparatively easier, since the logic is already there it is just a matter of ensuring that the syntax rules of the programming language are adhered to.

Algorithmic Problem Solving (cont)


Algorithms and their alter ego, programs, are the software. The machine that runs the programs is the hardware. Referring to the cook, his view can be depicted as follows:
Ingredients

Recipe (software)

Cooking utensils (hardware)

Ah-gong bah-kut-teh

Algorithmic Problem Solving (cont)


The first documented algorithm is the famous Euclidean algorithm written by the Greek mathematician Euclid in 300 B.C. in his Book VII of the Elements.

The modern Euclidean algorithm to compute gcd (greatest common divisor) of two integers is often presented as followed:

Data Types & Data Structures


In algorithmic problem solving, we deal with objects. Objects are data manipulated by the algorithm. To a cook, the objects are the various types of vegetables, meat and sauce. In algorithms, the data are numbers, words, lists, files, and so on. Algorithm provides the logic; data provide the values. They go hand in hand. Hence, we have this great truth: Program = Algorithm + Data Structures

Data Types & Data Structures (cont)


Data structures refer to the types of data used and how the data are organised in the program. Data come in different forms and types. Most programming languages provides simple data types such as integers, real numbers and characters, and more complex data structures such as arrays, records and files which are collections of data.

Data Types & Data Structures (cont)


Because algorithm manipulates data, we need to store the data objects into variables, and give these variables names for reference. For example, in mathematics, we call the area of a circle A, and express A in terms of the radius r. In programming, we would use more telling variable names such as area and radius instead of A and r in general, for the sake of readability.

Characteristic of an Algorithm
What makes an algorithm an algorithm? There are four essential properties of an algorithm. 1. Each step of an algorithm must be exact. 2. An algorithm must terminate. 3. An algorithm must be effective. 4. An algorithm must be general.
An algorithm should also emphasise on the whats, and not the hows, leaving the details for the program version.

Pseudo-codes and Flowcharts


We usually present algorithms in the form of some pseudo-code, which is normally a mixture of English statements, some mathematical notations, and selected keywords from a programming language. There is no standard convention for writing pseudo-code; each author may have his own style, as long as clarity is ensured.

Pseudo-codes and Flowcharts (cont)


Below are two versions of the same algorithm, one is written mainly in English, and the other in pseudo-code. The problem concerned is to find the minimum, maximum, and average of a list of numbers. Make a comparison.

Pseudo-codes and Flowcharts (cont)


Algorithm version 1:
First, you initialise sum to zero, min to a very big number, and max to a very small number. Then, you enter the numbers, one by one. For each number that you have entered, assign it to num and add it to the sum. At the same time, you compare num with min, if num is smaller than min, let min be num instead. Similarly, you compare num with max, if num is larger than max, let max be num instead. After all the numbers have been entered, you divide sum by the numbers of items entered, and let ave be this result. End of algorithm.

Pseudo-codes and Flowcharts (cont)


Algorithm version 2:
sum count 0 { sum = sum of numbers; count = how many numbers are entered? } min ? { min to hold the smallest value entually } max ? { max to hold the largest value eventually } for each num entered, increment count sum sum + num if num < min then min num if num > max then max num ave sum / count

Pseudo-codes and Flowcharts (cont)


Remarks Note the use of indentation and symbols in the second version. What should min and max be initialised with? Algorithms may also be represented by diagrams. One popular diagrammatic method is the flowchart, which consists of terminator boxes, process boxes, and decision boxes, with flows of logic indicated by arrows.

Pseudo-codes and Flowcharts (cont)


The flowchart below depicts the same logic as the algorithms above.
start
Terminator box

sum count 0 min ? max ?

Process box

Decision box

Yes

end of input? No increment count sum sum + num min num

num < min? ave sum/count No num > max? No end

Yes

Yes

max num

Control Structures
The pseudo-code and flowchart in the previous section illustrate the three types of control structures. They are: 1. Sequence 2. Branching (Selection) 3. Loop (Repetition) These three control structures are sufficient for all purposes.

Examples and Algorithms


Example 1: Compute the average of three integers A possible algorithm: Variables used: enter values for num1, num2, num3 num1 num2 num3 ave ( num1 + num2 + num3 ) / 3 ave print ave A quick peek at the C code: int num1, num2, num3; float ave; scanf ("%d %d %d", &num1, &num2, &num3); ave = (num1 + num2 + num3) / 3.0; printf ("Average is %.2f\n", ave);

Examples and Algorithms (cont)


Another possible algorithm: enter values for num1, num2, num3 total ( num1 + num2 + num3 ) ave total / 3 print ave A quick peek at the C code: int num1, num2, num3, total; float ave; scanf ("%d %d %d", &num1, &num2, &num3); total = num1 + num2 + num3; ave = (float) total / 3; printf ("Average is %.2f\n", ave);
Variables used:
num1 num2 total num3

ave

Examples and Algorithms (cont)


Example 2: Arrange two integers in increasing order (sort) Algorithm A: Variables used: enter values for num1, num2 num1 num2 /* Assign smaller number into final1, larger number into final2 */ final1 final2 if num1 < num2 then final1 num1 final2 num2 else final1 num2 final2 num1 /* Transfer values in final1, final2 back to num1, num2 */ num1 final1 num2 final2 /* Display sorted integers */ print num1, num2

Examples and Algorithms (cont)


Algorithm B: enter values for num1, num2 /* Swap the values in the variables if necessary */ if num2 < num1 then temp num1 num1 num2 num2 temp /* Display sorted integers */ print num1, num2
Variables used:
num1 num2

temp

Examples and Algorithms (cont)


A quick peek at the C code (for Algorithm B): int num1, num2, temp; scanf ("%d %d", &num1, &num2); if (num2 < num1) { temp = num1; num1 = num2; num2 = temp; } printf ("Sorted values are %d and %d\n", num1, num2); Exercise: Can you write out the algorithm to sort three integers?

Examples and Algorithms (cont)


Example 3: Find the sum of positive integers up to n (assuming that n is a positive integer) Algorithm: Variables used: enter value for n n /* Initialise a counter count to 1, and ans to 0 */ count 1; ans 0 count while count <= n do the following ans ans ans + count /* add count to ans */ count count + 1 /* increase count by 1 */ print ans

Examples and Algorithms (cont)


A quick peek at the C code: int n, count, ans; scanf ("%d", &n); count = 1; ans = 0; while (count <= n) { ans = ans + count; count = count + 1; } printf ("Sum is %d\n", ans);

Examples: From Problem Analysis to Coding.


Problem 1: Calculating Revenue X installs coaxial cable for company Y. For each installation, there is a basic charge of $25.00 and an additional charge of $2.00 for each foot of cable. During the month of January, X installed a total of 263 yards of cable at 27 different locations. What was the total revenue X generated for the month?

Examples: From Problem Analysis to Coding (cont).


Problem analysis INPUT Basic service charge: $25.00 Unit cable cost: $2.00 Number of installations: 27 Yards of cable: 263 OUTPUT Revenue generated

Examples: From Problem Analysis to Coding (cont).


One important aspect of problem analysis is generalization. The effort involved in later phases of the problem-solving process demands that the program eventually developed be sufficiently general, that it solves not only the given specific problem but also any related problem of the same kind with little, if any, modification required. INPUT Basic service charge Unit cable cost Number of installations Yards of cable OUTPUT Revenue generated

Examples: From Problem Analysis to Coding (cont).


Design: Algorithm for Revenue Calculation Problem (Sequential Structure) (* Input : A basic ServiceCharge, a UnitCost for cable, number of Installation, and YardsOfCable used. Purpose: This algorithm calculates the revenue generated by the installation of a certain number of yards of cable at a number of locations. For each installation there is a fixed basic service charge and an additional charge for each foot of cable. Output: Revenue generated. *)

Examples: From Problem Analysis to Coding (cont).


1. Enter ServiceCharge, UnitCost, Installation, and YardsOfCable. 2. Calculate FeetOfCable = 3 * YardsOfCable 3. Calculate Revenue = Installation * ServiceCharge + UnitCost * FeetOfCable 4. Display Revenue

Examples: From Problem Analysis to Coding (cont).


Coding: Revenue Calculation Problem
#include <stdio.h> main ( ) { /* Declarations */ int serviceCharge, installations, yardsOfCable; int feetOfCable, unitCost; int totalRevenue;

Examples: From Problem Analysis to Coding (cont).


/* Input information */ printf ("Enter service charge: "); scanf ("%d", &serviceCharge); printf ("Enter cost of one foot of cable: "); scanf ("%d", &unitCost); printf ("Enter number of installations: "); scanf ("%d", &installations); printf ("Enter yards of cables used: "); scanf ("%d", &yardsOfCable);

Examples: From Problem Analysis to Coding (cont).


/* Perform the calculations */ feetOfCable = 3 * yardsOfCable; totalRevenue = serviceCharge * installations + unitCost * feetOfCable; /* Output the results */ printf ("Revenue generated = %d\n", totalRevenue); return 0; /*completed the job */ }

Examples: From Problem Analysis to Coding (cont).


Problem 2: Pollution Index The level of air pollution in the city is measured by a pollution index. Readings are made at 12.00pm at three locations: X, Y and Z. The average of these three readings is the pollution index. A value of 50 or greater for this index indicates a hazardous condition, whereas values lower than 50 indicate safe condition.

Examples: From Problem Analysis to Coding (cont).


Problem analysis INPUT Three pollution readings. Cutoff value to distinguish between safe and hazardous conditions. OUTPUT Pollution index Condition: safe or hazardous

Examples: From Problem Analysis to Coding (cont).


Design: Algorithm for Pollution Index Problem (Selection Structure) (* Input : Three pollution levels and a cutoff value. Purpose: This algorithm reads three pollution levels, Level1, Level2, Level3, and a Cutoff value, It then calculates the pollution Index. If the value of Index is less than Cutoff, a message indicating a safe condition is displayed; otherwise, a message indicating a hazardous condition is displayed. Output: The pollution Index and a message indicating the air quality. *)

Examples: From Problem Analysis to Coding (cont).


1. Enter Level1, Level2, Level3 and Cutoff. 2. Calculate Index = (Level1 + Level2 + Level3) / 3 3. Display Index. If Index < Cutoff then display "Safe condition" else display "Hazardous condition"

Examples: From Problem Analysis to Coding (cont).


Coding: Pollution Index Problem
#include <stdio.h> main () { double level1, level2, level3, cutOff, index; /* Input */ printf ("Enter pollution level 1: "); scanf ("%lf", &level1); printf ("Enter pollution level 2: "); scanf ("%lf", &level2);

Examples: From Problem Analysis to Coding (cont).


printf ("Enter pollution level 3: "); scanf ("%lf", &level3); printf ("Enter cutoff value: "); scanf ("%lf", &cutOff); /* Compute pollution index */ index = (level1 + level2 + level3) / 3.0;

/* Display output */ printf ("The level 1 is %6.3f\n", level1); printf ("The level 2 is %6.3f\n", level2); printf ("The level 3 is %6.3f\n", level3); printf ("The index is %6.3f\n", index);

Examples: From Problem Analysis to Coding (cont).


/* Selection structure */ if (index < cutOff) printf ("Safe Condition\n"); else printf ("Hazadous condition\n"); return 0; /* completed the job */ }

Examples: From Problem Analysis to Coding (cont).


Problem 3: Mean Time to Failure One important statistic that is used in measuring the reliability of a component in a circuit is the mean time to failure, which can be used to predict the circuits lifetime. As part of this evaluation, an engineer tested several of these circuits and recorded the time at which each failed. We wish to develop a program to process the data and determine the mean time to failure.

Examples: From Problem Analysis to Coding (cont).

Problem analysis INPUT A collection of numeric values (number unknown). OUTPUT The number of values The mean (average) of the values

Examples: From Problem Analysis to Coding (cont).


Design: Algorithm for Mean Time to Failure Problem (Repetition Structure) (* Input : A collection of failure times. Purpose: This algorithm reads failure times, count them, and find the mean time to failure (MeanFailTime). FailTime represents the current failure time entered, NumTimes is the number of failure times, and Sum is their sum. Values are read until an end-of-data flag is encountered. Output: MeanFailTime and NumTimes. *)

Examples: From Problem Analysis to Coding (cont).


1. Initialize NumTimes to 0 and Sum to 0.0. 2. Enter the first value for FailTime. 3. While FailTime is not the end-of-data flag, do the following: a. Increment NumTimes by 1. b. Add FailTime to Sum. c. Enter next value for FailTime. 4. If NumTimes 0 then a. Calculate MeanFailTime = Sum /NumTimes b. Display MeanFailTime and NumTimes. else display a "No Data" message.

Examples: From Problem Analysis to Coding (cont).


Coding: Mean Time to Failure Problem #include <stdio.h> #define end_of_data 999 main () { int failTime, numTimes = 0; double sum = 0.0, meanFailTime; printf ("Enter first value of failure time: "); scanf ("%d", &failTime); /* a constant */

Examples: From Problem Analysis to Coding (cont).


/* A loop to read in failure times */ while (failTime != end_of_data) { numTimes = numTimes + 1; sum = sum + (double) failTime; printf ("Enter next failure time (999 to stop): "); scanf ("%d", &failTime); }

Examples: From Problem Analysis to Coding (cont).


/* To calculate the mean of failure if there is input data */ if (numTimes > 0) { meanFailTime = sum / (double) numTimes; printf ("The number of failure times = %5d\n", numTimes); printf ("The mean of failure = %6.3f\n", meanFailTime); } else printf ("No input data\n"); return 0; /* completed the job */ } /* end main */

You might also like