0% found this document useful (0 votes)
47 views49 pages

Computer Programming and Applications: Topic 1

This document provides an introduction to computer programming and C++. It discusses the basics of a program, software, and hardware. It describes the main hardware components including the CPU, memory, input/output devices. It explains how programs are executed with the involvement of the operating system, compiler, and linker. The document also discusses different levels of abstraction in programming and some common software used.

Uploaded by

yip90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views49 pages

Computer Programming and Applications: Topic 1

This document provides an introduction to computer programming and C++. It discusses the basics of a program, software, and hardware. It describes the main hardware components including the CPU, memory, input/output devices. It explains how programs are executed with the involvement of the operating system, compiler, and linker. The document also discusses different levels of abstraction in programming and some common software used.

Uploaded by

yip90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Computer Programming

and Applications
Topic 1
Introduction to
Programming and C++

Basics
Program

A set of instructions for a computer to follow. We


usually say we run a program on the computer, and that the
computer executes the program.

Software

The collection of programs used by a computer. For


example, some might be written by you for specific purposes.
Some, known as systems software, operate the hardware and form
the platform for running other programs.

Hardware

The actual physical parts that make up a computer. For


example, central processing unit (CPU), main memory, secondary
memory, and input/output devices.

ENGG1111A: Computer Programming and Applications

Hardware
CPU
Input
devices

Main memory

Output
devices

Secondary
memory
ENGG1111A: Computer Programming and Applications

Input/output components
CPU
Input
devices

Main memory

An input device is any


device that allows
information to be
communicated to the
computer.
Keyboard and mouse
are both input devices.

Secondary
memory
ENGG1111A: Computer Programming and Applications

Output
devices
An output device allows
the computer to
communicate
information to the user.
A monitor is the most
common output device.

Internal hardware
components
CPU
Input
devices

Main memory

Output
devices

Secondary
memory
ENGG1111A: Computer Programming and Applications

Hardware components:
Memory
Main memory is used by an executing program. Its
contents are volatile which means they will be lost if,
for example, power is turned off.

Secondary memory provides permanent storage of


data in the form of files. Hard disks, SSDs, CDs, DVDs,
USB flash drives are common forms of secondary
memory.

ENGG1111A: Computer Programming and Applications

Hardware components:
Main memory
Main memory provides temporary
storage for data and for the program
being executed.
It is arranged into numbered locations.
Each location is a byte (8 bits) or, in
some architectures, a word (multiple
bytes).
Data items can be stored in these
locations. If the item requires more than
one byte, it is stored in multiple
adjacent bytes.
The computer keeps track of what type
of data is encoded in each location

ENGG1111A: Computer Programming and Applications

00000000
byte 1000

00110101

byte 1001

10001110

byte 1002

01111101

byte 1003

00000111

byte 1004

01101010

byte 1005

01000011

byte 1006

00001101

byte 1007

11100111

byte 1008

11000001

byte 1009

01100110

byte 1010

00000000

byte 1011

00000000

4 byte
location

2 byte
location
4 byte
location

Information is represented
as strings of 0s and 1s

Main memory: addresses


00000000

The number that identifies a


particular byte in memory is
called its address.
For large data items, the
address of its first byte is used
as the address of the entire
multiple-byte location.
[This is a bit of a simplification.
We'll see the full story later in the
course]

byte 1000

00110101

byte 1001

10001110

byte 1002

01111101

byte 1003

00000111

byte 1004

01101010

byte 1005

01000011

byte 1006

00001101

byte 1007

11100111

byte 1008

11000001

byte 1009

01100110

byte 1010

00000000

byte 1011

00000000

ENGG1111A: Computer Programming and Applications

4 byte location
with address
1000
2 byte location
with address
1004
4 byte location
with address
1006

Hardware components:
The CPU
Although this is at the heart of the machine, it simply
follows the instructions provided in a program and
executes the required operations.

The operations that the CPU can perform are very


simple for example:
moving data from one memory location to another;
simple arithmetic (add, subtract, multiply, etc.) involving
the contents of memory locations;

ENGG1111A: Computer Programming and Applications

Hardware: how much


detail?
Modern hardware components, particularly CPUs, are
very complex. For general purposes, however, we don't
need to program "close to the machine"; that is, we don't
have to write our programs using the language that the
CPU actually understands.
Languages like C++ allow us to work at a higher level of
abstraction than the language of the hardware.
So, we don't need to know the details of the underlying
hardware. A simple conceptual model is sufficient.

