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

Computer Programming

This document provides an introduction to computer programming and the Pascal programming language. It discusses what computer programming is, the development of programming languages from machine language to high-level languages, and provides an overview of the key components of a Pascal program including the program header, comments, variable declaration, and the instruction block. It also demonstrates a simple "Hello World" Pascal program and discusses concepts like procedures, formatting output, and indentation.

Uploaded by

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

Computer Programming

This document provides an introduction to computer programming and the Pascal programming language. It discusses what computer programming is, the development of programming languages from machine language to high-level languages, and provides an overview of the key components of a Pascal program including the program header, comments, variable declaration, and the instruction block. It also demonstrates a simple "Hello World" Pascal program and discusses concepts like procedures, formatting output, and indentation.

Uploaded by

Shadrick Ilunga
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 16

INTRODUCTION TO COMPUTER PROGRAMMING

Introduction to Programming Languages

What is computer programming?

Computers are made up of hardware components that in themselves are not capable of
carrying out any processing of data to produce results. Computer software can make the
hardware carry out calculations and make logical decisions has to be created by a computer
programmer or software developer.

Writing a computer program requires the computer programmer to think logically and work
accurately in order to create the instructions for the hardware.

As you learnt in Chapter 3, data and instructions are represented as a series of 0s and 1s at the
most basic level in a computer. These basic elements are called bits. Eight bits make up a
byte. A byte is used to represent a simple character, such as a letter of the alphabet.

Computers work at the level of these 0s and 1s to store data and to receive instructions. This
is known as machine language or native code.

The first computer programs were written in machine language. This required the human
computer programmers to also work with 0s and 1s to give the computer instructions and to
feed it data. These humans therefore had to be able to ‘speak’ machine language. This is very
difficult and requires a high level of computer skills to carry out.

For example, the letter A is represented by the binary code 0100001. This means that a
programmer would have to enter this combination instead of just pressing the letter A on a
keyboard! Imagine how much work this took and how many chances there were to make
mistakes. Originally computers did not have keyboards as we know them. Input was done
through a series of switches that were set to either 0 or 1 for the input.

A low-level computer programming language such as an Assembler works directly at the


hardware level of the computer. These languages belong to the first generation of computer.
Fortunately, computer programming languages have developed over the years to so-called
high-level programming languages that use English words, which are easier for humans to
understand. Note though that some words used in programming are not normal English
words used everyday. High-level language source code needs a compiler or an interpreter to
convert the code into machine language that hardware can understand.

A computer converts the high-level programming source code into machine language. It is
used to create an executable program from the source code. Executable programs have the
exe file extension, for example Winword.exe.

An interpreter is a program that is able to execute the program instructions written in a high
level language. It does this by executing the program code directly or by executing the
already compiled code.

Examples of computer programming languages are COBOL, Fortran and Pascal, and more
modern languages such as C++, Java, Python and Delphi. There are also programming
languages used for other more specific purposes. For example SQL (Structured Query
Language) is used specifically to interact with and extract information from databases.

PROGRAMMING WITH PASCAL

INTRODUCTION TO PASCAL

Choose a compiler

In order to be able to write a computer program in Pascal you need a pascal complier.
Fortunately, there are a number of free compilers that you can download off the internet. In
this book, we’ll be using Turbo Pascal 7.0 for Windows 7 as the compiler.

Installing and running Turbo Pascal 7.0

Turbo Pascal 7.0 is a DOS-based program and therefore cannot run on a Windows operating
system without an emulator program. An emulator program, such as DOSBox, creates a
virtual version of an older IBM-compatible PC running the MS-DOS operating system. both
the Turbo Pascal 7.0 and DOSBox programs are on your Pupil CD.
The compiler provides you with a space in which to type the programming source code, and
is used to create the executable program file. The person using your program will run this
executable file.

The example in the editor window above shows the code for a simple program that will
display the message “Hello World” on the computer screen. Traditionally, this is the most
basic computer program for anyone learning any programming language to write. We will
investigate what each line means in due course.

Before you start, it is important to remember the following:-

 You must type with 100% accuracy- remember you are giving the computer specific
instructions and it is not intelligent on its own; it cannot cope with interpreting mistakes
in the programming code.
 Pascal is not case-sensitive. Note the use of indentation, and the syntax of semicolons and
