0% found this document useful (0 votes)
26 views

Week1 Combine

The document describes the program development process, which involves multiple steps to solve a problem and develop a computer program. It involves first understanding the problem, devising an algorithm to solve it through a problem-solving phase, and then implementing the algorithm into a program through coding, testing, and debugging during the implementation phase. As an example, it walks through solving the problem of calculating the distance between two points, including clearly defining the problem, describing the inputs and outputs, working through an example by hand, writing out precise step-by-step instructions, and generalizing the steps into a reusable algorithm. The key aspects are breaking the problem down into well-defined steps and being meticulous in writing out instructions a computer can follow precisely

Uploaded by

raley
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Week1 Combine

The document describes the program development process, which involves multiple steps to solve a problem and develop a computer program. It involves first understanding the problem, devising an algorithm to solve it through a problem-solving phase, and then implementing the algorithm into a program through coding, testing, and debugging during the implementation phase. As an example, it walks through solving the problem of calculating the distance between two points, including clearly defining the problem, describing the inputs and outputs, working through an example by hand, writing out precise step-by-step instructions, and generalizing the steps into a reusable algorithm. The key aspects are breaking the problem down into well-defined steps and being meticulous in writing out instructions a computer can follow precisely

Uploaded by

raley
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

Program Development Process [Prasanna Ghali]

Program Development Process


Computers are used to solve problems. However, before a computer can solve a problem, it must
be given instructions for how to solve the problem. A professional programmer usually doesn't
just sit down at a computer keyboard and start typing out. Instead, program development is a
multi step process that requires the programmer to understand the problem, develop an algorithm,
write the program, and then test the program. When you - the programmer - is given the task of
developing a program, you'll be given a program requirements statement that specifies what the
proposed program is to accomplish and the design of any program interfaces (that is, what sort of
input the program would consume and what sort of output the program would produce). You
would also receive an overview of the complete project so that you'll understand how your part
fits into the whole. Your job then is to determine how to take the inputs you're given and convert
them into the specified outputs. This is known as program design and sometimes colloquially
referred to as coding and sometimes as programming.

To help structure program development, the program design process can be divided into two
general phases: the problem-solving phase and the implementation phase, each of which is further
subdivided into multiple steps. A high-level view of the program design process is illustrated in
the following figure.

The problem-solving phase devises an algorithm that expresses a solution to the problem. This is
the most critical component of the program design process because it provides a solution to the
problem independent of any programming language. This phase is divided into six steps that
collectively analyze the problem, work the problem by hand for selected input(s), find pattern(s)
from the hand-computations to devise a step-by-step solution, and perform tests to ensure that
the solution is correct.

The implementation phase uses a specific programming language to convert the algorithm
received from the problem-solving phase into a working computer program. This phase
comprises of three steps: coding, testing, and debugging.

1 / 13
Program Development Process [Prasanna Ghali]

Problem-Solving Phase: Distance problem


The six steps of the problem-solving phase are:

1. Understand the problem clearly.


2. Describe the input and output information.
3. Work the problem by hand for a simple data set.
4. Decompose solution from previous step into step-by-step details.
5. Generalize the steps into an algorithm.
6. Test the algorithm with a broader variety of data.

Step 1: Problem statement

The first step to solving any problem is to understand it. Begin by stating the problem clearly. It is
extremely important to give a clear, concise problem statement to avoid any misunderstandings.
To give you an idea of how this process works, a fairly simple problem from geometry and
trigonometry is to find the distance between two points. Are you supposed to compute the distance
for two points on a number line [one-dimensional], or on a plane [two-dimensional], or in space
[three-dimensions], or in an abstract dimensional space? Once the problem is exactly
specified [in your case, the problem is to compute the distance between two-dimensional points],
begin by writing a concise problem statement:

As this example shows, even the simplest problem requires clarification. Imagine, how many
questions you'd have for a problem statement consisting of hundreds or even thousands of
detailed statements.

Step 2: Input/Output description

The second step is to carefully describe the information that is given to solve the problem and
then identify the values to be computed. These items represent the input and the output for the
problem and collectively can be called input/output (I/O).

For many problems, a diagram that shows the input and output is useful. At this point both the
solution and the program are an abstraction because you're not defining the steps to determine
the output; instead, you're only showing the information that is used to compute the output. The
I/O diagram for the distance between two points and follows:

Step 3: Hand example

The third step is to work the problem by hand or with a calculator, using a simple set of data. This
is a very important step, and should not be skipped even for simple problems. This is the step in
which you work out the details of the problem solution. Often this step will involve drawing a
diagram of the problem at hand, in order to work it precisely. The more precisely you can perform
this problem [including the more precisely you can draw a diagram of the situation if applicable],
the easier the remainder of your steps will be. A good example of the sort of picture you might
draw would be the diagrams drawn in many science classes [especially physics classes].

2 / 13
Program Development Process [Prasanna Ghali]

To compute the distance between two points in a plane, the solution by hand would begin with
points and having the following coordinates:

Based on your knowledge of analytic geometry, you would first draw a right triangle connecting
points and , as shown in the following figure, and then specify the distance between the two
points as the right triangle's hypotenuse.

Using the Pythagorean theorem, you would then compute the distance with the following
equation:

If you get stuck at this step, it typically means one of two things. The first case is that the problem
is ill-specified - it is not clear from the problem statement what you are supposed to do. If you
cannot take a simple set of numbers and compute the output [either by hand or with a
calculator], then you're no where close to implementing a program to solve the problem. In such
a situation, you must resolve how the problem should be solved before proceeding. In the case of
a classroom setting, this resolution may require asking your professor or TA for more details. In a
business setting, asking your technical lead or customer may be required. If you're solving a
problem of your own creation, you may need to think harder about what the right answers should
be and redefine your definition of the problem.

The second case where Step is difficult is when you lack domain knowledge - the knowledge of
the particular field or discipline the problem deals with. If you don't have knowledge of analytic
geometry for the distance example, that would be an example of lacking domain knowledge - the
problem domain is mathematics, and you are lacking in math knowledge. No amount of
programming expertise nor effort [that is, "working harder"] will overcome this lack of domain
knowledge. Instead, you must consult a source with domain expertise - a math textbook, website,
or an expert. Once you have the correct domain knowledge, you can proceed with solving your
instance of the problem. Note that domain knowledge may come from domains other than math.
It can come from any field, as programming is useful for processing any sort of information.

3 / 13
Program Development Process [Prasanna Ghali]

Step 4: Writing precise instructions for solving particular instance

For this step, you must think about what you did to solve the problem in step , and write down
the individual steps to solve that particular instance. That is, you must write down a clear step-by-
step outline of the solution that could be followed by anybody else to reproduce your answer for
the particular problem instance solved in Step . If you do multiple instances in Step , you'll
repeat Step multiple times as well, once for each instance you did in Step . If an instruction is
somewhat complex, that is all right, as long as the instruction has a clear meaning - these complex
steps will be solved separately later on by turning them into their own programming problems.

The difficult part of Step is thinking about exactly what you did to accomplish the problem. The
difficulty here is that it is very easy to mentally gloss over small details, "easy" steps, or things that
you do implicitly. Implicit assumptions about what to do, or relying on common sense lead to
imprecise or omitted steps. The computer will not fill in any steps you omit, thus you must be
careful to think through all the details. This difficulty is best illustrated by the exercise of making a
peanut butter and jelly sandwich. Here's my step-by-step outline for preparing such a sandwich:

1. Grab some bread


2. Toast the bread
3. Get some peanut butter and jelly
4. Spread the peanut butter on the bread
5. Spread the jelly on top of the peanut butter