Abstraction is a key element


of computational thinking
ENGG1111A: Computer Programming and Applications

10

Typical levels of
abstraction

Application level
High-order
language level
Assembly level
Operating
system level

Increasingly
machine-oriented

Each level has its


own language
In 1111A we work at
this level
Increasingly
humanoriented

Instruction set
architecture level
Microcode level
Logic gate level

ENGG1111A: Computer Programming and Applications

11

Software
We use and work with many types of software in
programming. These include:
Operating systems
Command line interpreters
Editors
Compilers
Development environments
Debuggers

ENGG1111A: Computer Programming and Applications

12

Operating system (OS)


This is a program that is running whenever the
computer is on.
It acts as a manager to coordinate the allocation
of resources of a computer to the tasks it is
required to perform. These resources are things
like CPU time, main memory, etc.
It manages tasks such as reading data from disk
and executing programs.
It will often provide a graphical user interface
(GUI) for the convenience of users.
Common operating systems: Windows, DOS,
UNIX, Linux, MacOS, iOS, Android
ENGG1111A: Computer Programming and Applications

13

Command line interpreter


A program that allows users to interact with the OS, for
example to start or stop programs
In Windows, you can start it by executing "cmd". This runs the
program cmd.exe which is the Command Prompt - the
Windows command line interpreter supplied by Microsoft

ENGG1111A: Computer Programming and Applications

14

Text editor
A word-processor-like program we use to write our own
programs. Examples include emacs, vi, pico, notepad, UltraEdit,
etc.
Some editors provide direct support for programming.

ENGG1111A: Computer Programming and Applications

15

The compiler
A program, such as g++ or vc++, that translates a program
written in a high-level language like C++ into low-level
native code, which can be understood by a computer

High-level languages are closer to English and are much


more human-readable than low-level language.

However, a computer can only understand programs written


in its low-level machine language (instructions). And that
language varies depending on the type of computer.

ENGG1111A: Computer Programming and Applications

16

High level and low-level


language
Here is a very simple C++
program that performs a
calculation and then
terminates without doing
anything with the result.

int main()
{
int height = 4;
int width = 7;
int area = height * width;
return 0;
}

Let's compile this for a Pentium microprocessor and take a look at the relevant
assembly-level instructions generated by the compiler.

Put values 4 and 7


into two memory
locations as 32 bit
values

mov
mov
mov
imul
mov

dword ptr [ebp-4],4


dword ptr [ebp-8],7
eax,dword ptr [ebp-4]
eax,dword ptr [ebp-8]
dword ptr [ebp-0Ch],eax

ENGG1111A: Computer Programming and Applications

Put the result into a


memory location

Multiply the values


in the two locations.
One is a general
purpose register
which will also
receive the result

17

Machine code
The assembly language instructions on the previous slide are still too highlevel to be understood by the computer. They must be converted into
strings of 0 and 1 that the computer can understand. This final form is

machine code.
The machine code for our example is shown on the left:

4-byte
instruction:

C7 45 FC 04 00 00 00 mov
C7 45 F8 07 00 00 00 mov
8B 45 FC
mov
0F AF 45 F8
imul
89 45 F4
mov

dword ptr [ebp-4],4


dword ptr [ebp-8],7
eax,dword ptr [ebp-4]
eax,dword ptr [ebp-8]
dword ptr [ebp-0Ch],eax

00001111
10101111
01000101
11111000

ENGG1111A: Computer Programming and Applications

18

The function of the


compiler
Source program

Application level
High-order
language level
Assembly level
Operating system
level

Object program

Machine
dependent

Instruction set
architecture level
Microcode level

Logic gate level


ENGG1111A: Computer Programming and Applications

19

The executable
If we ask the compiler to create an executable machine code program
from our simple source code, we'll end up with a file which is much larger
than the compiled version of our source code.
size of the
each file

09/03/2014
09/03/2014
09/03/2014

02:45 PM
02:46 PM
02:46 PM

102
460
15,451

area.cpp
area.o
area.exe

If we take a look, we'll see there are a lot of instructions there that we
didn't write ourselves.
How did they get there? They are combined with our code in the final
stage of creating an executable: linking.
ENGG1111A: Computer Programming and Applications