full stops.
 Pascal ignores black lines. They are used only to make your code more readable by
separating sections of code.

PROGRAM STRUCTURE

A Pascal program is divided into two main sections- the program header and the instructions
block.

Program header

The program header is always the first line of a Pascal program. It begins with the keyword
PROGRAM followed by an identifier (name) and a semicolon. The identifier should describe
the function of the program. The identifier starts with a letter, followed by letters or numbers
or the underscore (_) character only. For the purposes of conformity, we will use capital
letters for keywords and sentence case for identifiers.

Comments
This line is a comment. Comments are messages that the programmer leaves in the code,
usually to describe what the following section of code does. Comments appear between (*
and*) and are ignored by the compiler during execution. Comments are found beneath the
program header and throughout the instruction block. They make a program clear and
understandable later and for other programmers.

Comments are also known as the internal documentation of a program. You will be surprised
how easily you forget your own thought processes when you program a great deal.
Comments serve to remind the programmer how they were thinking at a particular point.
They also serve as explanations to other programmers. Programmers often work on teams
where each person is responsible for different modules in a bigger program, and so they need
to be able to follow each other’s logic and reasoning.

Comments are not only used by the programmer to make program notes but can also be used
to temporarily exclude code that has a mistake and will not compile (a syntax error) or code
that causes incorrect or unexpected results (a logic error).

When there is a syntax error, your code will not compile. Syntax errors occur as a result of
typing errors or from disobeying one of the Pascal programming rules. With a logic error, the
code compiles, but produces an incorrect result when the program is run. A third type of error
is a runtime error. Here the code compiles, but when the user runs the program, some kind of
error occurs that cause the program to crash. An example is an unintended division by zero.

Variable declaration

A variable is similar to a variable in Mathematics- it can assume varying values. The VAR
statement is used to introduce any suitable variables that will be used later in the program.
When you declare variables, the compiler reserves space for the variables in primary
memory.

Instruction block

The instruction block is the executable part of the program. It starts with the reserved word
BEGIN and finishes with the reserved word END followed by a period (full stop).
Written procedure

The reserved word WriteIn is the name of a standard procedure by means of which the
computer can communicate with the user. This communication can only take place on the
screen or the printer. What appears in the brackets () after the WriteIn command will
determine whether the display is reflected on the screen or on the printer.

Clrscr procedure

The reserved world Clrscr is a procedure that clears the screen. It makes output from the
screen look neater. In order to use the Clrscr command, the USES clause (use screen control
function) must be included.

Readln Procedure

The reserved word Readln is a procedure that establishes communication between the
computer and the user. It causes the compiler to wait for input from the keyboard before the
execution of the program can be completed.

Consecutive Pascal statements

Consecutive statements within the instruction block are separated by semicolons (;). The
statements can appear on the same line next to each other separated by semicolons, or on
separate lines separated by semicolons. It is not necessary to have a semicolon before the last
END statement.

Indentation

Each statement within the instruction block is indented to make it more readable

Display output on screen

We are going to learn how to produce output to screen using the Write and WriteIn
statements.

The difference between the Write and WriteIn statements is as follows:-


 After a Write statement has been executed, the output is produced from the current
position of the cursor but the cursor remains on the same line of output.
 After a WriteIn statement has been executed, the output is produced from the current
position of the cursor and the cursor moves to the next line of output.

In order to make the second sentence appear on its own line you will need to add a special
character or a special instruction to the code.

Formatting output-aligning output to columns

The format of output indicates how the information printed will be presented. This includes
spacing, the printing of blank lines and column positioning.

Notes

 The number within the {} brackets are for reference purposes only are not part of the
program.
 In line {1} the string constant is only to display column positions.
 Thus far we have been left-justifying constants to be printed as they are for line {1}.
 In line {2} the first constant, Surname, is left-justified and the second constant, first
name, is right-justified. We have applied right-justified formatting by adding the syntax
of a colon (:) and an integer number after the constant to be printed. This integer number
(:15) after the constant specifies the field width, that is, the number of column positions
to be used for printing the character constant, using right justification. It is important to
note that the field width is measured from just after the current position of the cursor.
 In line {3} the constant will be right-justified as well.

