+ All Categories
Home > Documents > CPA1415 01 Introduction

CPA1415 01 Introduction

Date post: 06-Dec-2015
Category:
Upload: yip90
View: 215 times
Download: 0 times
Share this document with a friend
Description:
CPA1415 01 Introduction
Popular Tags:
49
Computer Programming and Applications Topic 1 Introduction to Programming and C++
Transcript
Page 1: CPA1415 01 Introduction

Computer Programming and Applications

Topic 1

Introduction to Programming and C++

Page 2: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Basics

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.

Program

The actual physical parts that make up a computer. For example, central processing unit (CPU), main memory, secondary memory, and input/output devices.

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.

Software

Hardware

2

Page 3: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Hardware

Input devices

Outputdevices

Secondary memory

CPU

Main memory

3

Page 4: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Input/output components

An input device is any device that allows information to be communicated to the computer.

Keyboard and mouse are both input devices.

An output device allows the computer to communicate information to the user.

A monitor is the most common output device.

Input devices

Outputdevices

Secondary memory

CPU

Main memory

4

Page 5: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Internal hardware components

Input devices

Outputdevices

Secondary memory

CPU

Main memory

5

Page 6: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Hardware components: Memory

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.

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.

6

Page 7: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Hardware components: Main memory 00000000

byte 1000 00110101byte 1001 10001110byte 1002 01111101byte 1003 00000111byte 1004 01101010byte 1005 01000011byte 1006 00001101byte 1007 11100111byte 1008 11000001byte 1009 01100110byte 1010 00000000byte 1011 00000000

4 byte location

4 byte location

2 byte location

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

Information is represented as strings of 0s and 1s 7

Page 8: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Main memory: addresses

4 byte location with address 1000

4 byte location with address 1006

2 byte location with address 1004

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]

8

00000000byte 1000 00110101byte 1001 10001110byte 1002 01111101byte 1003 00000111byte 1004 01101010byte 1005 01000011byte 1006 00001101byte 1007 11100111byte 1008 11000001byte 1009 01100110byte 1010 00000000byte 1011 00000000

Page 9: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

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;⋯

9

Page 10: CPA1415 01 Introduction

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.

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.

10

Abstraction is a key element of computational thinking

Page 11: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Typical levels of abstraction

Logic gate level

Application level

High-order language level

Assembly level

Operating system level

Instruction set architecture level

Microcode level

Increasingly “machine-oriented”

Increasingly “human-oriented”

In 1111A we work at this level

Each level has its own language

11

Page 12: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Software

We use and work with many types of software in programming. These include:

Operating systems Command line interpreters Editors CompilersDevelopment environments Debuggers

12

Page 13: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Operating system (OS)

13

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

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

Page 14: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Command line interpreterA 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

14

Page 15: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Text editorA 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.

15

Page 16: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

The compiler

A program, such as g++ or vc++, that translates a program written in a high-level language like C++ into low-levelnative 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.

16

Page 17: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

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.

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

Put values 4 and 7 into two memory locations as 32 bit values

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

Put the result into a memory location 17

Page 18: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Machine codeThe assembly language instructions on the previous slide are still too high-level 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:

C7 45 FC 04 00 00 00 mov dword ptr [ebp-4],4C7 45 F8 07 00 00 00 mov dword ptr [ebp-8],78B 45 FC mov eax,dword ptr [ebp-4]0F AF 45 F8 imul eax,dword ptr [ebp-8]89 45 F4 mov dword ptr [ebp-0Ch],eax

4-byte instruction:

00001111101011110100010111111000

18

Page 19: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

The function of the compiler Application level

High-order language level

Assembly level

Operating system level

Instruction set architecture level

Microcode level

Logic gate level

Source program

Object program

19

Machine dependent

Page 20: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

The executable

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.

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.

09/03/2014 02:45 PM 102 area.cpp09/03/2014 02:46 PM 460 area.o09/03/2014 02:46 PM 15,451 area.exe

20

size of the each file

Page 21: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Compiler

Steps for creating and running a program

Create a program using a text editor

Source code

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

21

Page 22: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Compiler

Steps for creating and running a program

Create a program using a text editor

Source code

e.g. area.cppCheck 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.

22

Page 23: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

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

Steps for creating and running a program

23

Page 24: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Compiler

Create a program using a text editor

Source code

e.g. area.cpp

Check the syntax

Generate object code

Combine object code with library components

Linker Object code e.g. area.o

Executablee.g. area.exe

Run

Steps for creating and running a program

24

Library 3

Library 2

Library 1

Page 25: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

IDE

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

25

Code::Blocks

In this course we’ll use Code::Blocks - a cross-platform IDE for programming

This software is free and can be easily downloaded using the links we’ll provideOur next class introduces Code::Blocks

Page 26: CPA1415 01 Introduction

Computer Programming and Applications

Programming in C++

Page 27: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

A simple C++ program

Here is the traditional first C++ program.

27

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

#include <iostream> using namespace std;

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

}

Information for human readers

Information for the compiler

Our code

Let's take a closer look

Page 28: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Comments

28

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

#include <iostream> using namespace std;

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

}

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.

The // (double slash) indicates that the line is a comment

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.

/* This is a multiple line comment

*/

Page 29: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

The include directive

29

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

#include <iostream> using namespace std;

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

}

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.

Page 30: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

The using directive

30

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

#include <iostream> using namespace std;

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

}

Information for the compiler

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