20

Steps for creating and


running a program
Create a program
using a text editor

Source code

Compiler

e.g. area.cpp

Create a program with a Text Editor


This is source code. That is, your program written in a high-level
language like C++
It is saved in a file in secondary memory such as a hard drive like
any other text document
ENGG1111A: Computer Programming and Applications

21

Steps for creating and


running a program
Create a program
using a text editor

Source code
e.g. area.cpp

Compiler
Check the syntax
Generate object
code

Compile the program using a Compiler


The syntax is checked - the syntax of a language specifies the
structure and rules that must be followed when writing in it.
Similar to grammar in English
If there is no syntax error, the compiler translates the program into
low-level language, the object code.
ENGG1111A: Computer Programming and Applications

22

Steps for creating and


running a program
Link in any necessary library code using a Linker
The object code produced by the compiler is often not a solution on
its own. For example, your program may need code for performing
system input/output. You don't need to write such code yourself.
Usually it has been written by experts, compiled and made available
as object code in libraries. So, typically, you only write a portion of
the full program.
The linker combines all the object files into a single object program.
In this course we won't need to deal directly with the linker; linking
will be performed automatically.
The final combined object is called an executable file.

Execute the resulting code


ENGG1111A: Computer Programming and Applications

23

Steps for creating and


running a program
Create a program
using a text editor

Compiler
Source code

Check the syntax

e.g. area.cpp
Generate object
code

Linker

Object code

e.g. area.o

Combine object code with


library components

Executable
e.g. area.exe
Run
ENGG1111A: Computer Programming and Applications

Library 1
Library 2
Library 3
24

IDE
Software that integrates the steps of developing a program (e.g.
editing, compiling, linking, debugging) is called an Integrated

Development Environment (IDE)

Code::Blocks
In this course well use Code::Blocks - a cross-platform IDE for
programming
This software is free and can be easily downloaded using the
links well provide
Our next class introduces Code::Blocks

ENGG1111A: Computer Programming and Applications

25

Computer Programming
and Applications
Programming in C++

A simple C++ program


Here is the traditional first C++ program.
Information for human
readers

Information for the


compiler

Our code

// hello.cpp
// This program displays Hello World!
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
return 0;
}

Let's take a closer look


ENGG1111A: Computer Programming and Applications

27

Comments

Information for
human readers

We always try to make our programs


understandable to anyone who needs
to read them.
An effective way to do this is to provide
comments that describe our
intentions.

// hello.cpp

The // (double slash) indicates that the


line is a comment

#include <iostream>
using namespace std;

A comment line starts with a


double slash and ends at the end of
the line.
The whole line is ignored by the
compiler.
We can also use /* */ to bound
comment text, even across multiple
lines. The complier will ignore
everything in between.
ENGG1111A: Computer Programming and Applications

// This program displays Hello World!

int main()
{
cout << "Hello World!" << endl;
return 0;
}
/* This is a

multiple line comment


*/
28

The include directive

Information for the


compiler

We saw that we don't write everything


ourselves.
Here, for example, we want to use an
output routine that is available in the
C++ input/output library (the library is
called iostream).
The include directive, #include<>,
tells the compiler that the program
requires external library
components and where to look for
information about them.
The linker will combine object code
for the required libraries with the
object code for our own part of the
program.
ENGG1111A: Computer Programming and Applications

// hello.cpp
// This program displays Hello World!
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
return 0;
}

29

The using directive


Namespaces support the approach of
constructing our programs by
combining components, where each
component is developed separately
and possibly not by us.

Information for the


compiler

// hello.cpp
// This program displays Hello World!

You will appreciate namespaces better


when you begin to construct large
programs

#include <iostream>
using namespace std;

For the moment, simply add the line


usingnamespacestd;to your
programs.

int main()
{
cout << "Hello World!" << endl;
return 0;
}

This allows your program to "see" the


names packaged in the standard
library.

ENGG1111A: Computer Programming and Applications

30

The standard library

Information for the


compiler

C++ provides a standard library which


extends the core language with a lot
of useful functionality.
The standard library is large and it is
split into several sections so that we
can include only the parts we need.

iostream, is the part that provides


input and output functionality.
All parts of the standard library
package their function names, etc.
into a namespace called std.