Sometimes, when producing two left-justified columns, the output production is not correctly
aligned in the second column because of the different sizes of second column in the first column.
Remember that the field width of the second column starts from the end of the previous item to
be printed in the list. In this case, you will need to align the constants using the LENGTH
function to produce the correct output.
A function is pre-written code to achieve a particular purpose. A call to a function is always
within another expression and cannot be used as a standalone statement. The LENGTH function
returns the length of a string constant.

The out put should look like the following:

Surname First Name

Bomela Nomsa

Lubasi Pule

Mwape Nandi

How numbers behave in the output

You use the Write and WriteIn statements to print numbers as well as the results for
mathematical expressions. When printing integers, real numbers or mathematical expressions –
such as 3 +4, 6.5 -4 or 7 * 8) – these are not surrounded by single quotes. If these are surrounded
by single quotes, then they become string constants instead of numbers, and then cannot be used
in mathematical operations.

You can print integers, real numbers and mathematical expressions without formatting.
However, note that real numbers will be output in exponential (E) form if not formatted, which is
not easy to interpret. To format:

 An integer number, you apply single formatting, for example WriteIn (10:5). The integer
number 10 is right-formatted within 5 column spaces.
 A real number, you apply double formatting, for example WriteIn (-5, 6:10:2). Two
column spaces are set aside for two decimal places.

Display output on a printer


You can instruct the computer to print the results to the printer instead of displaying the
result on the screen. In the USES part you need to add a printer:

Pre-defined data types and variables in Pascal

The use of variables

So far we have been creating very simple programs that only use an output statement. It is
usually necessary to hold values in the computer memory (RAM) while running a program.
Variables are used as placeholders in the computer memory in which certain values can be
stored.

A computer needs to be told what type of data needs to be stored in each variable. Remember
that computer memory is able to store data in units called bytes. The Pupil CD contains a
summary of the pre-defined data types that can be used in Pascal. The summary of the pre-
defined data types that can be used in Pascal. The summary also indicates that size of the data
values that can be stored in each type of variable. Note that the sizes and ranges may differ
according to the compiler and computer you are using.

Access the file PB_Chapter_5_Data_Types.pdf on your Pupil CD to compare the ranges of


the various data types.

Don’t try to memorize the actual size of each data type. Just remember that it is good
programming practice to use the smallest possible data type that your programs don’t occupy
too much computer memory.

Declare variables

Variables need to be given a unique identifier name. The rules for an identifier are as
follows:-

 It must start with a letter.


 It may contain letters, numbers or the underscore (_) character.
 It may contain up to 127 characters. In some versions of Pascal, only the first eight
characters of an identifier are significant.
 It may not be a reserved word or a keyword. See the Pascal Reserved Words file on the
Pupil CD.

Variable identifiers should have descriptive names that identify what the variable stores. This
makes is easier for you to follow your own code and for others to understand what your code
is doing. By convention, variable identifiers are in lower-case letters. Note that Pascal is not
case sensitive. It will recognize number and NUMBER as being the same variable identifier.
The process of creating a variable, starting what type of data it will store and giving it a name
is called declaration.

Initialise Variables

Declaring variables doesn’t assign values to those variables. The process of assigning a value
to a variable is called initialization. You initialize a variable in the instruction block of your
ode. If you declared an integer variable, then you can only assign integer values to the integer
variable. The same works for all other data types. The only exception is the real variable data
type, to which you can assign an integer or a real number.

Use string variables

Variables that can store alphanumeric values that are longer than one single character are
known as strings. The syntax for the string data type is String(number). The number in
brackets indicates the maximum length of the string. Without the brackets, the characters
limit is 255. String can consist of combinations of:

 ‘a’ to ‘z’ or ‘A’ to ‘Z’


 ‘0’ – ‘9’
 Any ASCII character.

You can also join strings and other variables together in an output statement. look at the next
section of code for an example that will display the message “I am 16 years old.”

Note that the variable, age, doesn’t have any quotation marks surrounding it, because we are
outputting the value stored in the variable age. If we put the variable age in the WriteIn
statement within single quotation marks, then it will output the string age instead of the value
stored in the variable age.

Using strings in Pascal

You can join strings using the CONCAT function. The general syntax of the CONCAT
function is:

CONCAT (string 1, string 2,..) OR String 1 + String 2+..