Most humans would be able to follow these instructions to make a sandwich since they have the
ability to understand the context, the ability to "read between the lines", and based on the context
or situation determine the meaning of what was said. This is a skill that computers lack. A
computer would not be able to parse meaning from "Grab some bread". If computers could
speak, the litany of questions asked by a computer would include: What is "bread"? What does
"grab" mean? "Grab" from where? What is "toast"? How to "toast"? When to know bread is
toasted? What is "peanut butter"? And, "jelly"? Where are they stored? How to "Get some peanut
butter and jelly?" What does "Spread" mean and so on. Since computers are completely literal -
they do exactly what they're told and nothing more - the step-by-step outline must be precise,
specific, and thorough.

Returning to the distance problem, the exact steps for computing the distance between two
points in a plane would look like this:

4 / 13
Program Development Process [Prasanna Ghali]

The steps are very precise leaving nothing to guess work. Anyone who can perform basic
arithmetic can follow these steps to get the right answer. Computers are very good at arithmetic,
so none of these steps is even complex enough to require splitting into a subproblem.

Step 5: Generalize specific steps into algorithm

Once you've solved one or more instances of the problem, you're ready to generalize the steps
into an algorithm. You've to use the insights gained from solving specific instances to find a
pattern that allows you to solve the problem for possibly infinite instances. This generalization
typically requires two activities. First, you must take particular values that you used and replace
them with mathematical expressions of the input parameters. The second activity to generalize
steps requires you to find repetition of certain patterns - that is, find particular steps that are
repeated over and over. You must generalize how many times to repeat the pattern, as well as
what the individual steps of the pattern are. In the current distance example, repetition is
unnecessary - a second example is shown later on to illustrate how finding repetition of certain
steps will help devise an algorithm.

For simple problems such as the distance problem, the algorithm can be listed as operations that
are performed one after another. Replacing the particular values used with mathematical
expressions of the input parameters, steps , , , and are combined into a single step.

5 / 13
Program Development Process [Prasanna Ghali]

Step 6: Tracing the algorithm

The final step of the problem-solving phase is to test the algorithm devised to solve the problem.
The algorithm must first be tested with the hand examples from Step because those results are
already computed. Once the algorithm works for the hand-calculated examples, it should also be
tested with additional sets of data to be sure that the algorithm works for other valid data sets.

receives the locations of two points and in a plane and produces as


output, , the distance between the two points. You show how the algorithm executes if
the input points have locations and . Simulating the execution of an algorithm for
a specific input is called a trace. At line , the algorithm computes - the width of the right
triangle generated by points and . At line , the algorithm computes - the height of
the right triangle generated by points and . The effect is to assign values and to
and , respectively. At line , the algorithm computes the length of the hypotenuse of the
triangle, which is equal to the distance, , between points and . At this point, the
algorithm updates with the value which has an approximation of .

Although the two-dimensional plane consists of four quadrants, the previous test of the algorithm
uses points located in the first quadrant. The trace of the algorithm for the second quadrant
begins by choosing a pair of second quadrant points and . At line , the
algorithm computes as . This value should be problematic since it is geometrically
impossible for the length of triangle's edge to be negative. That is, until you notice that in line ,
the right triangle's hypotenuse is computed using the square of - which is always a positive
value. At line , the algorithm computes as . The resultant distance in line is
updated with the expected approximation .

The algorithm is traced for points in the third-quadrant by setting values and
and for points in the fourth-quadrant by setting values and . In
both cases, the distance in line is updated with the expected value .

The distance between two points located at the same position must be . Tracing the algorithm
for two coincident points leads to lines and assigning to both and , and
subsequently, line evaluating this as which is equivalent to .

It is well known that the square root of a negative number cannot be a real number.
Mathematicians have developed a system of imaginary numbers to express square roots of
negative numbers. However, computers are only able to represent a range of integral numbers
and a subset of real numbers. And, hence it is important for programmers to test whether the
algorithm is being asked to execute a step requiring the computation of the square root of a
negative number. In your case, line computes the square root of a value that is obtained by
adding two positive numbers [why?] and therefore will never compute the square root of a
negative number.

Implementation Phase: Distance problem


The three steps of the implementation phase consist of:

1. Coding the algorithm.


2. Testing the code.
3. Debugging the code if step doesn't match output generated by hand-calculations.

6 / 13
Program Development Process [Prasanna Ghali]

Step 1: Coding

After an algorithm has been devised in Step of the problem-solving phase that solves the
original problem and after it has been thoroughly hand-tested in Step of the problem-solving
phase, the solution can be coded for execution by a computer. If the algorithm has been given in
sufficient detail, much of the coding will be routine. However, every programming language has
its own peculiarities, so additional issues will have to be dealt with.

is converted to a C program so that you can use a computer to perform


the computations:

1 /*
2 Source file: distance.c
3
4 This program prompts user to enter source and destination points P and Q;
5 computes the distance between points P and Q using Algorithm d(P,Q);
6 and prints the computed distance to standard output.
7
8 To compile using GCC on Linux:
9 gcc -std=c11 -pedantic-errors -Wstrict-prototypes -Wall -Wextra -Werror
distance.c -o dist-gcc.out -lm
10 To compile using clang on Linux:
11 clang -std=c11 -pedantic-errors -Wstrict-prototypes -Wall -Wextra -Werror -
lm distance.c -o dist-clang.out -lm
12 To compile using Microsoft C compiler (in Windows):
13 cl /EHsc /TP /Za /Fedist-msvc.exe distance.c
14 */
15
16 #include <stdio.h>
17 #include <math.h>
18
19 int main(void) {
20 // input portion
21 double px, py, qx, qy;
22 printf("Enter point P: ");
23 scanf("%lf %lf", &px, &py);
24 printf("Now, enter point Q: ");
25 scanf("%lf %lf", &qx, &qy);
26
27 // computations
28 double width = qx - px;
29 double height = qy - py;
30 double distance = sqrt(width*width + height*height);
31
32 // output portion
33 printf("Distance from P(%.3f, %.3f) to Q(%.3f, %.3f) is %.3f\n",
34 px, py, qx, qy, distance);
35 return 0;
36 }
37

The source code in distance.c can be compiled into an executable machine code like this:

7 / 13
Program Development Process [Prasanna Ghali]

1 $ gcc -std=c11 -pedantic-errors -Wstrict-prototypes -Wall -Wextra -Werror


distance.c -o dist-gcc.out

Note that the $ character above represents the Linux bash shell prompt and is not a part of the
compiler command.

In Linux, the executable generated by the compiler can be run like this:

1 $ ./dist-gcc.out
2 Enter point P: 1 4
3 Now, enter point Q: 4 6
4 Distance from P(1.000, 4.000) to Q(4.000, 6.000) is 3.606
5 $

Step 2: Testing

After the solution has been coded, testing proceeds similarly to hand-testing an algorithm. The
difference, of course, is that the code will now be executed by the computer several times for
different input. Again you should try to make the input as difficult and potentially troublesome for
the computer as possible. Boundary values and input for which the solution should be trivial
should again be considered. Large input sizes, infeasible to hand-test, must now be tested.

Program testing can be a very tedious and time-consuming part of program development. This is
surely one major factor for students submitting code [for assignments] that works for a particular
input but not for other inputs. As a programmer, you're responsible for completely testing your
program. In business environments consisting of large development projects, there are often
specialists known as test engineers who're responsible for testing to make sure the programs
written by individual programmers and teams work together as a single system.

There are two types of testing: blackbox and whitebox. Blackbox testing is done by the system test
engineer and the user. Whitebox testing is the responsibility of the programmer.

Blackbox testing gets its name from the concept of testing the program without knowing what is
inside it, that is, without knowing how it was designed and implemented. In other words, the
program is like a black box that cannot be seen into. Instead, the test engineer uses the problem
statement to determine the program's behavior, then supplies input data data to be consumed by
the program, and then compares the output data produced by the program with the expected
output obtained through hand-testing.