// hello.cpp
// This program displays Hello World!
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
return 0;
}

So any time you include any of the


standard library (that is almost always)
your program will have the line

usingnamespacestd;
ENGG1111A: Computer Programming and Applications

31

The main function

When a program is run, execution


starts at the main function

int main(){...}
Every C++ program must contain
a main function
The braces { and } mark the
beginning and end of the function.

ENGG1111A: Computer Programming and Applications

Our code

// hello.cpp
// This program displays Hello World!
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
return 0;
}

32

Statements

Our code

// hello.cpp
Between the braces, the main function // This program displays Hello World!
contains a sequence of statements
the instructions that the computer will
#include <iostream>
execute one by one.
using namespace std;
Each statement MUST end with a
semi-colon.

ENGG1111A: Computer Programming and Applications

int main()
{
cout << "Hello World!" << endl;
return 0;
}

33

cout and endl from

Our code

iostream
cout is used to construct output
statements which will write output to
the monitor screen.

// hello.cpp
// This program displays Hello World!

cout is defined in iostream and we


can think of it as connected to the
screen

#include <iostream>
using namespace std;

To display something on the screen,


we insert it into cout using the
insertion operator, <<

int main()
{
cout << "Hello World!" << endl;
return 0;
}

endl is also defined in iostream.


We insert it into cout to produce a
newline.

ENGG1111A: Computer Programming and Applications

34

String literals

A string literal is a sequence of


characters enclosed by a pair of

double quotes

Our code

// hello.cpp
// This program displays Hello World!

e.g. "Thisisastring"

#include <iostream>
using namespace std;

You can only do two things with a


string literal display it or assign it to
a string variable.

int main()
{
cout << "Hello World!" << endl;
return 0;
}

ENGG1111A: Computer Programming and Applications

35

The return statement

return0; indicates where execution of


the main function stops. A value of
zero is returned to the OS.
Control is then passed back to the OS.
A non-zero value would indicate failure
of some kind.

ENGG1111A: Computer Programming and Applications

Our code

// hello.cpp
// This program displays Hello World!
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
return 0;
}

36

Reminder: Steps for creating


and running a program
Create a program
using a text editor

Source code

Compiler
Check the syntax

hello.cpp
Generate object
code

Linker

Object code

hello.o

Combine object code with


library components

Executable
hello.exe

iostream

Run
ENGG1111A: Computer Programming and Applications

37

Compiling our code


The options we are using are:

Here we are executing the compiler


from the Windows command prompt.
We are using a specific compiler. It is
the same compiler we use with
Code::Blocks

-c which tells the compiler not to link, and


-o hello.o which tells the compiler to write
the output to a file with this name

We could also use "c++", which is the


system c++ compiler. It may or may not
be g++.

D:\ENGG1111A>g++ -c hello.cpp -o hello.o


D:\ENGG1111A>dir
Volume in drive D has no label.
Volume Serial Number is C69F-619A
Directory of D:\ENGG1111A
09/07/2014
09/07/2014
09/07/2014
09/07/2014

10:20
10:20
10:20
10:20

PM
PM
PM
PM

<DIR>
<DIR>

ENGG1111A: Computer Programming and Applications

.
..
167 hello.cpp
1,406 hello.o

Here we tell the name of


the source file to compile.
It is hello.cpp

This is the object file


produced
38

Creating an executable
Our output file
will be executable
and so we name it
appropriately

If we execute the compiler without the


c option, it will compile and link with
the required libraries

D:\ENGG1111A>g++ -o hello.exe hello.cpp


D:\ENGG1111A>dir
Volume in drive D has no label.
Volume Serial Number is C69F-619A

Huge size of exe file is


a result of linking with
the iostream library

Directory of D:\ENGG1111A
09/07/2014
09/07/2014
09/07/2014
09/07/2014
09/07/2014

10:23 PM
<DIR>
.
10:23 PM
<DIR>
..
10:20 PM
167 hello.cpp
10:23 PM
1,001,851 hello.exe
10:20 PM
1,406 hello.o
3 File(s)
1,003,424 bytes
2 Dir(s) 30,894,530,560 bytes free

Execute our program

D:\ENGG1111A>hello
Hello World!
D:\ENGG1111A>

ENGG1111A: Computer Programming and Applications

It works!!
Displays the string
and a new line

39