The string is stored in a array structure, which allows you to access each character of the
string. Each character is stored in a particular position in the string.

You can insert a string at a certain position in another string by using the INSERT procedure.
The syntax for the INSERT procedure is:

INSERT (Insert String, Character String, Position):

This inserts the string Insert String into the string Character String starting at position in the
character String.

BASIC OPERATORS IN PASCAL

The use of the: = sign as an assignment operator has already been discussed. There are a
variety of operators used in Pascal, such as arithmetic operators and logical operators. For
now, we will look at the arithmetic operators.

Arithmetic Operators

There are five arithmetical operators that are used in Pascal:

 +, for addition
 -, for subtraction
 *, for multiplication
 DIV, for integer division
 /, for real division
 MOD, for modulus (remainder of division of two integer values).
Note that if you add, subtract, multiply, divide (DIV) or modulus (MOD) two integer
numbers, then the answer will be an integer number. If you add, subtract, multiply or divide
(/) two real numbers, then the answer will be a real number.

Note that the order of operations is the same as you’ve learnt in basic Mathematics. Use
round brackets to change the order of operations. For example, a +b *c will produce a
different answer to (a + b) *c. In the first case, the multiplication will happen before the
addition. In the second case, you force the addition to take place before the multiplication
and division followed by addition and subtraction.

Notes

 Just line in ordinary Mathematics, division by zero is not permitted. If done in Pascal it will
lead to a Division by Zero error.
 When you divide an integer value by another integer value, the answer is always rounded
down and any decimals are discarded. This is known as integer division. This is a very
important point to remember as you might do this accidentally and get unexpectedly
incorrect results in a program. It is useful in certain cases. For example, when you would like
to know how many minutes there are if you have been given a value in seconds.

Obtain basic user input

The most common input device is the keyboard. The simplest way to capture user input from
the keyboard is to use the Reading statement. The Reading statement allows data values that
exist independently of the program to be entered via the keyboard and associated with the
variables declared in the program. Note that the data value input must be the same data type
as that of the variable it will be stored in.

Overwriting values in variables

When you have initialized a variable with a certain value it is possible to change that value in
a number of ways. This process is called overwriting.

Define Constants
Constants are fixed values that the program may not change. For example, if you’re writing a

program to work out the perimeter or the area of a circle, you will need Pi( ). You could

create the value of Pi as a constant. This makes sense because the value of Pi never changes.
Similarly, when the program you’re writing has limits such as an upper and a lower age limit
for participants in an activity, you could set those values as constants in your program.

The constant declaration section must appear before the VAR declaration. Note that in the
cost declaration the equals sign rather than the assignment sign is used.

User-defined data types

So far we have used the pre-defined data types in Pascal. It is also possible to define your
own data types based on the existing data types. Basically, this means that you are simply
giving an existing data type a new name. This is done for two reasons-either you find the pre-
defined data type too long to type and you can want to redefine it with a shorter name, or you
use a particular data type very often and want to use an easy-to-remember reference to the
data type.

Useful Mathematical Functions

Pascal provides some useful mathematical functions such as:

 Sqrt(x) to determine the square root of a number x.


 Exp (power* In(base)) to raise the number base to the power of number power.

PROGRAMMING WITH C++

INTRODUCTION TO C++

Choose a compiler

In order to be able to write a computer program in C++ you need a C++ compiler.
Fortunately, there is a number of free compilers that you can download off the Internet. In
this book, we’ll be using Turbo C++ as the compiler. You could also download Microsoft’s
Visual Studio Express.
The compiler provides you with a space in which to type the programming source code, and
is used to create the executable program file. The person using your program will run this
executable file.

Write your first program

The programs we will write in this chapter are known as console programs as they execute on
the old DOS command line rather than the window frames that we are used to in normal
programs today.

The example shows the code for a simple program that will display the message “Hello
World!” on the computer screen. Traditionally, this is the most basic computer program for
anyone learning any programming language to write. We will investigate what each line
means in due course. Before you start, it is important to remember the following:

 You must type with 100% accuracy-remember you are giving the computer specific
instructions and it is not intelligent on its own; it cannot cope with interpreting mistakes in
the programming code.
 C++ is case-sensitive and the use of upper-case and lower-case characters can have very