Whereas blackbox testing assumes that the tester knows nothing about the program, whitebox
testing assumes that the tester knows everything about the program. In other words, the
program is like a glass house in which everything is visible. For this reason, whitebox testing is
also referred to as glass house testing. Whitebox testing is your responsibility. As the programmer,
you know exactly what is going on inside every program you author. You must make sure that
every command, every instruction, and every possible situation have been tested. This is not a
simple task!

An important aspect of whitebox testing is to test functions of a program (function is the term
used in C to describe code that encapsulates an algorithm) in isolation. You write a short
program, called a test harness, that calls the function to be tested and verifies that the results are
correct. This process is called unit testing. You must begin thinking of unit testing when you're
designing the algorithm. Ask yourself what boundary conditions and unusual situations you need
to test for and make a note of them immediately because being human you won't remember

8 / 13
Program Development Process [Prasanna Ghali]

them an hour later. When you're writing your pseudocode or drawing your flowcharts, review
them with an eye towards test cases and make additional notes of the cases you need. Always
document your test cases. After your program is finished and in production, you'll need the test
plan again when you make modifications to the program. Finally, remember that except for the
most trivial programs, one set of test data will not completely validate a program. Large-scale
development projects may require hundreds of test cases to validate a program.

What happens when programs malfunction? Catastrophic failures of systems attributed to


incorrect software behavior are cataloged here and here. This article discusses what happens
when software executes incorrect and unexpected actions.

How do you know when a program is completely tested and reliable? In reality, there is no
way to know for sure. But you can do certain things to keep the odds on your side. Even though
not all of the concepts may be clear to you until more material and topics are covered in this
course, they're included here for the sake of completeness:

1. Verify that every line of code has been executed at least once.
2. Verify that every selection statement in your program has executed both and
branches.
3. For every iteration statement in your program, make sure the tests include the first and last
iterations. The tests must also include iterations below the first and above the last to ensure
that out-of-range iterations are not executed by the program.
4. If error conditions are being checked, make sure all error logic tested. This may require you
to make temporary modifications to your program to force the errors. For instance, an
input/output error usually cannot be created - it must be simulated.

Step 3: Debugging

After a program is completely tested and you've ensured that the program produces correct
output for specified input, you have now created a working program that can then be used by your
clients. Instead, if the program generates incorrect output or behaves in unintended ways, then
you've created an incorrect program containing one or more software bugs. Bugs can arise
because of incorrect implementation - that is, mistakes and errors were made in the coding step
[Step of the implementation phase]. Bugs can also arise because of incorrect design - that is, an
incorrect algorithm was conceived during Step of the problem-solving phase.

The intent of the debugging step is to identify the source of software bugs within the program.
The activity of debugging is distinct from testing [Step of the implementation phase]. While
testing focuses on revealing the presence of bugs [by finding inputs for which the program
generates incorrect outputs], debugging is concerned with the processes initiated after incorrect
program behavior is detected by testing; hence, debugging follows testing.

Once testing has determined the existence of bugs, you begin the process of locating the source
of the bug and fixing it. The most popular way to find bugs is by manual debugging; that is, you
manually contrast what is happening to what should be happening when your program is
executing. The intent here is to confirm, one by one, that the many things you believe to be true
about your program are actually true. The classic technique is to insert trace code into the
program to print values of variables as the program executes. By manually analyzing the output
of the trace code, you may find that one or more of these variables have values that contrast with
the correct values they must have for correct program behavior. In that case, you've found a clue
to the location of a bug. Further analysis of the trace code output and hand simulation of the
program will help you determine whether the bug was caused by incorrect implementation or by
an incorrect algorithm. As illustrated by Figure , bugs caused by incorrect implementation are

9 / 13
Program Development Process [Prasanna Ghali]

easier to correct and only require an iteration over the implementation phase. Instead, bugs
caused by incorrect algorithm will be more expensive since they will require a re-evaluation of the
entire program design process.

What makes debugging time consuming and expensive is that it is an iterative process. Debugging
requires programmers to implement a constant cycle of adding trace code to print out values of
variables during execution, recompiling, executing the program, analyzing the output of the trace
code, and then moving the trace code to a different location after removal of the current bug.

To speed up the debugging process, modern compiler environments provide special programs,
called debuggers, that remove the tedium of inserting trace code into your program. A debugger is
a special program that executes other programs such as your buggy program, allowing you to run
your program step by step by providing facilities to pause and restart the program's execution
and at each step examine the values of variables. A debugger allows you to be more productive
by directly examining what your program is doing while it runs without the need for trace code.

I'll provide more details as the semester unfolds on debugger usage and special strategies for
debugging that will make you more productive as a programmer.

Problem-Solving Phase: Exponentiation


Consider the problem of writing an algorithm for computing the exponentiation function .

The first step is to understand the problem clearly. One understanding of the exponentiation
function is by substituting suitable values for and . In mathematics, the set of real numbers
contains the set of infinite points on the infinitely long real number line ranging from .
Exponentiation is used extensively in many fields, including economics and physics, chemistry,
and biology with applications such as population growth, compound interest, and chemical
reaction kinetics. For our solution, we restrict the values of and to integer values (because the
exponentiation algorithm is simpler for integer values) so that we can think of .

Understand that if and , then . Further, confirm your understanding with


another set of values, say and , and compute .

Because of our clear understanding of the problem, the second step of describing inputs and
output becomes straightforward: both inputs and are integer values and the output is also
an integer value. For now, the algorithm is unknown and can be thought of as a blackbox allowing
us to visualize the inputs to the blackbox and output generated by the blackbox as:

The third step is to work the problem by hand or with a calculator, using a simple set of data.
Suppose and . The steps to compute or by hand will look like this:

For the step, you must think about what you did to solve the problem in step , and write
down the individual steps to solve that particular instance. That is, you must write down a clear
step-by-step outline of the solution that could be followed by anybody else to reproduce your
answer for the particular problem instance solved in Step . Step for the hand solution in step
would look like this:

10 / 13
Program Development Process [Prasanna Ghali]

For the step, you've to use the insights gained from step to find a pattern that allows you to
solve the problem of computing for not just and but for possibly infinite
combinations of integer values and . The first task in step is to replace particular values used
in each step of step with mathematical expressions of parameters. Doing this for step would
look like this:

The second task in step is to find repetition in terms of these parameters:

Notice that after setting , the repetitive process of multiplying by occurs times where
is equivalent to . Using this key insight, the third and final task in step is to write the
algorithm as:

11 / 13
Program Development Process [Prasanna Ghali]

Implementation Phase: Exponentiation


is converted to a C program so that you can use a computer to perform the
computations:

1 /*
2 Source file: expo.c
3
4 This program prompts user to enter two integer values, say x and y.
5 The program computes and prints x^y to standard ouput.
6
7 To compile using GCC on Linux:
8 gcc -std=c11 -pedantic-errors -Wstrict-prototypes -Wall -Wextra -Werror
expo.c -o expo-gcc.out -lm
9 To compile using clang on Linux:
10 clang -std=c11 -pedantic-errors -Wstrict-prototypes -Wall -Wextra -Werror -
lm expo.c -o expo-clang.out -lm
11 To compile using Microsoft C compiler (in Windows):
12 cl /EHsc /TP /Za /Feexpo-msvc.exe expo.c
13 */
14
15 #include <stdio.h>
16
17 int main(void) {
18 // input portion
19 printf("Enter integer values for base and power: ");
20 int base, power;
21 scanf("%d %d", &base, &power);
22
23 // computations
24 int expo = base;
25 int i = 1;
26 while (i < power) {
27 expo = expo * base;
28 i = i + 1;
29 }
30
31 // output portion
32 printf("pow(%d, %d) = %d\n", base, power, expo);
33 return 0;
34 }
35

