Topic 1. Introduction to Programming Learning Outcome At the end

advertisement
Topic 1. Introduction to Programming
Learning Outcome
At the end of this lesson, students will be able to:
1.
2.
3.
4.
5.
6.
7.
Explain what is a program
List and explain the various components of a computer system
List the steps involved in designing and writing programs
Use pseudocode and flowchart in their program design
Conduct desk-checking of a program
Explain the steps in coding, compiling, and running a C++ program
Differentiate the different types of computer program errors
Glossary
Execution
Integrated Development Environment
1.0 What is a program?
If you go to an ATM machine to withdraw money from your bank account, you will come face to
face with a screen which gives you instructions for you to follow. Examples of the instruction
could be as follows:
Please insert your bank card
Please enter your pin number
Please choose the service you want (eg. Withdrawal, fund transfer, exit, etc)
Please enter the amount you want to withdraw
Please remove your card
Please remove money from the slot
Please take receipt
Thank you and have a nice day
How could the ATM machine interact with you in such a way? After all, it is just a machine. Yes,
you are right! The ATM machine is actually a type of computer. And this computer is run by a
program.
Can you think of another example of a computer and a program which runs on the computer?
As we will see in the next section, a “computer” as we usually refer to, is actually a system
which is made up of a few components.
2.0 Computer systems
A computer system is made up of a hardware and a software components. The physical
machine that you see is the hardware of the computer system. This physical machine needs a
“brain” to make it work, and that is the software component. Let us take a closer look at these
two components.
2.1 Hardware
A computer system basically has 5 components: input device, output device, the
processor (or better known as CPU), main memory (better known as RAM), and
secondary memory.
An input device is to allow a person to communicate information to the computer. In
can be a keyboard, a mouse, a touch screen or any other device that allows a person to
enter an input or response to the computer.
An output device allows the computer to communicate information to the human, such
as displaying information on a display monitor, printing out information on a printer,
producing information as a sound from a speaker, ect.
The computer’s processor and the main memory form the heart of the computer and
are usually thought of a one integrated unit.
The secondary memory is used to store a permanent copy of the information. A hard
disk is the most common type of secondary memory you will see. Other secondary
memory are tapes, disks (CD or DVD), thumb drives, etc.
2.2 Software
A software is the program that allows you to “talk” to the computer. First of all, the
computer must have a program which is called the operating system. The operating
system is a special program which was written by experts and its main purpose is to
allow the machine to interact with you. The operating system controls the computer’s
resources. If you want to run a program, you will tell the operating system the name of
the file that contains it, and the operating system will run the program. This program
which you want to run is called an application program. Application programs can be
programs which you buy, or it can be programs which you write yourself.
A program is a set of instructions for a computer to follow. It can be a simple set of
instructions, or a complex one. In this course you will learn how to design and write
programs. Programs can be written using computer languages. In this course we will use
the C++ language to practice our program writing.
3.0 How to design and write programs?
If you want to write a program, you must first design it. But before you can do any designing,
you must first know what it is that you want and what you want to achieve. All these are part of
a process called the software development life cycle (SDLC).
3.1 Software development life cycle
What is SDLC? When you decide to write a program, it is to solve a problem faced by a
user or to perform a certain task as required by a user. Writing a program in real life will
in many cases involve large, complex and usable software. Writing and designing the
program itself is not enough. A program, or in the case of a large and complex program
we usually call software, the story does not end with the design and the coding. The
software has a life cycle. There are six steps in the software development life cycle and
they are as follows:
1.
2.
3.
4.
5.
6.
Analysis (define the problem)
Design the software (algorithm design)
Implementation (writing the program code using a specific language)
Testing (test the program)
Maintenance
Obsolescent
In this course, we will concentrate on the first three steps; analysis of the problem,
designing the program, and writing the program code.
3.2 Problem Solving
As mentioned in the earlier section, before you can write a good program, you must first
analyse the problem that you want to solve, and then to design the algorithm of the
program before you can write the program codes.
You have to understand the problem before you can attempt to solve it. To understand
the problem, you need to analyze it. The purpose of analyzing the problem is for you to
determine what is it that the program must to do. This is the first important step and
you must be able to determine what is task the program need to perform, and you must
specify this completely and precisely. One way that can help you get started is by
determining the output that the program must produce. In order to get an output, the
program requires input. You must determine what that input is , and how does the
program process the input to produce the output. It is important for you to remember
that a program consist of the following:
INPUT
PROCESS
OUTPUT
Many times, you will have to consult with the program’s potential users – the person for
whom you are creating the program, to get a description of the program’s output, and
input. An output can be what the user wants to see displayed on the computer screen,
or what the user wants to see printed on a page, or what the user wants to store in a file
on a storage device. An input is the information or data that the computer need in
order to produce the output. Input can be given to the program through the keyboard,
or it can be a data taken from a file in a storage device, or in can be any from any other
input devices. Let us look at a simple example.
Problem:
Ali is a businessman who runs a foreign exchange bureau, exclusively for
exchange currencies from US dollars to Malaysian Ringgit. The conversion
rate between these two currencies varies daily. Ali wants a program that
would help him calculate the conversion and display it on the computer’s
monitor for his customer to see.
Let’s analyze this problem. You can start with determining the output of the program.
What is it? The output of the program is to display the amount in Malaysian Ringgit on
the computer screen. What is the input? The input of the program is the amount of US
dollar, keyed in by the user from the keyboard. And you also must have the conversion
rate. Conversion rates for foreign exchange fluctuates daily. Therefore, this information
must be given to the computer. So, this is another input which is required by this
program.
After you have determined the input and the output of the program, the next step is to
figure out the process that will take the input and produce the output that you want.
Besides the analysis of the problem, this is another challenging phase in writing a
program. This is called the problem-solving phase and the end of this phase you should
have something that is called an algorithm. An algorithm is a sequence of instructions
that leads to a solution.
Deriving an algorithm is an iterative process. After you have prepared the first version of
your algorithm, you have to check the algorithm by performing a process called deskchecking or hand-tracing. This process requires you to execute each step of the
algorithm in your mind, or with the help of pen and paper. The purpose of this process is
to verify that the algorithm is not missing any steps and will produce the correct output.
If the algorithm does not perform as it should, then it has to be redesigned. This
iterative process will go on until the desk-checking confirms that the algorithm is
correct. After you are satisfied with the algorithm which you have derived, you may
now code your program in a chosen programming language. After you have written the
codes to your program on a computer, you may run the program, and hope that you
program will run and perform the tasks as you expected.
However, most of the time, you will find that your first few tries at running the program
will not be successful even though you have checked and rechecked the algorithm. We
will discuss why in later sections. When this happens, you will need to figure out the
reason why your program does not perform as it should, you will have to make some
changes to your codes (and maybe even your algorithm), and you will have to do this
over and over again until you get the result that you want.
The following diagram summarizes the steps that are involved in writing a program.
START
Problem definition
Algorithm design &
desk-checking
Coding
Testing
WORKING
PROGRAM
4.0 Programming Methodology
An application program is usually written to do a specific task or solve a specific problem. But
before you can write your program in a chosen computer language, you must first figure out
how to instruct a computer to perform the task or how to solve the problem that need to be
solved. In order to do that, you have to analyze the problem: determine the output the
program should produce, and then determine the input the program requires in order to
produce such output. Next, you need to figure out the steps that need to be carried out to
perform the task or solve the problem. The steps are instructions that the program need to
need to carry out, that will transform the program’s input into its output, and is usually called
the algorithm of the program.
4.1 Algorithm
Relook at Problem 1.
Let us look at the earlier example. You want to write a program that will help user
convert US dollar into Malaysian Ringgit. You already determined the output of the
program. The output will be to display the amount in Malaysian Ringgit on the computer
screen. The input of the program is the amount of US dollar, keyed in by the user from
the keyboard. There is also a second input, which is the conversion rate. Now you have
to figure out the process that will transform the value of the US dollars into an
equivalent value in Malaysian Ringgit. In this example, the process is not very complex.
To convert the value, the computer has to multiply the value of the US dollars by the
conversion rate. We can put this information in an Input-Process-Output (IPO) table as
shown below:
Table 1. Input-Process-Output (IPO) Chart
Input
Value of USD
Conversion rate
Process
Output
Algorithm :
Value in RM
1. User enter the value of US dollars
(USD)
2. Enter the conversion rate
3. Calculate the value in Malaysian ringgit
(RM) by multiplying the value of USD
by the conversion rate
4. Display the value in RM
It is safe to say that an algorithm usually begins with getting input data, then processing
that data, and then it usually end with the display or printing of output. In this example,
the algorithm is specified as a list of steps, from step 1, to the last step. Some
programmers prefer to design the algorithm using a mixture of English words and codelike statements. This is called pseudocode.
4.2 Pseudocode
A pesudocode is a an artificial and informal language, which is similar to everyday
English, but is also allows you to use some kind of coding statements similar to program
language codes. There is no specific standards for pseudocodes; each person may have
his or her own style of writing pseudocode. If a programmer is familiar with C++
language, he or she may feel comfortable to use codes similar to C++, codes which are
not actually C++ code. But why use codes similar to C++ codes, why not just use actual
C++ codes? In pseudocode, he can use a mixture of C++ like codes and English. By doing
this, he is able to write the algorithm without having to worry about the details of C++
syntax (rules of writing C++ codes). Below is how the pseudocode for Example 1 may be
written.
Start
Get value of US dollars (USD)
Get conversion rate
RM = USD x conversion rate
Display value in RM
End Program
There is another alternative to design algorithm for a program, and that is by drawing a
diagram called a flowchart.
4.3 Flowchart
Unlike pseudocode, flowcharts uses a set of standardized symbols. There are specific
symbols for input and output; symbol for processes, symbols for start and stop of
program, symbol for decision and symbol to represent the flow of the steps. There are
other symbols for other puposes, but the ones that are most common ate summarized
in the following diagram.
Table 2. Flowchart Symbols
Oval - To start or terminate program / module
Parallelogram - For input / output data eg. Read data, display
data, print data
Rectangle - For process, eg. Calculation, such as RM = USD x rate
Diamond - For decision (we will discuss this in later chapters)
Arrow - For showing flow of process
Below is how the flowchart for Example 1 looks like.
Start
Get
USD
Get Conv
Rate
RM = USD X Rate
Display
RM
Stop
4.4 Desk-checking
When you design your algorithm, before you code them into a specific program
language, you should ensure that the algorithm is complete and that you have not
missed any steps, and that the steps are correct. To do this, you have to perform deskchecking. Some people call this activity hand-tracing. How do you perform a deskcheck?
Before you start, you must first choose a set of input values, then you must compute or
calculate the steps manually to get the expected outputs for the set of inputs. For
example, in the currency converter problem you may choose the following set of input:
Set 1 : USD = 100
Converrion rate = 3.48
Set 2 : USD = 33
Conversion rate = 3.50
For each of the input set, you will then manually calculate the expected outcome.
Therefore, the outcome for the input sets are as follows :
Set 1: Output = 100 x 3.48 = RM348.00
Set 2: Output = 33 x 3.50 = RM115.50
Then using the input sets, by going through each step of the algorithm. You can choose
to use either the pesudocode version of the flowchart version. Let us check the
pseudocode version.
Start
Get value of US dollars (USD)
Get conversion rate
RM = USD x conversion rate
Display value in RM
End Program
To assist in the desk-checking, first create a table that contains a column for each
input, output, any temporary calculation (if necessary). For the program given
above, you will need a table as shown in Table 3.
The first instruction in the algorithm is for the user to enter the value of USD to be
converted, and the rate of conversion. Place these values in the corresponding
columns as shown in the following table.
Table 3. Desk Check Table – USD and conversion rate entered
USD
Conversion Rate
100
3.48
RM
The next instruction is to calculate the RM value based on the formula given, which
is to calculate the value of USD by the value of conversion rate. Using the table, you
will get the values that are to be calculated. So, if for example, the USD column in
the table is empty, then you know that your algorithm has missed a step. Now, since
you have the values in the respective columns, use those values to calculate the RM
value. 100 x 3.48 = 348.00, and place that value in the RM column as shown in Table
4 below.
Table 4. RM value calculated and entered in the check table.
USD
Conversion Rate
RM
100
3.48
348.00
The last instruction is to display the RM value on the computer screen. In this case,
the value 348.00 will be displayed, because that is the value that appears in the
table’s RM column. If this value is consistent with the manual calculation you
performed earlier, prior to desk-checking the algorithm, then the algorithm appears
to be correct. You should however, perform more desk checking using different sets
of input values. You must now try to conduct desk checking using the second set of
values given earlier.
5.0 More Examples
With the increase of petrol prices, your friend Ahmad wants a program that will
calculate how much km per liter of petrol was consumed. For example, when starting a
journey, Ahmad will fill up his car’s tank to full and reset his car’s trip meter to zero.
After travelling 378 miles, Ahmad stopped at a petrol station to refuel. The car required
25 liters to fill up the tank. The program should calculate the number of km the car can
be driven per liter.
5.1 Algorithm
Table 5. IPO chart
Input
Miles driven
Petrol used
Process
Algorithm :
1. User enter the number of km driven
2. Enter the liter of petrol used
3. Calculate km per liter by dividing
number of km driven by the number of
liter petrol used
4. Display the value of km per liter
5.2 Pseudocode
Start
Get value of km driven
Get liter of petrol used
Km per liter = km driven / liter of petrol used
Display value of km per liter
End Program
Output
Km per liter
5.3 Desk-checking
First choose a set of input values. Then you must compute or calculate the steps
manually to get the expected outputs for the set of inputs. For example, in the problem
given above, you may choose the following set of input:
Set 1 : km driven = 324
Liter of petrol used = 35
Set 2 : km driven = 675
Liter of petrol used = 60
For each of the input set, you will then manually calculate the expected outcome.
Therefore, the outcome for the input sets is as follows:
Set 1: Output = 324 divided by 35 = 9.25 km per liter
Set 2: Output = 675 x 60 = 11.25 km per liter
Let us check the pseudocode version.
Start
Get value of km driven
Get liter of petrol used
Km per liter = km driven / liter of petrol used
Display value of km per liter
End Program
First, create a table that contains a column for each input, output. For the program
given above, you will need a table as shown in Table 6. The first instruction in the
algorithm is for the user to enter the value of km driven, and the liter of petrol used.
Place these values in the corresponding columns as shown in the following table.
Table 6. Desk Check Table – values for km driven petrol used entered
Km driven
Petrol used
324
35
Km per liter
The next instruction is to calculate the km per liter value based on the formula given,
which is to divide the value of km driven by the value of petrol used. Using the table,
you will get the values that are to be calculated. So, if for example, the km driven
column or the petrol used column in the table is empty, then you know that your
algorithm has missed a step. Now, since you have the values in the respective
columns, use those values to calculate the km per liter value. 324 divided by 35 =
9.25, and place that value in the km per liter column as shown in Table 7 below.
Table 7. Km per liter value calculated and entered in the check table.
Km driven
Petrol used
Km per liter
324
35
9.25
The last instruction is to display the km per liter value on the computer screen. In
this case, the value 9.25 will be displayed, because that is the value that appears in
the table’s RM column. If this value is consistent with the manual calculation you
performed earlier, prior to desk-checking the algorithm, then the algorithm appears
to be correct. You should however, perform more desk checking using different sets
of input values.
For practice, you must now try to conduct desk checking using the second set of
values given earlier.
6.0 Coding, compiling and running a C++ program
6.1 Layout of a C++ program
Programs are written using programming languages. There are many programming
languages ranging from the earlier languages such as FOTRAN, COBOL and Pascal, to
more recent languages such as C++, Java, Visual Basic, ASP, PHP and so on. These
languages are called high-level languages and they resemble English language. They are
designed that way so that it would be easy for humans to read and write in these
languages.
Besides high-level languages, there are also low-level languages and machine language.
You can try and find out more about these languages yourself. In this course, we will
concentrate on the C++ language.
Once you have decided which language you are going to use to write and later run your
program, you must learn the “rules” or the “grammar” of using the language. First of all,
you must know that each language must be written or coded in a specific way, or a
specific layout. There are some specific “statements” which you must have in your
program and it must be typed exactly as the language requires it. Let’s look at an
example of a C++ program. This program is a simple program and I will not design the
algorithm for it. This program will display the word “HELLO” on the screen. The program
looks like this :
/* This is my first program */
/*Program HELLO */
#include <iostream>
using namespace std;
int main()
{
cout << “HELLO\n”;
system("pause"); //this statement is needed when using DEV C++
return 0;
}
This program codes can be typed or edited in any text editor such as a Notepad.
However, you can also use any C++ software development kit which you purchase or
download. The kit which contains both the editor and compiler in one integrated
environment is called an IDE or Integrated Development Environment. Examples of
these kits are Microsoft Visual Studio, Dev C ++, among others. There is one thing that
you should be aware of, which is, each IDE may have it’s own “rules”, and therefore, the
examples given here may have to be adapted to run on the IDE you are using.
Now, let’s try to understand the Hello program given above. To make it easier to refer to
the program statements, I will place the line number for each of the line in the program
codes. The program code can be saved as a file and we usually refer to these codes as
source codes.
1. /* This is my first program */
2. /*Program HELLO */
3.
4. #include <iostream>
5. using namespace std;
6.
7. int main()
8. {
9.
cout << “HELLO\n”;
10.
system(“pause”); //this statement is needed when using DEV C++
11.
return 0;
12. }
Explanation of the C++ codes :
Lines 1 and 2 are comment lines. This is indicated by the usage of the /* and */
symbols. The /* symbol indicates the beginning of a comment and the */ symbol
indicates the end of the comment line. Lines 3 and 6 were intentionally left blank to add
readability to the program codes. They do not have any effect on the execution of the
program.
Line 4, has the #include directive. Lines which start with “#” are called pre-processor
directives. The #include directive has a specific job and it must be present in your C++
program. It tells the compiler to include the contents of a particular file in the current
program. At this point of time, you only need to use the directive
#include <iostream>
What this directive does, is to ask the compiler to include the contents of the iostream
file. The iostream file must be included in any
program that uses input/output
statements such as cin statement to input data from keyboard, and cout statement to
output data to the screen. C++ is a case sentitive. Which means, if you type #Include
(with a capital letter “I”), it will create an error in your program. This is called a syntax
error, which means the program (or more accurately, the compiler) does not recognize
the word “Include”.
Note: You may find that in some C++ environment, the file is specified as iostream.h
instead of iostream.. If the environment requires this, you can replace lines 4 and line 5
with the following statement
#include<iostream.h>
In many cases, you are not to include line 5. You can look at sample programs provide by
the IDE to see which style it requires.
Line 7 has the beginning of the program, which is the statement
int main()
The word main() is the name of a function. A function is a block of codes placed
between the curly brackets { and }. You know that a word is a function if it has ()
following it, such as main(). We will discuss more about functions later. In many cases,
the function main() is the beginning of the C++ program, therefore this function is
required in C++ programs. The word int preceding the word main indicates that the
function main returns an integer number. It is also possible to have a void main()
statement to indicate that the main function does not return any value. Actually the int
main() statement is called a function header. It is the beginning of a function. A program
can have only one main() function. However, there may be other additional functions in
a C++ program, as we will find out later.
The main() function is followed by the body of the function. The beginning of the body
of the function is indicated by the curly bracket {, and the end of the body of the
function is indicated by the curly bracket }. Lines 8 and 12 show these symbols
respectively. It is in the body of the main() function where the logic or the algorithm of
the program are located. In the program shown above, all the program will do is to print
the word “HELLO” on the display monitor. This is done by using the cout statement as
shown in line 9.
Line 11 contains the statement to complement the int main() statement at the
beginning of the program. This return statement simply return the value “0” to the
operating system at the end of the program. Value 0 indicates that the program has
terminated successfully. We will elaborate this return statement when we discuss
functions in later chapters.
The figure below summarizes the important points mentioned in the above paragraph :
Draw diagram similar to pg 26 of Ivor’s book
Figure 1.
6.2 Coding a C++ program
Once we have determined the codes for the program, how do we type them into the
program and run them? For this course, we are going to use the Dev C++ IDE which
can be downloaded from the internet.
After you have downloaded the software, you can open the editor which is shown in
the following figure. You can also use other C++ IDE as mentioned earlier.
You can open a new source file where you will type the source codes given in the
HELLO program above. Figure 3 illustrates.
6.3 Compiling and running C++ program
Once you have typed in the codes, you need to compile the codes. To ensure that
you don’t lose your codes, you should save the codes before compiling them. In
some IDEs, the word “build” is used instead of compile. What this process does is for
the system to read your source code and understand it. What happens is that the
system compiles the source codes into object code, and a linker links the object code
to machine code required for the program to run. If you look in the directory where
you saved your source code, you will find new files which have been created by the
system. The final step is to run or execute the compiled codes.
If your codes did not follow the correct syntax rules, the compiler will identify the
errors. However, it does not guarantee that the program will run correctly. During
execution, the program may terminate due to errors in the algorithm, and this type
of errors is referred as logical error. Another problem you may encounter is that
even though the program does not terminate, it could still provide incorrect output,
and this is also caused by error in the algorithm. In cases like these, you will have to
re examine your codes, your algorithm, and maybe even your problem analysis.
For the above program, the compilation of the codes should be successful and will
show the following response.
Once the compilation is successful, you can execute the program, and the result will
be as in the figure below.
6.4 More Practice
You can now try to type in the codes for the problem which we have analyzed
earlier.
Without trying to understand the whole program at this point of time, the following
is the codes that would be written for the currency conversion problem stated
earlier.
#include <iostream>
using namespace std;
int main()
{
float usdAmount, cRate, rmAmount;
cout << "Amount of USD to convert : ";
cin >> usdAmount;
cout << "Enter conversion rate : ";
cin >> cRate;
rmAmount = usdAmount * cRate;
cout << "USD" << usdAmount << " is equivalent to RM" << rmAmount << endl;
system("pause"); //this statement is needed when using DEV C++
return 0;
}
After keying in the source codes into the IDE editor, you should save it in a file. Then
compile the source codes. If you get any error during compilation, check that you have
typed in each line of code correctly. If your compilation is successful, you can execute
the program. In this program, when the program is executed, it requires the value od
USD and conversion rate as inputs. You can use the values that we have determined
earlier for the desk-checking process, and once the values are entered, the program will
display the value in RM. The following figure illustrates the output of the program using
the two sets of input values given.
7.0 Problem Solving Practice
Let’s try to solve this simple problem. Let’s say you want the computer to add two numbers
which you enter through an input device, and you want the computer to display the answer
on the monitor. How would you write the instructions?
When figuring out an algorithm, you must remember that the computer does not have a
brain, and therefore must receive explicit instructions. So, in order to perform the task
stated in the above example, you will need to give instruction as follows.
First, you will ask the computer to get both numbers from the input device, add them up
and then display the answer on the answer on the monitor.
But is it practical to write the instructions in long paragraph as written above? If you have a
complex problem to solve, you may have a very long paragraph of instructions. This makes
it very difficult to read. It would be better to write the instructions as a list. So the above
paragraph can be written in a form of a list as follows :
Get the numbers to be added from the input device
Add both numbers
Display the answer on the monitor
8.0 Exercises
Download