different meanings in the code.
 C++ ignores blank lines. They are used only to make your code more readable by separating
sections of code.

Explanation of the basic code structure

This line is an instruction for the compiler’s pre-processor that tells it to include the iostream
standard file. IO stands for Input and Output, so this has to do with the input from the user
and the output, usually to the computer screen. Directives for the pre-processor must start
with an # (hash) sign. Note that there is no semicolon at the end of line and that in newer C+
+ compilers such as Visual Studio, the .h must not be included.

This line is a comment. Comments are messages that the programmer leaves in the code,
usually to describe what the following section of code does. The compiler ignores all lines of
text that start with the double forward slash (//).
Comments are also known as the internal documentation of a program. You will be surprised
hoe easily you forget your own thought processes when you program a great deal. Comments
serve to remind the programmer how they were thinking at a particular point. They also serve
as explanations to other programmers. Programmers often work on teams where each person
is responsible for different modules in a bigger program, and so they need to be able to
follow each other’s logic and reasoning.

This is the start of the main function. This function is required in all C++ programs and is the
starting point of the execution of any program. Even if more functions have been coded into
a program, and even if they have been typed before the main function, the main function will
always execute first.

Note that the word main must be followed by a set of round brackets or parentheses ( ). The
use of brackets and the shape of brackets is very important in C++. Each opening bracket
must have a matching closing bracket.

Note too that the main function is followed by a set of curly brackets or braces {}. These
indicate thee beginning and end of the code that will be executed when this function is used.

This is a C++ statement that serves as an instruction to the computer. All statements must end
with a semicolon (;). This particular statement causes the words Hello World! To be
displayed on the computer screen. The standard output stream is represented by cout, which
places the characters that follow this code onto the computer screen.

The double smaller than signs << form the insertion operator, which inserts the data that
comes after it into the output stream.

This return statement indicates the end of the program. When this line has been reached, it
usually means the program has executed successfully. You will probably find that the
console window containing the output only pops up for a brief moment. You need to find
the .exe file created by your compiler and then run this file in your own console window. It
will probably not run successfully from inside Windows Explorer as you have not created a
Microsoft Windows application, but an older format of program. To make it easier for
yourself, copy the .exe file for your program directly to the root of the C: drive of your
computer. If this is not possible, then use your personal network drive.

Comments in C++

Comments are not only used by the programmer to make program notes but can also be used
to temporarily exclude code that has a mistake and will not compile (a syntax error) or code
that causes incorrect or unexpected results (a logic error).

When there is a syntax error, your code will not compile. Syntax errors occur as a result of
typing errors or from disobeying one of the Pascal programming rules. With a logic error, the
code compiles, but produces an incorrect result when the program is run. A third type of error
is a runtime error. Here the code compiles, but when the user runs the program, some kind of
error occurs that cause the program to crash. An example is an unintended division by zero.

Single lines are turned into comments by placing the double forward slash// at the beginning
of the line. To comment several lines you place /* at the start of the commented section, and
*/ at the end of the section.

The use of variables

So far we have been creating very simple programs that only use an output statement. It is
usually necessary to hold values in the computer memory (RAM) while running a program.
Variables are used as placeholders in the computer memory in which certain values can be
stored.

A computer needs to be told what type of data needs to be stored in each variable. Remember
that computer memory is able to store data in units called bytes. The Pupil CD contains a
summary of the pre-defined data types that can be used in Pascal. The summary of the pre-
defined data types that can be used in Pascal. The summary also indicates that size of the data
values that can be stored in each type of variable. Note that the sizes and ranges may differ
according to the compiler and computer you are using.

Access the file PB_Chapter_5_Data_Types.pdf on your Pupil CD to compare the ranges of


the various data types.
Don’t try to memorize the actual size of each data type. Just remember that it is good
programming practice to use the smallest possible data type that your programs don’t occupy
too much computer memory.

More advanced programs and concepts

Define constants

Constants are fixed values that the program may not change. For example, if you’re writing a

program to work out the perimeter or the area of a circle, you will need Pi( ). You could

create the value of Pi as a constant. This makes sense because the value of Pi never changes.
Similarly, when the program you’re writing has limits such as an upper and a lower age limit
for participants in an activity, you could set those values as constants in your program.

You might also like