Sunteți pe pagina 1din 50

Chapter 1.

Introduction
2014-2015 1st Semester

ENGG 1111B Computer Programming


and Applications
Department of Computer Science, The University of Hong Kong
Slides prepared by - Dr. Chui Chun Kit (http://www.cs.hku.hk/~ckchui/) for students in ENGG1111
For other uses, please email : ckchui@cs.hku.hk
We are going to learn
Computer? Programming?
What are the basic components in a computer?
How does a computer execute a program?
A sample C++ program
Testing and debugging

Program design

2
Section 1.1

Computer?
Programming?
Understanding how computers work.

Slides prepared by - Dr. Chui Chun Kit (http://www.cs.hku.hk/~ckchui/) for students in ENGG1111
For other uses, please email : ckchui@cs.hku.hk
Basic concepts
Note that computer is not only referring to
your personal computer (PC), it can be
The computer inside your mobile phone.
The computer inside your camera.
The computer in your video game console.

iPhone 5 Galaxy S4
Panasonic Lumix GF

Question: What are the


common components of
these computers?
XBOX 360 and Kinect Play station 3 CANNON EOS 600D

4
Hardware
The actual physical parts that make
up a computer.
1. Central Processing Unit (CPU)
The brain of the computer.
Follows instructions in a program.
Performs simple tasks like A quad-core i7 CPU

Question: Do you know how is the CPU speed measured?


Addition, subtraction,
multiplication and division. Answer : Clock-rate is the fundamental rate
in cycles per second at which a computer
Move data from one performs its most basic operations such as
memory location to another. adding two numbers.
100MHz = 100 Million cycles per second,
1GHz = 1 Billion cycles per second.
5
Hardware
The actual physical parts that make
up a computer.
2. Main memory
Main Memory
A DDR3 RAM
Long list of memory cells. Address 1
Address 2

Each memory cell has an address (a number) Address 3


that gives its position in the memory.
0 0 0 0 0 0 0 1
Each memory cell consists of 8


digits (1 byte). Question: What is the normal RAM size
that can be bought nowadays?
Volatile information will be lost
Answer : There are 8GB DDR3
when the computer is switched off. RAM. Which can store
8,589,934,592 of memory cells!
6
Hardware
The actual physical parts that make
up a computer.
3. Secondary memory
Non-volatile information will not be lost
even after the computer is switched off.
For permanent storage of data in units of files.
An internal Hard Disk

E.g., hard disks, DVD/CD ROMs, thumb drives

Flash hard drive External Hard Disk DVD/CD ROMs USB flash drive
7
Hardware
The actual physical parts that make
up a computer.
4. Input devices
Any device that allows a user to communicate
information with the computer.

5. Output devices
Any device that allows a computer to communicate
information to the user.

8
Hardware
Xbox360 Kinect Ipad 4 iPhone5
Processer CPU Input
device(s) 3.2 GHz PowerPC 1.4 GHz dual-
Processer A6 Dual core
Tri-Core Xenon core Apple A6X

Fast Main memory 512 MB 1024 MB 1GB

Secondary 16, 32, or 64,


Output Up to 320 GB 16, 32 or 64 GB
memory 128 GB
Main memory device(s)
Controller /
Input device(s) Kinect (motion Touch screen, Touch screen,
sensing) etc camera, micetc camera, micetc

Output Video output, 9.7 inches retina 4 inches retina


device(s) Audio output, display, touch display, touch
Slow Controller screen screen

Secondary Question: Besides a Personal Computer, Can you distinguish these


memory components for a smart phone / IPad / video game console?
9
Computer program
What is a computer program?
Processer CPU Input A computer program is a
device(s)
sequence of instructions written
Fast to perform a specified task with a
computer.
Output
Main memory device(s)

Slow

Secondary Compute 2+3=?


memory
10
Computer program
When a Program is being executed
Processer CPU Input The program is loaded into the main
device(s) memory.
Fast

Output
Main memory device(s)
Compute 2+3=?

Slow

Secondary Compute 2+3=?


memory
11
Computer program
When a Program is being executed
Processer CPU Input The program is loaded into the main
Compute 2+3=5 device(s) memory.
Fast
The CPU reads the program instructions
and process the program data.
Output
Main memory device(s)
Compute 2+3=?

Slow

Secondary
memory
12
Computer program
When a Program is being executed
Processer CPU Input The program is loaded into the main
Compute 2+3=5 device(s) memory.
Fast
The CPU reads the program instructions
and process the program data.

Main memory
Output The output of the program can be
device(s)
written to the main memory, secondary
Compute 2+3=?
memory, or displayed through the
output device(s).
Slow

Secondary
memory
13
Computer program
Registers A closer look into CPU
ALU
Control unit (CU) - Extracts instructions from
CU memory and decodes and executes them.
Registers - Store the instructions / data loaded
Fast
from main memory for very fast processing.
0011001001001
0010101011010
Arithmetic logic unit (ALU) - Performs simple
Main memory arithmetic and logical operations, e.g. AND /OR.
Compute 2+3=?
Question: A CPU can only process data and codes represented as
0s and 1s, so how can it execute a program? A program is
NOT written using 0s and 1s!
Slow
Answer: We need a translation tool to help to translate
Secondary a program written by you, to the 0s and 1s machine
memory language that the CPU understand.
14
Programming languages
Machine language
CPU can only understand machine language (machine
code).
Well defined Instructions and data executed directly by
computer's central processing unit (CPU).

?
Machine Human
language language
Write a program that computes
0111000100001111
the addition of two integers.
1001110110110001
1110000100111110

15
Programming languages
Assembly language
A low-level programming language.
Defined by the hardware manufacturer, so every kind of
computer has its own unique assembler language.
Need to translate to machine code for CPU to execute. The
translation program is called an assembler.

Machine Assembly Human


language language language
Write a program that computes
0111000100001111 LOAD A
the addition of two integers.
1001110110110001 ADD B
1110000100111110 STORE C

16
Programming languages
High-level programming languages

Resemble human languages.


Use more complicated instructions than the CPU can follow.
Need to translate to machine code for CPU to execute. The
translation program is called a compiler.

Machine Assembly Programming Human


language language language language
Write a program that computes
0111000100001111 LOAD A // C++ program the addition of two integers.
1001110110110001 ADD B C = A+B;
1110000100111110 STORE C

17
Software
Software that are frequently encountered in
programming
Operating system
Command prompt
Editor
Compiler and linker
IDE

18
Operating system User

Acts as a manager to coordinate and allocate Applications


the resources of a computer. (e.g., reading data
from disk, executing programs)
Operating System
Provides a graphical user interface (GUI) for users
to perform basic tasks easily. (e.g., controlling the
printer, facilitating networking, managing files) Hardware

19
Command Prompt
A command-line interface (CLI) is a mechanism that allows users
to interact with a computer operating system or software by
typing commands to perform specific tasks.

Under Windows, the command prompt can be started by typing


cmd in RUN.

20
Editor
A word-processor like program used for typing in
and editing the source code of a program.

E.g., emacs, vi, pico, Notepad, UltraEdit


Editor

#include <iostream>

int main ( ) {
int width = 5;
int height = 10;
int area = width * height;
cout << Area is << area;
return 0;
}

Source code (area.cpp) 21


Compiler
Computers can only understand programs written
in low-level languages (simple instructions), which
differ from one kind of computers to another.

A Compiler is a program that translates a Editor


high-level language program, such as a C++
program, into a machine-language program
#include <iostream>
that a computer can directly understand and
execute. int main ( ) {
int width = 5;
int height = 10;
int area = width * height;
cout << "Area is " << area;
Object code return 0;
(Machine language ) Compiler }

(E.g. area.o) Source code (area.cpp) 22


Linker
A program can make use of other programs
(libraries) that have been written by others. (e.g.,
programs for handling math calculation, input /
output)
Editor
A Linker is a program that takes one or more
objects generated by a compiler and combines
them into a single executable program. #include <iostream>

int main ( ) {
Linker Executable int width = 5;
int height = 10;
(E.g. area.exe) int area = width * height;
Library
Library cout << "Area is " << area;
Library
Object code return 0;
(Machine language ) Compiler }
(E.g. iostream.o)
(E.g. area.o) Source code (area.cpp) 23
IDE
An Integrated Development Environment (IDE) is
a software that integrates the steps of developing
a program (e.g., editing, compiling, linking,
debugging)
IDE Editor
E.g., Dev-C++ on Window (Freeware)

#include <iostream>

int main ( ) {
Linker Executable int width = 5;
int height = 10;
(E.g. area.exe) int area = width * height;
Library
Library cout << "Area is " << area;
Library
Object code return 0;
(Machine language ) Compiler }
(E.g. iostream.o)
(E.g. area.o) Source code (area.cpp) 24
Section 1.2

A sample
C++ program
What are the basic components in
writing a C++ program?

Slides prepared by - Dr. Chui Chun Kit (http://www.cs.hku.hk/~ckchui/) for students in ENGG1111
For other uses, please email : ckchui@cs.hku.hk
A sample C++ program

// This is a sample C++ program


/*
Written by : Kit
Date : 2014-9-4
*/
#include <iostream>
using namespace std;
int main(){
cout << "Hello World!" << endl;
return 0;
}
hello.cpp

26
A sample C++ program
Comment
// This is a sample C++ program
A double slash indicates a /*
Written by : Kit
comment line. Date : 2014-9-4
*/
Any text after // till the end of #include <iostream>
using namespace std;
the line, or the program int main(){
segment bounded by /* */ cout << "Hello World!" << endl;
will be ignored by the compiler. return 0;
}

Comment lines make a program hello.cpp


more readable.

27
A sample C++ program
Include directive
// This is a sample C++ program
It tells the compiler where to /*
Written by : Kit
find information about certain Date : 2014-9-4
routines used by the program. */
#include <iostream>
iostream is the name of a using namespace std;
int main(){
library that contains the cout << "Hello World!" << endl;
declarations of the routines return 0;
that handle input from the }
keyboard and output to the hello.cpp
screen.

28
A sample C++ program
The main function
// This is a sample C++ program
int main(){} is called the main /*
Written by : Kit
function of the program. Date : 2014-9-4
*/
The braces { and } mark the #include <iostream>
beginning and end of the using namespace std;
int main(){
function.
cout << "Hello World!" << endl;
When a program is put into return 0;
}
execution, it always starts at the
main function. hello.cpp

29
A sample C++ program
The return statement
// This is a sample C++ program
It tells the computer to exit the /*
Written by : Kit
function with a return value. Date : 2014-9-4
*/
#include <iostream>
using namespace std;
int main(){
cout << "Hello World!" << endl;
return 0;
}
hello.cpp

30
A sample C++ program
A Statement
// This is a sample C++ program
A statement is the basic building /*
Written by : Kit
block of a function. Date : 2014-9-4
*/
Each statement ends with a #include <iostream>
semicolon ; using namespace std;
int main(){
Statements in a function are cout << "Hello World!" << endl;
executed sequentially. return 0;
}
hello.cpp

31
A sample C++ program
Console output
// This is a sample C++ program
cout is used to print output to /*
Written by : Kit
the screen. Date : 2014-9-4
<< is the insertion operator. */
#include <iostream>
A sequence of characters using namespace std;
int main(){
enclosed by a pair of double cout << "Hello World!" << endl;
quotes forms a string literal, e.g., return 0;
"Hello World!". }

endl is used to produce a newline. hello.cpp

This statement will print the string Hello World! to the


screen followed by a newline. 32
Section 1.3

Testing and
Debugging
3 types of programming errors

Slides prepared by - Dr. Chui Chun Kit (http://www.cs.hku.hk/~ckchui/) for students in ENGG1111
For other uses, please email : ckchui@cs.hku.hk
Testing and Debugging
A mistake in a program is called a bug, and the
process of eliminating bugs is called debugging.

Three kinds of program errors


Syntax errors
Run-time errors
Logic errors

34
Syntax error
Errors resulting from violation of the syntax (i.e., the
grammar rules) of the programming language.
Can be caught by the compiler during compilation.
// This is a sample C++ program
Let me use the command
prompt to call the compiler /*
(c++) to compile the source code Written by : Kit
hellp.cpp, and output the Date : 2014-9-4
executable as hello.exe */
#include <iostream>
C:\...\> c++ -o hello.exe hello.cpp using namespace std;
int main(){
cout << "Hello World!" << endl
return 0;
}
Command prompt hello.cpp (with syntax error) 35
Syntax error
Errors resulting from violation of the syntax (i.e., the
grammar rules) of the programming language.
Can be caught by the compiler during compilation.
// This is a sample C++ program
Let me use the command
prompt to call the compiler /*
(c++) to compile the source code Written by : Kit
hellp.cpp, and output the Date : 2014-9-4
executable as hello.exe */ Missing ;
#include <iostream>
C:\...\> c++ -o hello.exe hello.cpp using namespace std;
hello.cpp: In function int main(): int main(){
hello.cpp:10: error: expected `;' before return cout << "Hello World!" << endl
C:\...\> return 0;
}
Command prompt hello.cpp (with syntax error) 36
Runtime error
Errors occur during the execution of a program.
Typical source of runtime error
// To return the width of a rectangle
Division by zero /*
Written by : Kit
Date : 2014-9-4
*/
#include <iostream>
using namespace std;
int main ( ) {
int area= 10;
C:\...\> c++ -o width.exe width.cpp int height = 0;
C:\...\> width.exe int width = area / height;
cout << "Width is" << width;
return 0;
}
Command prompt width.cpp (with runtime error) 37
Runtime error
Errors occur during the execution of a program.
Typical source of runtime error
// To return the width of a rectangle
Division by zero /*
Written by : Kit
Segmentation error Date : 2014-9-4 10/0 = undefined!
*/
Stack overflow #include <iostream>
using namespace std;
int main ( ) {
int area= 10;
C:\...\> c++ -o width.exe width.cpp int height = 0;
C:\...\> width.exe int width = area / height;
Floating point exception cout << "Width is" << width;
C:\...\> return 0;
}
Command prompt width.cpp (with runtime error) 38
Logic error
Errors due to incorrect logic flow.
Logic errors are most difficult to debug as they are not
reported by the compiler, but incorrect results may be
produced.
// To return the area of a rectangle
#include <iostream>
using namespace std;
int main ( ) {
int height= 10;
C:\...\> c++ -o area.exe area.cpp int width = 5;
C:\...\> area.exe int area= width + height;
cout << "Area is" << area << endl;
return 0;
}
Command prompt area.cpp (with logic error) 39
Logic error
Errors due to incorrect logic flow.
Logic errors are most difficult to debug as they are not
reported by the compiler, but incorrect results may be
produced.
Area should // To return the area of a rectangle
be 50! #include <iostream>
using namespace std;
int main ( ) {
int height= 10;
C:\...\> c++ -o area.exe area.cpp int width = 5;
C:\...\> area.exe int area= width + height;
Area is 15 cout << "Area is" << area << endl;
C:\...\> return 0;
}
Command prompt area.cpp (with logic error) 40
Section 1.4

Program
design
Design and implementation

Slides prepared by - Dr. Chui Chun Kit (http://www.cs.hku.hk/~ckchui/) for students in ENGG1111
For other uses, please email : ckchui@cs.hku.hk
Program design
Problem solving phase
Understand the problem specification.
Identify the input and output of the program.
Come up with an algorithm that solves the problem.
The solution is not be specific to any programming language.

Implementation phase
Translate the algorithm into a programming language.
Compile the program source code (identify syntax error)
Execute the program on sample input (identify runtime and
logic error)
42
Examples
Problem specification
A construction company provides a service to build a staircase with stone
rods (See the figure below) for its customers. Suppose each stone rod is of
1 feet height, and the cost of a stone rod is $10. You are asked to write a
program to compute the cost of constructing a staircase of height of 5.
Answer: The input is Question:
1) the cost for a stone rod ($10), What is the input/ output
2) the height of the staircase: (5). of the program?

height 1 2 3
cost $10 $30 $60
43
Examples
Problem specification
A construction company provides a service to build a staircase with stone
rods (See the figure below) for its customers. Suppose each stone rod is of
1 feet height, and the cost of a stone rod is $10. You are asked to write a
program to compute the cost of constructing a staircase of height of 5.
Can you come up with an
algorithm to solve the problem?
My idea:
Count the number of
rods : it is 1+2+3+4+5,
and then multiply the
total number of rods by
$10. height 1 2 3
cost $10 $30 $60
44
Examples
Problem specification
A construction company provides a service to build a staircase with stone
rods (See the figure below) for its customers. Suppose each stone rod is of
1 feet height, and the cost of a stone rod is $10. You are asked to write a
program to compute the cost of constructing a staircase of height of 5.

int main(){
int rodprice = 10;
int count, cost;
count = 1 + 2 + 3 + 4 + 5 ;
cost = count * rodprice ;
cout << "Total cost is " << cost;
return 0;
} height 1 2 3
cost $10 $30 $60
45
Examples
Problem specification
A construction company provides a service to build a staircase with stone
rods (See the figure below) for its customers. Suppose each stone rod is of
1 feet height, and the cost of a stone rod is $10. You are asked to write a
program to compute the cost of constructing a staircase of height of n.
I want a generalized program
The input now becomes:
that is able to calculate the
1) the cost for a stone rod ($10),
cost of ANY arbitrary height!
2) the height of the staircase: (n).
Easy! I just repeat the steps in
the previous program for n
times!

height 1 2 3
cost $10 $30 $60
46
Examples
Problem specification
A construction company provides a service to build a staircase with stone
rods (See the figure below) for its customers. Suppose each stone rod is of
1 feet height, and the cost of a stone rod is $10. You are asked to write a
program to compute the cost of constructing a staircase of height of n.
Any other methods to solve
int main(){ this problem?
int n = 5;
int rodprice = 10 , count = 0;
int cost;
for (int i = 1 ; i<= n; i++){
count = count + i;
}
cost = count * rodprice;
cout << "Total cost is " << cost; height 1 2 3
return 0;
cost $10 $30 $60
}
47
Examples
Problem specification
A construction company provides a service to build a staircase with stone
rods (See the figure below) for its customers. Suppose each stone rod is of
1 feet height, and the cost of a stone rod is $10. You are asked to write a
program to compute the cost of constructing a staircase of height of n.
Well done!

int main(){
int height = 5;
int rodprice = 10;
int cost =(height *(height + 1)
/2)*rodprice;
cout << "Total cost is " << cost;
return 0;
height 1 2 3
}
cost $10 $30 $60
48
Summary
A computer mainly consists of a processor, main
memory, secondary memory, input device(s) and output
device(s).
High-level programming language like C++ has to
compile to low-level machine code (object files) for the
computer to execute.

A good algorithm design is the first step to an efficient


program.

49
Chapter 1.

END
2014-2015 1st Semester

ENGG 1111B Computer Programming


and Applications

Slides prepared by - Dr. Chui Chun Kit (http://www.cs.hku.hk/~ckchui/) for students in ENGG1111
For other uses, please email : ckchui@cs.hku.hk

S-ar putea să vă placă și