12 / 13
Program Development Process [Prasanna Ghali]

The source code in expo.c can be compiled into an executable machine code like this:

1 $ gcc -std=c11 -pedantic-errors -Wstrict-prototypes -Wall -Wextra -Werror


expo.c -o expo.out

In Linux, the executable generated by the compiler can be run like this:

1 $ ./expo.out
2 Enter integer values for base and power: 3 5
3 pow(3, 5) = 243
4 $

13 / 13
HIGH-LEVEL PROGRAMMING I
Program Development Process by Prasanna Ghali
Outline
2

 Program development process


 Six steps of problem-solving phase
 Implementation phase
Program Development Process
3
Problem-solving phase

Steps 1-2: Steps 3-5: Step 6:


Problem
Analyze Problem Devise Algorithm Trace Algorithm
Incorrect algorithm

Incorrect implementation

Step 3: Step 2: Step 1:


Debug Incorrect Test Code
program
Correct program

Implementation phase
Working Program
Problem-Solving Phase
4

1. Understand problem clearly


2. Describe inputs and outputs
3. Work problem by hand for simple data set
4. Decompose solution into step-by-step details
5. Generalize steps into algorithm
6. Test algorithm with broader variety of data
Algorithm for 𝑥 𝑦 (1/8)
5

 Step 1: Understand problem clearly


 If 𝑥 = 2, 𝑦 = 3, then 23 = 8
4
 If 𝑥 = 3, 𝑦 = 4, then 3 = 81

 Step 2: Describe input and output clearly


 Inputs are integer values, output is integer value

𝒙
𝒙𝒚
𝒚
Algorithm for 𝑥 𝑦 (2/8)
6

 Step 3: Work the problem by hand for simple


data set
 Set𝑥 = 3, 𝑦 = 4
 Multiply 3 by 3
 You get 9
 Multiply 3 by 9
 You get 27
 Multiply 3 by 27
 You get 81
4
3 is 81
Algorithm for 𝑥 𝑦 (3/8)
7

 Step 4: Decompose solution into step-by-step


details
 Each step must be precise
 Nothing is left to guesswork
Algorithm for 𝑥 𝑦 (4/8)
8

 Step 5: Generalize steps into algorithm – you’ll


need to see underlying pattern to solve
problem
 Requires two activities:

 Replace particular values used in each step with


mathematical expressions of parameters
 Find repetition in terms of parameters
Algorithm for 𝑥 𝑦 (5/8)
9

 Replace particular values used in each step with


mathematical expressions of parameters
 Set𝑥 = 𝑛 = 3, 𝑦 = 4
 Multiply 𝑥 by 𝑛 = 3
 You get 𝑛 = 9
 Multiply 𝑥 by 𝑛 = 9
 You get 𝑛 = 27
 Multiply 𝑥 by 𝑛 = 27
 You get 𝑛 = 81
𝑦
𝑥 is 𝑛
Algorithm for 𝑥 𝑦 (6/8)
10

 Find repetition
 Set𝑛 = 𝑥 = 3, 𝑦 = 4
 𝑛 = 𝑚𝑢𝑙𝑡𝑖𝑝𝑙𝑦 𝑥 𝑏𝑦 𝑛

 𝑛 = 𝑚𝑢𝑙𝑡𝑖𝑝𝑙𝑦 𝑥 𝑏𝑦 𝑛

 𝑛 = 𝑚𝑢𝑙𝑡𝑖𝑝𝑙𝑦 𝑥 𝑏𝑦 𝑛
𝑦
 𝑛 = 𝑥 is 𝑟𝑒𝑠𝑢𝑙𝑡
Algorithm for 𝑥 𝑦 (7/8)
11

 Generalize steps into algorithm


 Set𝑛 = 𝑥, 𝑖 = 1
 while (𝑖 < 𝑦)
𝑛 = 𝑛 ∗ 𝑥
𝑖 = 𝑖 + 1

 endwhile

𝑛 is answer
Algorithm for 𝑥 𝑦 (8/8)
12

 Test algorithm with broader variety of data


Implementation Phase
13

 Code the algorithm


 Test code

 Debug code in case testing step generates


incorrect results
Coding the Algorithm
14

#include <stdio.h>

int main(void) {
int x, y, i, n;
printf("Enter two integers: ");
scanf("%d %d", &x, &y);

n = x;
i = 1;
while(i < y) {
n = n * x;
i += 1;
}
printf("%d raised to power of %d is: %d\n", x, y, n);
return 0;
}
Coding the Algorithm – Even better
15
#include <stdio.h>

int exponent(int x, int y);

int main(void) {
printf("Enter base and power: ");
int base, power;
scanf("%d %d", &base, &power);
int result = exponent(base, power);
printf("%d ^ %d is: %d\n", base, power, result);
return 0;
}

int exponent(int x, int y) {


int n = x, i = 1;
while (i < y) {
n = n * x;
i = i + 1;
}
return n;
}
Testing the Code
16

 Whitebox vs. Blackbox testing


 Unit test requires calling function or program

and verifying that results are correct


 If testing step generates incorrect results,

debug code
 Note: There are 2 major bugs in previous

program!!!
Brief Introduction to Algorithms [Prasanna Ghali]

Brief Introduction to Algorithms


What is an algorithm?
An algorithm is a step-by-step method for solving a problem. Think of it as a procedure whose
steps are completely specified to always give the correct result for valid input. It is the idea behind
every computer program. Examples of algorithms can be found throughout history, starting with
ancient Babylonia. School children learn to compute the greatest common divisor of two integers
using the Euclidean algorithm which was described by Euclid in BC. Indeed, the word
"algorithm" derives from the name of the ninth-century Arabic mathematician Al-Khwarizmi.

Informally, think of algorithm as just a fancy word for recipe or rule of procedure. A recipe is
nothing but a sequence of steps that instruct a cook in preparation of a particular dish. The
following recipe for salmon furnishes an example of an algorithm:

1. Take a to pound salmon and allow it to swim in clear water for hours.
2. Scale and fillet the salmon.
3. Rub fillets with butter and season with salt and pepper.
4. Place on cedar board and bake in oven set at for minutes.
5. Throw away salmon and eat cedar board.

While a recipe describes the ingredients and the sequence of steps required to convert the
ingredients into a dish, an algorithm describes the input data and sequence of steps to generate
the required output from the given input. Just as there are many recipes to make a dish, a
problem or class of problems may have many different algorithms. And, for each such algorithm,
there can be many different implementations of computer programs.

Formally, an algorithm is a procedure to accomplish a well-specified problem and has the


following characteristics:

Input. The algorithm receives zero or more inputs taken from a specified set of objects.
Output. The algorithm produces one or more output which have a relation to the inputs.
Precision. The steps are precisely and rigorously stated without cause for any ambiguity in
their actions.
Finiteness. The algorithm must terminate after a finite number of steps are executed.
Uniqueness: The intermediate results of each step of execution are uniquely defined and
depend only on the input to and results of the preceding steps.
Generality. To be interesting, the algorithm must solve the problem for a general set of
inputs.

Finally, a word about why the subject of algorithms is important and useful. One specific reason is
that algorithms are the basis of all computer programs and thus this subject underlines the entire
field of computing and computer science. A more general reason is that the discipline of
algorithmic thinking is valuable in carrying out any non-trivial project because it aids in the
planning of such tasks and, in particular, helps avoidance of errors by forcing a consideration of
all possibilities. This latter point is crucial when designing a large system such as a manned lunar
probe, where forgetting even the smallest detail will lead to catastrophic results.

Common elements of algorithms


Algorithms contain the following five elements:

1 / 12
Brief Introduction to Algorithms [Prasanna Ghali]

