eng2002 computer programming - lnx01 @ dell …lnx01.ee.polyu.edu.hk/~eewlchan/eng2002/ch1-2.pdf ·...
TRANSCRIPT
ENG2002 Computer Programming
Subject Lecturer: Dr. W.L. Chan
THE HONG KONG
POLYTECHNIC UNIVERSITY
Room: CF609E-Mail: [email protected]: 27666145lnx01.ee.polyu.edu.hk/~eewlchan/ENG2002
Subject coordinator: Dr Frank Leung (EIE)Email: [email protected]: CD633 Tel: 2766 6224
1
References:
1. S. Rao, Sams Teach Yourself C++ in One Hour a Day. Indianapolis, Ind.: Sams, 2012.
2. P.J. Deitel and H.M. Deitel, C++ How To Program(9th ed.) Boston, Mass.: Prentice Hall, 2014.
3. J Liberty and R. Cadenhead, Sams Teach Yourself C++ in 24 hours (5th ed.) Indianapolis, Ind.: Sams, 2011.
Computer Programming
THE HONG KONG
POLYTECHNIC UNIVERSITY
2
Teaching Plan:
1. Introduction to Programming (week 1)2. A Taste of C++ (week 1)3. Bolts and Nuts of C/C++ (week 2-4)4. Program Design and Debugging (week 5)5. Basic Object Oriented Programming (week 6-7) 6. Pointer and Array (week 8-11)7. Stream I/O (week 12)
THE HONG KONG
POLYTECHNIC UNIVERSITY
3
Computer Programming
THE HONG KONG
POLYTECHNIC UNIVERSITY
Student Learning Outcomes:
� Familiarize themselves with at least one C/C++ programming environment.
� Be proficient in using the basic constructs of C/C++, to develop a computer program.
� Be able to develop a structured and documented computer program.
� Understand the fundamentals of object-oriented programming and be able to apply it in computer program development.
� Be able to apply the computer programming techniques to solve practical engineering problems.
4
Computer Programming
THE HONG KONG
POLYTECHNIC UNIVERSITY
5
Assessment Plan:
� One application development - 20% (a group of 2 students)
� Two programming tests - 30% (open book)
� Others - 20% (quizzes & assignments)� Exam - 30% (closed book )
THE HONG KONG
POLYTECHNIC UNIVERSITY
6
Computer Programming
0 - 34 F
35-40 D
41-46 D+
47-53 C
54-60 C+_______________________61-70 B71-80 B+_______________________81-90 A91-100 A+
Computer Programming
THE HONG KONG
POLYTECHNIC UNIVERSITY
7
Marks to grade mapping:
Schedule for the programming tests
� First programming test – week 8
� Second programming test – week 13
Computer Programming
THE HONG KONG
POLYTECHNIC UNIVERSITY
8
Lectures� Monday, 9:30 – 11:20
� Thursday, 15:30 – 17:20
Tutorials and practices� Monday, 8:30 – 9:25
� Thursday, 17:30 –18:25
Computer Programming
THE HONG KONG
POLYTECHNIC UNIVERSITY
9
Programming� Programming is very different from other
engineering subjects !� Just like learning a foreign language – you
need to speak more often, read more often� To learn programming well, you must write
your own program !!!� Think logically, plan and design properly before
you start writing your program !!!
10
Computer Programming
THE HONG KONG
POLYTECHNIC UNIVERSITY
11
Computer Programming:
A systematic approach to instruct a computer doing something for us.
Computer Programming1. Introduction to Programming
Hardware
CPU
Memory
I/O devices
12
Process of Computer Programming
Computing Problems
Algorithmsand Data
Structures
High-levelLanguage
Hardware
Operating System
Application Software
Coding
Binding(Compile, link and load)
Mapping
Computer Programming1. Introduction to Programming
Details in the following slides
Way of thinkingComputer
13
Computing Problems
Algorithmsand Data
Structures
High-levelLanguage
Hardware
Operating System
Application Software
Coding
Binding(Compile, link and load)
Mapping
Computer Programming1. Introduction to Programming
14
Identify the Problem• Before writing a program, ask yourselves two questions:
1. What is the problem I want to solve?
2. Do I really needto write a program to solve it?
• A problem can often be so large that requires the co-operation of a few programs to solve it
• E.g. To design a computer game
- Design the story
- Design the graphics
- Design the motion
:
Computer Programming1. Introduction to Programming
15
• Do we need to write a program for the following problems?• Calculate the result of 1 + 1?
• Play a piece of MP3 music using the computer?
• Develop a Web page?
No. Just use your fingers!
No. Use application software such as Media Player.
Yes or no, depending on how complicate your Web page is.
• Usually we need to write a program if the problem is too complicatedand specificto our needs.
Computer Programming1. Introduction to Programming
Local computer Vs networked computers
16
Computing Problems
Algorithmsand Data
Structures
High-levelLanguage
Hardware
Operating System
Application Software
Coding
Binding(Compile, link and load)
Mapping
Computer Programming1. Introduction to Programming
17
Find the Best Algorithm• A problem can be solved by different approaches
• Using a clever approach can save you a lot of time in getting the result
• E.g.Calculate 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +
10 + 11 + 12• Solution?
Computer Programming1. Introduction to Programming
11 additions
Use algorithm A: 12 x (1 + 12) / 2 = 781 addition, 1 multiplication, 1 division
Seems better, BUT ...
18
• Consider the following situation:• For a particular computer, it may take 1 µs to
compute an addition but uses 10 µs to do a multiplication or division.
Calculate 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12
• Do you still want to use algorithm A?
Direct addition: 11 µsec Direct addition: 11 µsec Use algorithm A: 21 µsec Use algorithm A: 21 µsec
� Algorithm needs to match with the hardware architecture� Algorithm needs to match with the hardware architecture
Computer Programming1. Introduction to Programming
19
Computing Problems
Algorithmsand Data
Structures
High-levelLanguage
Hardware
Operating System
Application Software
Coding
Binding(Compile, link and load)
Mapping
Computer Programming1. Introduction to Programming
20
Coding• Computer can only understand 0 and 1
• The most direct way to communicate with the computer is to use 0 and 1
⇒ Machine Language Programming
0110001111000010
0001000111100011
:
:
0011000100001000
1000001001010101
MachineLanguageProgram
Very tedious and can make error easilyVery tedious and can make error easily
1. Introduction to Programming
Computer Programming
21
Coding - Assembly Language• Assembly Languageis created to help human instructing
CPU to work
• By using a software tool called Assembler, assembly language programs can be converted into machine language programs.
Assembler
01100011110000100001000111100011
::
00110001000010001000001001010101
LD R0, #05ADD R0, $1234
::
SUB R0, #22LD $2345, R0
Assembly Language Machine Language
1. Introduction to Programming
Computer Programming
22
Coding - High Level Language
• Assembly language programmingis still too complicatedfor general users
• They are far from human used language
e.g. “Set W equal to W plus X minus Y divided by Z”
“Repeat the next sequence of instructions until X is less than 0 or Y equals Z”
• A high level languageis required to reduce the gapbetween human and computers.
1. Introduction to Programming
Computer Programming
23
Give me the result of adding 1 to 10
Compiler
Linker10110101010101010101
:
High Level Program
ExecutableMachine Language Program
Object codeLibrary
1. Introduction to Programming
.exe
.cpp
Details in the following slides
Start
Finish
Computer Programming
24
• Compiler: Generate the object code
• Object code � Similar to the machine language code but cannot be executed because of the missing of some information.
• Linker : Resolve the missing information from the library or other programs.
For a program, it is very common that some of the information in the program needs to be obtained from the Library provided by the programming tool. It is the job of linker to obtain these missing information.
For a program, it is very common that some of the information in the program needs to be obtained from the Library provided by the programming tool. It is the job of linker to obtain these missing information.
1. Introduction to Programming
Computer Programming
25
Coding - High Level Languages• From time to time, high level languages (HLL)are designed
for different purposes
• Earlier examples:BASIC : for simple and general computing (obsolete for long) COBOL : for data processing (still using in local banks)FORTRAN : for scientific computation (ever replaced by C or C++)
• Recent examples:Pascal: a sophisticated but complicated HLL (replaced by C or C++)
C : a simple structural HLL for general computing (still in use)
• Current examples:C++ : the most well-knownobject-oriented (OO)language
Java : an OO language designed with the concept of networking.
1. Introduction to Programming
Computer Programming
� FORTRAN – FORmula TRANslator– 1954-1957: IBM– Complex mathematical computations
� Scientific and engineering applications
� COBOL– COmmon Business Oriented Language – 1959: computer manufacturers, government and
industrial computer users– Precise and efficient manipulation of large amounts
of data� Commercial applications
1. Introduction to Programming
Computer Programming
28
What is C?� C is a general purpose, procedural, imperative
language developed in 1972 by Dennis Ritchie at Bell Labs for the Unix Operating System.– Low-level access to memory– Language constructs close to machine instructions– Used as a “machine-independent assembler”
1. Introduction to Programming
Computer Programming
29
My First C Program
#include <stdio.h>/* My first C++ program! */int main(){
printf("hello, world\n");return 0;
} char array/string
Indicate correct termination
Write to standard output
A preprocessor directive
Include standard io declarations
1. Introduction to Programming
Computer Programming
30
29
Programming Language C++• Object-Oriented programming concept is overwhelming
• OO Programming has the advantage of achieving reuse of software components
• The C++ programming language is created to implement the concept of OO programming
• C++ is an extension to the widely popular C language
• It has become the predominant language for the development of commercial software
• Standardized by the American National Standards Institute (ANSI), C++ program is portable to different machines.
1. Introduction to Programming
Computer Programming
“Hello World” in C++
using namespace std;#include <iostream>// My first C++ program!int main(){
cout << "hello world!" << endl;return 0;
}
Use the standard namespace Include standard iostream classes
A C++ comment
cout is an instance of ostream
operator overloading(two different argument types!)
1. Introduction to Programming
Computer Programming
32
Java
� Eliminated unsafe features of C++� Concurrency features� Libraries for applets, GUIs, database access� Portable: Java Virtual Machine concept, JIT
compilers� Widely used for WWW pages� Use for other areas increased faster than any
other language (Android Apps)
1. Introduction to Programming
Computer Programming
33
Hello World in Java
// My first Java program!public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello world!");}
}
1. Introduction to Programming
Computer Programming
34
Scripting Languages for the Web
� JavaScript– A joint venture of Netscape and Sun Microsystems– Used in Web programming (client side) to create dynamic
HTML documents– Related to Java only through similar syntax
� PHP– PHP: Hypertext Preprocessor– Used for Web applications (server side); produces HTML code
as output
� Python– An OO interpreted scripting language– Type checked but dynamically typed– Supports form processing
1. Introduction to Programming
Computer Programming
35
Hello World in JavaScript
<html><body>
<script>// My first JavaScript program!// helloWorld.html
alert("Hello World");</script>
</body></html>
1. Introduction to Programming
Computer Programming
36
Machine binary language Low-level assembly High-leve l
1. Introduction to Programming
Computer Programming
38
Coding - High Level Languages
36
Programming Environment
• Before doing any C++ programming, first we need to familiarize with the programming environment.
• A programming environment is a software packagethat can help us developand testprogram code.
• For PC, one of the most popular programming environment is Microsoft Visual Studio.
• It is more popular because of its direct support to the Microsoft Windows environment.
Computer Programming2. A Taste of C++
• Visual C++is one of the components of the product –Visual Studio, which also contains development tools for other programming languages, e.g. Visual Basic, Visual C#, etc.
• The version we use is Visual Studio Community 2015. The compiler that is incorporated is Visual C++ 2015.
• Additional features include
• Produce C++/CLI codesthat run in the Common Language Runtime (CLR)
• Allow the use of .NET Framework class libraries.
Visual Studio Community 2015
NOT
covered in
ENG2002
2. A Taste of C++
Computer Programming
40
38
Solution and Project• In Visual Studio, each user task is referred to as a
solution to a problem.
• A solution refers to the computer resource(such as memory, disk space, etc.) required for one or more projects to complete the task.
• Every project contains • executable codeand debuginformation• files containing the C++ programs• classesand objectsused in the project• other related resources such as
• icon images used in the project• graphical user interface (GUI), e.g. button, menu.
They are all in files
Computer Programming2. A Taste of C++
39
Solution
Project 1
Project 2 Project 3
Files
• A Solutionmust contain at leastone Project
• A Projectmust contain at leastone File
Computer Programming2. A Taste of C++
Source ProgramEditing
Display compilation results
Display resources
of the solution, such as, projects and files inside
2. A Taste of C++
Computer Programming
40
Project Example
• Solution Explorerallows us to clearly see the different files includedin the project
Computer Programming
41
2. A Taste of C++
42
Project Example
Program can be typed here
2. A Taste of C++
Built result (result of compiling and linking)
shown here
Computer Programming
43
Build your first project -HelloWorld• Building a project means to produce target
executable files (.exe files)based on the program codes.
• Project can be built to execute in consoleorwindows mode• Console mode:Use the Command Prompt for
input/output• Windows mode:Use the Windows environment
for program execution.
Computer Programming2. A Taste of C++
44
Command Prompt• It is a traditional interface between the user
and computer• User types in commands to instruct computer
to work.
Computer Programming2. A Taste of C++
45
Build your first project - HelloWorld
#include <iostream>
int main(){
std::cout << "Hello World!" << std::endl;return 0;
}
• Hello.cpp : File containing a C++ program that prints a message “Hello World!” on the console output.
The returned typeof main() MUST be declaredin Visual Studio 2015
Computer Programming2. A Taste of C++
� Inserts the contents of another file (Library) into the program
� Is a preprocessor directive– Not part of the C++ language– Not seen by compiler
� Example: for the cout object #include <iostream>
The #include Directive
46
Computer Programming2. A Taste of C++
The cout Object� Displays information on computer screen� Use << to send information to cout
std::cout << "Hello World!";
� Can use << to send multiple items to cout std::cout << "Hello " << “World!";
Or std::cout << "Hello ";std::cout << “World!";
47
Computer Programming2. A Taste of C++
Starting a New Line
To get multiple lines of output on screen - Use endl
std::cout << "Hello World!" << std::endl;
- Use \n in an output stringstd::cout << "Hello World!\n";
2-4848
Computer Programming2. A Taste of C++
Step 1:
Start Microsoft Visual Studio 2015
Click New Project...
First time starting may take minutes, be patient.
2. A Taste of C++
Computer Programming
52
50
2. A Taste of C++
Step 2 You can modify the location of the files of your project.
Note where you create this project
Computer Programming
Step 3
Computer Programming
51
2. A Taste of C++
52
2. A Taste of C++
Step 4:
Right-clickSource Files ,select Add→ New Item...
Computer Programming
53
2. A Taste of C++
Step 5:Choose C++ File (.cpp) .
Give a name to the C++ file you are going to add
Computer Programming
a
Source ProgramEditing
Display compilation results
Solution Explorer
Display resources of the solution, such as, projects and files inside
2. A Taste of C++
Computer Programming
54
55
Step 6:
Type the program on p.37 in here
Click Build→ Build Solution
See the built result
Computer Programming2. A Taste of C++
Do you see the following result?
Note: The result is shown in the Command Prompt (cmd.exe) – Console Application
Step 7:
Execute the program by clicking Debug → Start Without Debugging
Computer Programming
56
2. A Taste of C++
57
What has actually done?• In this HelloWorld
example, one solution is created that contains aproject called chap2p1 .
• Inside the project, there is one C++ program called Hello.cpp .
Solution
Project: chap2p1
C++ sourceFile: Hello.cpp
Computer Programming2. A Taste of C++
58
• The C++ Compiler of Visual Studio compilesthe program Hello.cpp and generates an executable file chap2p1.exe.
• When you click Debug → Start Without Debugging , Visual Studio actually runs the executable file chap2p1.exe for you.
• All files generated in this project is stored in
E:\VS_Proj\chap2p1
Run Windows Explorer
Computer Programming2. A Taste of C++
59
2. A Taste of C++
Contains all files created after building the solution
Contains info. about the project. Double-click this will automatically start the project
The C++ file you created
Computer ProgrammingWindows Explorer
60
2. A Taste of C++
The EXE(executable) file created
Computer Programming
Program Input Using the cin Object� cin Object: allows data entry to a running
program� Use of the cin object causes the program to
wait for input from the keyboard� When keyboard entry is complete, the program
resumes execution, using the entered data� An output statement preceding the cin object
statement provides a prompt to the user
61
Computer Programming2. A Taste of C++
cin.get();
62
2. A Taste of C++ We can always run the program under the command prompt
We can always run the program under the command prompt
Computer Programming
63
Exercise 2.1Consider the two programs on the RHS. For each of the program, construct a new project in Visual Studio and then build the solution.
For each program, note the error messages when building the project. Fix the errors and execute the resulting project. What do you see?
#include <iostream>int main()
cout << "Hi World!" << std::endl;
return 0;}
#include <iostream>int test(){
std::cout << "How are you!"<< std::endl;
return 0;}
Computer Programming2. A Taste of C++
64
Exercise 2.21. Open the Command Prompt .2. By using the command cd , change the current folder to the
folder that contains chap2p1.exe (you may want to use the command dir to show the content of a folder.)
3. Run chap2p1.exe by typing its file name and press Enter .
4. Compare the result with that you run the program in Visual Studio. Can you see any difference coming up?
5. If no, add the following lines of code before “return 0 ;” of Hello.cpp .
std::cout<<"Press Enter to continue."<<std::endl;
std::cin.get();
Rebuild the solution. Repeat 1 to 4 and note any difference.
Observe the output and explain.
Computer Programming2. A Taste of C++