You will appreciate namespaces better when you begin to construct large programs

For the moment, simply add the line using namespace std;  to your programs.

This allows your program to "see" the names packaged in the standard library.

Page 31: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

The standard library

31

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

#include <iostream> using namespace std;

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

}

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.

So any time you include any of the standard library (that is almost always) your program will have the lineusing namespace std; 

Page 32: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

The main function

32

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

#include <iostream> using namespace std;

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

}

Our code

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.

Page 33: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Statements

33

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

#include <iostream> using namespace std;

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

}

Our code

Between the braces, the main function contains a sequence of statements –the instructions that the computer will execute one by one.

Each statement MUST end with a semi-colon.

Page 34: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

cout and endl from iostream

34

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

#include <iostream> using namespace std;

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

}

Our code

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

cout is defined in iostream and we can think of it as connected to the screen

To display something on the screen, we insert it into cout using the insertion operator, <<

endl is also defined in iostream. We insert it into cout to produce a newline.

Page 35: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

String literals

35

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

#include <iostream> using namespace std;

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

}

Our code

A string literal is a sequence of characters enclosed by a pair of double quotese.g. "This is a string"

You can only do two things with a string literal – display it or assign it to a string variable.

Page 36: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

The return statement

36

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

#include <iostream> using namespace std;

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

}

Our code

return 0; 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.

Page 37: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Compiler

Create a program using a text editor

Source code

hello.cpp

Check the syntax

Generate object code

Combine object code with library components

Linker Object code hello.o

Executablehello.exe

Run

Reminder: Steps for creating and running a program

37

iostream

Page 38: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Compiling our code

38

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

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

Directory of D:\ENGG1111A

09/07/2014 10:20 PM <DIR> .09/07/2014 10:20 PM <DIR> ..09/07/2014 10:20 PM 167 hello.cpp09/07/2014 10:20 PM 1,406 hello.o

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

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

Directory of D:\ENGG1111A

09/07/2014 10:20 PM <DIR> .09/07/2014 10:20 PM <DIR> ..09/07/2014 10:20 PM 167 hello.cpp09/07/2014 10:20 PM 1,406 hello.o

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

We could also use "c++", which is the system c++ compiler. It may or may not be g++.

The options we are using are:

-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

Here we tell the name of the source file to compile. It is hello.cpp

This is the object fileproduced

Page 39: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Creating an executable

39

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

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

Directory of D:\ENGG1111A

09/07/2014 10:23 PM <DIR> .09/07/2014 10:23 PM <DIR> ..09/07/2014 10:20 PM 167 hello.cpp09/07/2014 10:23 PM 1,001,851 hello.exe09/07/2014 10:20 PM 1,406 hello.o

3 File(s) 1,003,424 bytes2 Dir(s) 30,894,530,560 bytes free

D:\ENGG1111A>helloHello World!

D:\ENGG1111A>

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

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

Directory of D:\ENGG1111A

09/07/2014 10:23 PM <DIR> .09/07/2014 10:23 PM <DIR> ..09/07/2014 10:20 PM 167 hello.cpp09/07/2014 10:23 PM 1,001,851 hello.exe09/07/2014 10:20 PM 1,406 hello.o

3 File(s) 1,003,424 bytes2 Dir(s) 30,894,530,560 bytes free

D:\ENGG1111A>helloHello World!

D:\ENGG1111A>

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

Huge size of exe file is a result of linking with the iostream library

Execute our program

If we execute the compiler without the –c option, it will compile and link with the required libraries

It works!!Displays the string and a new line

Page 40: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

In Code::Blocks

40

Pressing F9 will compile, link and run your program

Page 41: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

In Code::Blocks after F9

41

This window shows the build log with the commands executed by the IDE.

Do you recognize this line?

Page 42: CPA1415 01 Introduction

But what if it doesn't work?

Common programming errors

Page 43: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

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 errorsRun-time errorsLogic errors

43

Page 44: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

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.

/ This program displays Hello World!#include < iostream> using namespace std

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

Spot the errors in the program.

Sometimes syntax errors are not easy to see, but at least the compiler tells us about them.

44

Page 45: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Syntax errors

You will see something like this when the compiler finds syntax errors

45

C:\Program Files (x86)\CodeBlocks\MinGW\bin>g++ bad_hello.cppbad_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 '<' tokencout < < "Hello World!" < < endl;

^bad_hello.cpp:8:11: error: expected '}' at end of input

return 0;^

C:\Program Files (x86)\CodeBlocks\MinGW\bin>

// This program displays Hello World!#include <iostream> using namespace std

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

Page 46: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Run-time errorsThese 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 assignmentint 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?

46

Page 47: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

Run-time errors

47

$ ./average.exeHow many assignments submitted? 2Enter marks: 55 0 75Average per submission: 65

$ ./average.exeHow many assignments submitted? 0Enter marks: 0 0 0Floating point exception (core dumped)

What you will see depends on the run-time environment:

$ more average.exe.stackdumpException: STATUS_INTEGER_DIVIDE_BY_ZERO at eip=00401244…

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

D:\ENGG1111A>averageHow many assignments submitted? 0Enter marks: 0 0 0

Page 48: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

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.

48

To check that our program's logic is correct we must test it.

Page 49: CPA1415 01 Introduction

ENGG1111A: Computer Programming and Applications

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.

…int area = height + width;cout << "Area is " << area << endl;…

49

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?

logic error


Recommended