Input: Algorithms must have the means of acquiring data from external means. For example,
an algorithm that computes the roots of a quadratic equation must receive
the coefficients as input.
Sequence: Algorithms must be able to perform actions in order, one after the other. A
majority of these sequential actions consist of arithmetic computations [addition,
subtraction, multiplication, division, and so on], relational comparisons [greater than, less
than, and so on], and testing logical conditions [equal to, not equal to, and so on].
Selection: Algorithms must have some means of selecting (or choosing) among two possible
courses of actions based on initial data, input values, and/or computed values.
Iteration: Algorithms must be able to repeatedly execute a collection of instructions, for a
fixed number of times or until some logical condition holds.
Output: At their conclusion, algorithms must have the means to report the results obtained
by executing the algorithm.

Expressing algorithms
The term algorithm is derived from the name of a ninth-century Arabic textbook author, Musa al-
Khowarizimi (son of Moses, native of Khowarizm). It is a word familiar to - although perhaps
quickly forgotten by - generations of secondary school students many of whom have learned
Euclid's algorithm, a rule for computing the greatest common divisor of two integers.

Indeed, algorithms are something most people use every day even when they've never heard of
the word. When using a recipe in a cookbook, the algorithm is the specific sequence of
instructions which the cook follows. The route information published by mapping apps provides
another example of an algorithm. In this case, the route is the specific sequence of directions that
must be followed to travel from a source location to a destination location. Often algorithms are
used implicitly, that is, without explicit thought about a sequence of steps. You just don't know it
or think about it much. Almost every activity in your lives can be modeled as algorithm: figuring
out what to wear, alphabetizing books on a shelf, folding laundry retrieved from a dryer, how to
navigate the grocery store to purchase weekly supplies, determining how to prioritize your tasks
for the day, and so on.

Computers are used to solve problems. However, before a computer can solve a problem it must
be given instructions for how to solve the problem. And to determine what these instructions are,
an algorithm, apart from any specific computer and any specific programming language, must be
devised to solve the problem. Algorithms intended to be executed or run or performed on a
computer must avoid imprecision and ambiguities because computers do exactly what they're
told and nothing more. They are notoriously poor at resolving ambiguities since they lack the
ability to read between the lines and they lack the skill to determine what was meant rather than
what was said. An informal instruction "please get me a glass of water" in a non-computing
context can be understood and accomplished by you and most humans but not by a computer. In
contrast, an algorithm is a sequence of steps that describes how to solve a problem and/or
complete a task, which will always give the correct result. For the previous non-computing "please
get me a glass of water" instruction, the algorithm might be

1. Go to the kitchen.
2. Pick up a glass.
3. Turn on the tap.
4. Put the glass under the running water and remove it once it is almost full.
5. Turn off the tap.
6. Take the glass back to the person who gave the instruction.

2 / 12
Brief Introduction to Algorithms [Prasanna Ghali]

It is reasonable to assume that you and most other humans would be able to follow these steps
and fetch the glass of water. However, from a computational context, no computer could execute
these steps. These steps are too informal, too lacking in precision. For example, how would a
computer execute the step "Go to the kitchen." Assuming the person requesting the glass of
water is on the patio, how does the computer navigate its way to the kitchen? How does the
computer open the door separating the patio from the kitchen. How does it avoid obstacles?
What has been said about the lack of precision in the first step is true for the remaining steps.

Another example in a computational context might be to "display the list of high scores" for a
video game. Again, informal instructions like this aren't precise; there's no way that a computer
could follow that instruction exactly, but you would get the general idea of what is meant and
what you have to do, which would be "go through each score in a table of scores for various
players, keeping track of the largest score and the player's name." These sorts of informal
descriptions are only useful for giving another human the general idea of what you mean, and
even then there's a risk that they won't properly understand it. In a computational context, the
video game's authors will have to implement the algorithm in more detail with more precise steps
before a programmer could author a program that executes the algorithm.

To emphasize the idea of precisely describing actions in a computational algorithm, it is de


rigueur for introductory programming courses to have students write down an algorithm to make
a peanut butter and jelly (PBJ) sandwich. The instructor then executes these algorithms, which are
often imprecise and ambiguous. The instructor takes the most comical interpretation of the
instructions to underscore that what the students wrote did not actually describe what they
meant.

This exercise underscores an important point - you must specify exactly what you want the
computer to do. The computer does not "know what you mean" when you write something
vague, nor can it figure out an "etc." Instead, you must be able to describe exactly what you want
to do in a step-by-step fashion. Precisely describing the exact steps to perform a specific task is
somewhat tricky, as you are used to people implicitly understanding details you omit. Irrespective
of the programming language used, no computer will do that for you.

Describing and writing algorithms requires a notation for expressing a sequence of steps to be
performed. The options available to us include natural languages such as English and
programming languages such as Java, Python, C, C++, and so on.

Humans communicate in their daily lives using natural languages such as English, Spanish,
Japanese, and so on. However, human communications are too rich, ambiguous, and depend on
context. They lack structure and therefore would be hard to follow when used for expressing
computer science algorithms.

A programming language is at the other end of the spectrum - it is too rigid for expressing
solutions. When solving problems, you want to think at an abstract level. However, programming
languages shift the emphasis from how to solve the problem to tedious details of grammar and
syntax.

Rather than using natural languages or programming languages, an algorithm is better expressed
using one of two tools: pseudocode or flowchart.

Pseudocode is an English-like representation of the logical sequence of steps required to


solve a problem.
Flowchart is a pictorial representation of the same thing.

3 / 12
Brief Introduction to Algorithms [Prasanna Ghali]

Writing pseudocode
Pseudocode involves thinking at an abstract level about the problem and using an English-like
representation of the solution. Pseudo is a prefix that means false, and to code a problem means
to put it in a programming language; therefore pseudocode means false code, or sentences that
appear to have been written in a computer programming language but don't necessarily follow
syntax rules of any specific language.

Pseudocode is flexible and provides a good compromise between natural and programming
languages because it is a planning tool, and not the final product. It is simple, readable, and has
no rigid rules to adhere to.

Any pseudocode must be able to represent the five common elements of any algorithm: input,
sequence, selection, iteration, and output. Sometimes, pseudocode is prefaced with a beginning
statement like and ended with a terminating statement like . The statements between
and look like English and are indented slightly so that and stand out.

Input

Reading input from an user would be written as:

Output

Printing or presenting the output to the user can be written as:

Sequence

A sequence structure consists of computational statements that are executed in order, one after
the other. Basic arithmetic operations are written as:

A bit of terminology first. Each computational line in the pseudocode and more generally every
line of the pseudocode is labeled a statement. Each statement consists one or more expressions.
Line containing the text is a statement. This statement consists of expressions (from
left to right): , , and . Every expression consists of one or more operands and zero or
more operators. Operators represent actions while operands represent the objects on which
these actions are applied. In expression , symbol represents the operator while symbol
and value represent operands. While will always intrinsically describe an integer value ,
symbol specifies a variable. Think of a variable as a named memory location that can store
values. Unlike constant , the contents of a variable change during the course of execution of
the program.

In terms of execution, every expression evaluates to a value and a type (more on types in
subsequent lectures).

At line , statement means "Copy value into ." More generally, the statement

4 / 12
Brief Introduction to Algorithms [Prasanna Ghali]

means "Copy value of into ," or, equivalently, "Replace the current value of
by the value of ." For example, when the statement on line

is executed, the value of is copied into and the value of is unchanged. The symbol is
interpreted as "is assigned." We call symbol the assignment operator.

Relational expressions are used to compare two values.

The relational operators , , , , , and have the usual meanings from algebra:
equal to, not equal to, greater than, greater than or equal to, less than, and less than equal to,
respectively. The thing to remember though is that relational expressions evaluate to a or
value. By convention, zero value is considered while any non-zero value evaluates
.