In Code::Blocks

Pressing F9 will compile,


link and run your program
ENGG1111A: Computer Programming and Applications

40

In Code::Blocks after F9

This window shows the build


log with the commands
executed by the IDE.
Do you recognize this line?
ENGG1111A: Computer Programming and Applications

41

But what if it doesn't work?


Common programming
errors

Programming errors
Sometimes we make mistakes when programming. These errors
introduce defects, also called bugs, into the program
The process of getting rid of the bugs is called debugging. We
have a lab session on debugging using the IDE later in the course.
There are three main types of programming error:
Syntax errors
Run-time errors
Logic errors

ENGG1111A: Computer Programming and Applications

43

Syntax errors
These are caused by violating the grammar rules of the language.
The compiler will spot syntax errors. It will give you an error
message and terminate. It can't proceed because it doesn't know
what you mean.

Spot the errors in the


program.
Sometimes syntax
errors are not easy to
see, but at least the
compiler tells us about
them.
ENGG1111A: Computer Programming and Applications

/ This program displays Hello World!


#include < iostream>
using namespace std
int
main ()
{
cout < < "Hello World!" < < endl;
return 0;
44

Syntax errors

You will see something like this when the


compiler finds syntax errors

// This program displays Hello World!


#include <iostream>
using namespace std
int
main ()
{
cout < < "Hello World!" < < endl;
return 0;

C:\Program Files (x86)\CodeBlocks\MinGW\bin>g++ bad_hello.cpp


bad_hello.cpp:5:1: error: expected ';' before 'int'
int
main
()
^
bad_hello.cpp: In function 'int main()':
bad_hello.cpp:7:11: error: expected primary-expression before '<' token
cout < < "Hello World!" < < endl;
^
bad_hello.cpp:7:30: error: expected primary-expression before '<' token
cout < < "Hello World!" < < endl;
^
bad_hello.cpp:8:11: error: expected '}' at end of input
return 0;
^
C:\Program Files (x86)\CodeBlocks\MinGW\bin>
ENGG1111A: Computer Programming and Applications

45

Run-time errors
These errors are detected when you run the program, hence at run-time.
Execution will typically stop and the run-time system will output an error
message if it can.
For example, consider a program containing the following fragment where
the 3 marks and the number of assignments submitted (all integers) have
been supplied as inputs:

// calculate truncated average mark per submitted assignment


int total_mark = a1_mark + a2_mark + a3_mark;
int average_per_submission = total_mark / number_submitted;
cout << average_per_submission << endl;

What happens if a student did not submit any assignments?


ENGG1111A: Computer Programming and Applications

46

Run-time errors
What you will see depends on the run-time environment:
$ ./average.exe
How many assignments submitted? 2
Enter marks: 55 0 75
Average per submission: 65
$ ./average.exe
How many assignments submitted? 0
Enter marks: 0 0 0
Floating point exception (core dumped)
$ more average.exe.stackdump
Exception: STATUS_INTEGER_DIVIDE_BY_ZERO at eip=00401244

D:\ENGG1111A>average
How many assignments submitted? 2
Enter marks: 55 0 75
Average per submission: 65
D:\ENGG1111A>average
How many assignments submitted? 0
Enter marks: 0 0 0

ENGG1111A: Computer Programming and Applications

47

Logic errors
Even if a program compiled successfully and there are no run-time errors,
it does not mean that the program is correct.
For example there may be mistakes in the solution you developed or you
may not have implemented that solution correctly in C++.
The effect will be a program that runs, yet produces an incorrect result.
The program contains logic errors.
Logic errors are difficult to detect because we get no help in terms of error
messages from the compiler or at run-time.

To check that our program's logic is


correct we must test it.

ENGG1111A: Computer Programming and Applications

48

Testing for logic errors


We test by running the program on test data and checking to see if it
produces the correct result for those data.
Even if the program gives the correct result for each test case, it still does
not guarantee that there are no logic errors. The program may still fail on
other, untested data.
Take a look at the following fragment, where height and width are integers
input by the user. There is a logic error. We should test by inputting
values for height and width and checking the output.
logic error

int area = height + width;


cout << "Area is " << area << endl;

ENGG1111A: Computer Programming and Applications

BTW, can you think of a test case (i.e. a


value of height and a value of width)
that would not reveal the logic error?

49

You might also like