Logical expressions are mostly used to control the sequencing of steps. They allow the
pseudocode to make a decision based on multiple conditions. Each operand is considered to be a
condition that can be evaluated or . Then the values of the conditions are combined to
determine the overall value of the groupings or
grouping.

Operator perform a logical operation, that is, the expression


is only if both operands are [non-zero]. Operator
performs a logical operation, that is, the expression is when
either operand is [non-zero]. Operator performs a logical [negation] operation, that
is is only if is .

Selection

Input, output, and sequence statements are sequentially executed, that is, the statements are
executed in order one after the other. In contrast, a selection statement alters the sequential flow
of control by allowing one of two courses of action to take place depending on whether the
answer to a condition is or . An action that might or might not be executed can be
written as:

5 / 12
Brief Introduction to Algorithms [Prasanna Ghali]

Notice that the steps performed by the and clauses are indented slightly so that
they can stand out and can be easily discerned. Such conditional situations arise often in our daily
lives. For example:

In certain situations, the clause doesn't appear. For example, when there is a high
probability that it might rain, you would like to carry an umbrella to stay dry during your
commute. If rain is not forecast, you go about your commute as usual:

Line in the pseudocode contains text delimited by symbols and representing a comment.
Comments are not an intrinsic part of an algorithm but are instead present when the algorithm's
author wishes to convey explanatory information to readers of the algorithm.

Iteration operations

The fifth element represents repeat operations where a block of basic operations are repeatedly
executed until a certain condition is met:

Notice that the steps repeatedly performed by the statement are indented slightly so that
they can stand out and can be easily discerned. How does this work? First, is
evaluated. If it is , then the loop terminates and the step on line immediately following the
loop is executed. Instead, if is , then the algorithm executes the
in order, one by one. Here's an example that prints a table of numbers
and their corresponding squares:

Pseudocode example: Traveling on a subway


Suppose you wish to travel from station to station on the Singapore Mass Rapid Transit
[MRT] system. The following picture shows a map of the MRT [image from lta.gov.sg] with
different lines indicating different colors.

6 / 12
Brief Introduction to Algorithms [Prasanna Ghali]

Let's embody the thought process you might apply in deciding how to make your trip from station
to station into an algorithm expressed in pseudocode:

Algorithm should be understandable even if you've never seen an algorithm before. You
may have noticed ways that might be improved. For example, suppose you know a long
walk is required to change from one line to another at station compared to some other station
. How might that fact be used by the algorithm? You should always be on the lookout for ways
in which an individual algorithm may be improved.

You may have also noted some ambiguities in . What do you do if two pairs of lines require
the same number of stops? How about the case where two lines have more than one station in
common? What if certain lines are less busy than other lines at certain parts of the day and thus it
is highly likely that you'd be able to find a seat? And, what if the more comfortable journey takes
more time than the less comfortable journey? How should algorithm decide between the
two options? These are not serious problems with because it is an algorithm intended for
consumption by humans who are usually pretty good at "reading between the lines" and using
situational contexts to resolve ambiguities.

7 / 12
Brief Introduction to Algorithms [Prasanna Ghali]

Pseudocode example: Mathematical algorithm


Lets consider a problem from mathematics:

The input is the terminating index , and the output is the sum of the first terms of the series. If

you aren't familiar with summation notation , it means that you take the quantity after the

and evaluate it for each value of implied by the limit below the and the limit
above the and then add the evaluated values together. Thus, for example,

The following algorithm is developed to solve the problem.

The algorithm receives a positive natural number as input and produces as output, , the
sum of the first terms of the series.

The first task of the algorithm is to initialize variables to their appropriate values. Lines and
initialize variable (keeping track of the summation computed so far) to and counter
(keeping track of the numbers whose reciprocals are to be computed) to .

In line , the 's conditional expression is if is smaller-than-or-equivalent-to


. The condition will be when becomes greater-than . This is the correct and necessary

condition to compute for all values of in the interval . Lines and are repeatedly

executed to compute the summation.

To test algorithm , we should check it by hand for several values of . Simulating the
execution of an algorithm for a specific input is called a trace. Here the minimum value of is ;
has no maximum since can be equal to any positive integer.

If is , at lines and , and are set to . At line , is incremented to . At line , is


set to . The algorithm terminates at line since is equal to ; both are now equal to . The
algorithm correctly computes .

8 / 12
Brief Introduction to Algorithms [Prasanna Ghali]

Next, we show how the algorithm executes if the input, , is equal to . At lines and , the
algorithm sets to and to . At line , it assigns the value , which is since is , to .
The effect is to add to . At line , it adds [i.e., to , so that now has value . At
line , the algorithm tests whether equals . Because equals and equals , the algorithm
repeats lines and .

At line , the algorithm updates to . It then adds [i.e., ] to . At this point, the value of
is . Since now equals and therefore is not equal to , the algorithm repeats lines
and .

At line , the algorithm updates to . It then adds [i.e., ] to . At this point, the value of
is . Since equals , is now equal to . Therefore, the algorithm terminates.
The value, stored in , is the sum of the first three terms of the series: .

Recall that an algorithm must have the following characteristics: input, output, precision,
finiteness, uniqueness, and generality. Let's evaluate algorithm for these characteristics:

Input. The algorithm receives exactly one input - the terminating index - which can have
any of the infinite values of a positive natural number.

Output. The algorithm produces the required summation .

Precision. The algorithm is decomposed into simple sequential steps from lines through
each of which performs a specific action without any ambiguity.
Finiteness. This is where most algorithms have errors - it is especially important to test
boundary values: the minimum and maximum values. First, the counter is initialized to on
line . If [that is, is equivalent to ], the algorithm stops after one repetition since
line increments to ensuring that the condition on line will evaluate . There is no
maximum value for this algorithm. However large the value of is, is always incremented
by each repetition meaning that after repetitions will have a value of at which
point the condition on line will evaluate .
Generality. The algorithm works for all positive natural numbers of which an infinite number
exist.

Checking algorithm for small values of doesn't prove that the algorithm is correct. It
proves only that the algorithm is correct for the values that were tested! However, checking the
algorithm for small values of does give you confidence that the algorithm is correct. To prove
that the algorithm is correct, a mathematical technique such as mathematical induction could be
used. Such correctness proofs are beyond the scope of this basic introduction.

Drawing flowcharts
A flowchart is a combination of graphical symbols that are used to represent the logical flow of
data through a solution to a problem. When you create a flowchart, you draw geometric shapes
that contain the individual statements and that are connected with arrows.

A parallelogram represents an input symbol indicating that it contains input operations. The input
statement in English is written inside the parallelogram. The same symbol is used to represent an
output operation. Since the parallelogram is used to represent both input and output, it is often
called the input/output symbol, or I/O symbol.

A rectangle represents sequence operations.

9 / 12
Brief Introduction to Algorithms [Prasanna Ghali]

To implement selection and iteration structures, a decision symbol, which is shaped like a
diamond is used. The diamond usually contains a question, the answer to which is one of two
mutually exclusive options: or .

To show the correct sequence of these statements, flowlines represented by arrows are used to
connect these graphical symbols.

To be complete, a flowchart should include the two terminal symbols at each end: start and stop
symbols. These symbols are graphically represented by the lozenge shape.

Flowchart example: Computing series summation


As a first example of flowcharting an algorithm, algorithm [which computes the summation

] is illustrated using a flowchart.

Flowcharts are difficult to draw for complex algorithms compared to writing pseudocode.
diagrams.net is a free online tool for rendering flowcharts.

Algorithm example: Counting


This basic introduction to writing algorithms concludes by writing pseudocode and drawing a
flowchart for the really simple problem of counting. That is, given a non-negative integer, what is
the next integer in sequence? Now this is so familiar and trivial to you that your first reaction may
be: why is an algorithm required at all for such a trivial process? The rationale is that the problem
here is not how to count - of course, you know how to do that - but rather whether you can
explain how to count to something inanimate like a computer which doesn't know how to count
or to someone who doesn't know how to count. Think about how you would explain counting to
something rudimentary that its only arithmetic capability is to be able to add to the digits
[but not since adding to involves a carry into the 's place]. Being able to take

10 / 12
Brief Introduction to Algorithms [Prasanna Ghali]

something as trivial as counting and writing an algorithm to perform that task would be a true
test of your understanding of the concept of counting. Assume that an integer can be represented
as a sequence of digits , so that, for example, the number is
represented by with having a value of . Likewise, the
number is represented by with having a value of .

Test the algorithm for general values such as the number , the number , and , for all of
which . Test boundary conditions such as where , or where , or with
and with .

The following figure illustrates the flowchart corresponding to algorithm that adds
to an integer .

11 / 12
Brief Introduction to Algorithms [Prasanna Ghali]

Do you prefer the pseudocode or the flowchart? If this is your first introduction to both these
techniques, then I'd hazard a guess that you prefer the flowchart because it contains easy-to-
follow symbols. This notation was popular in the early days of computing but is no longer used
because it is quite unwieldy for all but quite small algorithms. Once you get used to pseudocode
notation, you'll find it easier to read and understand than flowcharts.

Exercises
The following problems are meant for exercising your knowledge of writing pseudocode and
flowcharting algorithms. The practice gained from developing algorithms, pseudocode, and
flowcharting will help you write more robust and elegant code. For each problem, write the
pseudocode and draw a flowchart for the algorithm that solves the problem. Before attempting to
write any algorithm, you should think carefully about precisely what it is you want to do and how
you're going to go about doing it.

1. This is a classic problem introduced to every computer science student. Write an algorithm
to make a peanut butter and jelly sandwich.
2. In the same vein as the previous question, think about the process of calling your friend
using a telephone. Next, provide an algorithm that can be followed by an inanimate robot to
make a call using a telephone.
3. Compute the area of a trapezoid.
4. Compute the factorial of a positive integer :
.

5. Write an algorithm that computes the sum of the first terms of the series .

6. Compute the greatest common divisor of two positive integers.


7. Find the roots of a quadratic equation for some real numbers , , and .
8. Let be a set of elements where each element is a real number.
Find the maximum number in the set . The input is the sequence, , and the integer, ,
indicating the number of elements in the sequence. The output is the index of the smallest
element in the sequence.
9. Alternatively, determine the minimum value in the set from the previous question.
10. Find the length of the longest sequence of values that are in strictly increasing order given a
sequence of real values . From the definitions of increasing and
strictly increasing functions, we can conclude that the sequence of values are in
strictly increasing order while the sequence of values are in increasing order.
The length of the longest sequence of values in strictly increasing order is for the sequence
of values . The length of the longest sequence of values in is - the
subsets and are in strictly increasing order.

12 / 12
HIGH-LEVEL PROGRAMMING I
Intro to Algorithms by Prasanna Ghali
Outline
2

 What is an Algorithm?
 Algorithm characteristics
 Elements of an algorithm
 Expressing algorithms
 Pseudocode
 Flowcharting
 Examples
What is an Algorithm?
3

 Step-by-step method for solving a problem


 Similar in concept to a cook’s recipe
Algorithm Example: Recipe for
4
Brownies
½ cup butter 1 tsp vanilla extract
1 cup sugar ½ cup cocoa
2 eggs ½ cup flour

1. If butter not soft, then melt butter


2. Blend melted buffer and sugar until mixture has
creamy consistency
3. Add eggs and vanilla; stir
4. Add cocoa and flour; mix until well blended
5. Pour into greased round glass cake pan
6. Microwave for 9-10 minutes
Examples of Algorithms
5

 Putting together IKEA furniture


 Going from airport to hotel in new city

 Solving Rubik’s cube

 Playing board games such as Chess, Go, …

 Solving a maze

 Choosing a TV cable plan

 Choosing a cell phone subscription plan


Oldest Algorithm?
6

 First documented algorithm was presented by


Greek mathematician Euclid in 300 B.C. to
compute Greatest Common Divisor (GCD)
1. Let 𝐴 and 𝐵 be integers such that 𝐴 > 𝐵 ≥ 0
2. If 𝐴 = 0, then GCD is 𝐵 and algorithm ends
3. If 𝐵 = 0, then GCD is 𝐴 and algorithm ends
4. Write quotient remainder format: 𝐴 ← 𝐵 ∙ 𝑄 + 𝑅
5. Set 𝐴 ← 𝐵 and 𝐵 ← 𝑅
6. Go to 2
Formal Definition
7

 Procedure to solve well-specified problem


 Must have following characteristics

 Input

 Output

 Precision

 Finiteness

 Uniqueness

 Generality
Algorithm Elements (1/4)
8

 Mid-60s, mathematicians proved that any logic


problem, no matter how complicated, can be
constructed using one or more of only three
structures or elements
 Think of an element as basic unit of logic
 What are these three elements?
 Sequence

 Selection

 Iteration
Algorithm Elements (2/4)
9

 Euclid’s Greatest Common Divisor (GCD)


algorithm
1. Let 𝐴 and 𝐵 be integers such that 𝐴 > 𝐵 ≥ 0
2. If 𝐴 = 0, then GCD is 𝐵 and algorithm ends
3. If 𝐵 = 0, then GCD is 𝐴 and algorithm ends
4. Write quotient remainder format: 𝐴 ← 𝐵 ∙
𝑄+𝑅
5. Set 𝐴 ← 𝐵 and 𝐵 ← 𝑅
6. Go to 2
Algorithm Elements (3/4)
10

 Elements an be combined in infinite ways


 Every element has single entry and single exit point
 Elements can be stacked or connected to one
another only at their entry or exit points
 Any element can be nested within another element
Algorithm Elements (3/3)
11

 We’ll add two additional elements


 Input

 Sequence

 Selection

 Iteration

 Output
Expressing Algorithms
12

 Need notation for expressing algorithms


 Options range from natural to programming

languages
 Two tools commonly used

 Pseudocode

 Flowchart
Pseudocode
13

 Pseudo means false


 Code a problem means to put it into
programming language
 Pseudocode means false code

 Sentences that appear to be written in


programming language but don’t necessarily
follow syntax rules of any specific language
Flowcharting
14

 Combination of graphical
input/output
symbols that represent
logical flow of data thro’
solution sequence

decision

terminal

flowline
Pseudocode: Input
15

 Can write reading of input from user as:

1: read x input x

1: read a, b, c input a, b, c
Pseudocode: Output
16

 Writing of output to user represented as:

1: print x output x

output
1: print “your speed is: “, x
“your speed is: “, x
Sequence (1/2)
17

 Computational statements executed


in order, one after another
 Once you start series of steps in

sequence, you must continue step by step 1


step until sequence ends
1: step 1 step 2
2: step 2
3: …
⋮ step n
n: step n
Sequence (2/2)
18

x = 10
1: x = 10
2: y = ax2+bx+c y=ax2+bx+c
3: z = y
z=y
Statements, Expressions, … (1/4)
19

 Statement made up one or more expressions


 Expression consists of one or more operands

and zero or more operators


 Operand can be constant or variable

operator

variable x = 10 constant

operand
Statements, Expressions, … (2/4)
20

 How many expressions in following statements?

3 1: x = 10
5 2: y = x*x
7 3: z = x + y * y
Statements, Expressions, … (3/4)
21

 Every expression evaluates to a value of


certain type
 Type represents set of values and set of

operations that can be applied on these values

1: z is integer assignment
2: z = 10 = operator

type is
z 10 integer
Statements, Expressions, … (4/4)
22

 Numbers without fractions (such as 10, 33, …)


are called integers
 Digital systems cannot represent infinite set of

fractional values on real number-line


 Instead, they represent a finite set of floating-
point values with each floating-point value
being an approximation of real values
Assignment Operator
23

variable = expression

 Copy value of expression into variable, or


 Replace current value of variable by value of
expression

variable expression
Arithmetic Operators
24

variable = operand1 operator operand2

 +, -, *, /, %
=

op
variable

operand1 operand2
Relational Operators
25

 Used to compare two operands or values or


expressions
 ==, !=, >, >=, <, <=

 Expression involving relational operators

always evaluates to either 1 (true) or 0 (false)


 Value 0 means false
 Any non-zero value means true
Logical Operators
26

 Used to control sequencing of steps; combine


simple relational expressions into more
complex expressions
 &&, ||, !

 Expression involving logical operators always


evaluates to either 1 (true) or 0 (false)
 a = x < y || x > z

 b = x >= y && x <= z


Selection Element (1/4)
27

 Alters sequential flow of control


 One of two courses of action is taken based on
result of evaluation of condition
 How to assign letter grades?
 Should I take an umbrella?
 Overtime pay? condition
true false
 Cable billing
action1 action 2
Selection Structure (2/4)
28

condition condition
true true false
false
action action 1 action 2

if (condition) then if (condition) then


action action 1
endif else
action 2
endif
Selection Structure (3/4)
29

𝒂% Letter Grade
𝑎 ≥ 93 A
𝑎 ≥ 93 90 ≤ 𝑎 < 93 A−
true false 87 ≤ 𝑎 < 90 B+
83 ≤ 𝑎 < 87 B
print ‘A’ print not ‘A’ 80 ≤ 𝑎 < 83 B−
77 ≤ 𝑎 < 80 C+
73 ≤ 𝑎 < 77 C
70 ≤ 𝑎 < 73 C−
60 ≤ 𝑎 < 70 D
𝑎 < 60 F
Selection Structure (4/4)
30

𝑎 ≥ 93
true false
print ‘A’ 𝑎 ≥ 90
true false
print ‘A-’ 𝑎 ≥ 87
true false
print ‘B+’ 𝑎 ≥ 83
true false

print ‘B’ ⋮
true false
Iteration Element
31

 Repeat actions while a condition remains true

condition true action


while (condition)
action false
endwhile
start

First Algorithm input 𝑁


32

 Compute 𝑥 2 ∀ 𝑥 ∈ 1, 𝑁 𝑠𝑢𝑚 = 0
𝑥=1
 1: read 𝑁
 2: 𝑠𝑢𝑚 = 0
𝑓𝑎𝑙𝑠𝑒
𝑥≤𝑁
 3: 𝑥 = 1 𝑡𝑟𝑢𝑒
 4: while (𝑥 <= 𝑁)
𝑠𝑢𝑚 = 𝑠𝑢𝑚 + 𝑥 2
 5: 𝑠𝑢𝑚 = 𝑠𝑢𝑚 + 𝑥 ∗ 𝑥 𝑥 =𝑥+1

 6: 𝑥 = 𝑥 + 1

 7: endwhile
output 𝑠𝑢𝑚

 8: print 𝑠𝑢𝑚 end


Traveling on a Subway
33
Algorithm: Subway
34

 Input: Source station 𝐴 and destination station 𝐵


 Output: Directions to go from 𝐴 to 𝐵 using maximum of single transfer
 if 𝐴 and 𝐵 are on same line 𝐿 then
 travel on line 𝐿 from 𝐴 to 𝐵
 else [𝐴 and 𝐵 are on different lines]
 find all pairs of lines (𝐿𝑖 , 𝐿𝑗 ) s.t 𝐴 is on 𝐿𝑖 & 𝐵 is on 𝐿𝑗
and two lines have common station
 if there is only one such pair then
 take 𝐿𝑖 to a station also on 𝐿𝑗 , get off, and then take 𝐿𝑗 to station 𝐵
 else [more than one possible pair of them]
 use pair (𝐿𝑖 , 𝐿𝑗 ) which requires fewest stops
 endif
 endif
Summary
35

 What is an Algorithm?
 Algorithm characteristics: inputs, outputs, precision,
finiteness, uniqueness, generality
 Elements of an algorithm: sequence, selection, iteration
 Expressing algorithms: Pseudocode, flowcharting
 Sequence: operator, operand, expression, variable,
constant, type, integer and floating-point values,
assignment operator, arithmetic operator, relational
operators
 Examples
 Things to do: Read handout, complete assignment
HIGH-LEVEL PROGRAMMING I
Introduction to HLP1 by Prasanna Ghali
High-Level Programming 1
2

 Assumed Knowledge
 Objectives

 Teaching Rationale

 Teaching Strategies

 Learning Strategies

 Help
Assumed Knowledge
3

 None
Objectives
4

 Teach fundamental programming concepts and


methodologies using C programming language
 Give you exposure to computational thinking
 Get you to think harder and deeper about
what is happening in your machine
 Get you to be disciplined and detail
oriented
 Ultimately, pave the way for you to become a
polyglot
Teaching Strategies
5

 Lectures
 Labs/Tutorials [20%]

 Quizzes and Exercises [15%]

 Programming Assignments [15%]

 Midterm and Final Assessments [50%]


Teaching Strategies: Lectures
6

 Introduce theoretical concepts


 Almost always accompanied by live coding

demonstrations and examples of theory


 After lecture, you must read associated
material in textbook and program before
attending next lecture!!!
 Attendance is mandatory
Teaching Strategies: Labs/Tutorials
7

 Clarify material covered in lectures


 We’ll focus on most critical concepts covered

that week and implement program(s) that


exercise these concepts
 Pair programming is encouraged

 Attendance is mandatory

 Respect submission deadlines!!!


Teaching Strategies: Quizzes
8

 Provide a venue to better understand theory


covered in lectures
 Involves reading specified text book material

and answering questions that test your


comprehension
 Could be in-class or take home

 Submission is mandatory – no submission

equivalent to zero grade


Teaching Strategies: Programming
9
Assignments
 Provide venue to improve problem solving skills
 Consist of structured programming exercises

with little hand-holding


 Submission is mandatory

 Respect submission deadlines!!!


Teaching Strategies: Midterm &
10
Final Tests
 Aim is for you and us to know how much you
know
 Involves all material covered in lectures, labs,

quizzes, and assignments


 Involves reading code, analyzing code, writing
code, debugging code, …
 Attendance is mandatory
Online Only
11

 All assessments are online only!!!


Learning Strategies
12

 Be an active and motivated learner


 Come prepared to every lecture and lab

 Take pride in your submissions!!!

 Get your hands dirty by programming!!!

 Expand your horizons by reading the text book

 Get help – we’re here to help you succeed


Getting Help
13

 If you’ve specific questions about HLP1


material:
 Post questions to Teams channel
 Use instructors consultation hours on Teams
 Use Academic Support Center

 Questions involving your grades and other


private matters should be directed to your
instructor
 Emails must always have [CSD1120] or [SEM1503] in
Subject
Are You Helping Yourself?
14

 We’re here to help, but what have you done to


help yourself?
 Your problem solving skills will determine your future
career’s trajectory
 You can learn this skill by analyzing and debugging
your problem extensively before asking for help
 Asking for help at first sign of something not working is
similar to spoon feeding!!!
Academic Integrity
15

 You’ve to submit original work


 Discussingsolutions is encouraged
 Pair programming is encouraged during labs

 Having study groups is encouraged

 Don’t take solutions


 Don’t provide solutions

 Read academic integrity policy on course web

page

You might also like