Specialist Programming C++ CS2001N(IM202)

Download Report

Transcript Specialist Programming C++ CS2001N(IM202)

Specialist Programming C++
CS2001N
Semester 1
2008/9
CS2001N – Specialist Programming C++
Module Lecturer: Dr. Yong Xue
Office: Room T10-02, Tower Building
Surgery hours:
Telephone: Direct Line – (020) 7133 4385
Ext. 4385
Email: [email protected]
Outline of Study Programme
Two principal methods of formal teaching:
• Lectures:
• Tutorials:
• At the end of each week the lecture OHPs will be
published on WebLearn, and can also be viewed via:
• http://learning.londonmet.ac.uk/CCTM/CS2001N/
CS2001N – Specialist Programming C++
Lecture & Practical Sessions
Semester 1, 2008 / 2009
Lecture Sessions
Tuesday: 14:00-16:00 TM1-45
Practical Sessions
Tuesday: 16:00-18:00 T3-05 (Eden Grove)
CS2001N – Specialist Programming C++
Level: Intermediate
Credit Rating: 15
Prerequisites:
A PASS in a programming module –CS1014N
(CS1002N) or its equivalent
CS2001N – Specialist Programming C++
RECOMMENDED TEXTBOOK AND READING LIST
• Essential textbook: C++ How to Program, 5/E
– Harvey M. Deitel, Deitel & Associates, Inc. Paul J. Deitel, Deitel &
Associates, Inc.
– Print ISBN: 0-13-185757-6, Web ISBN (SafariX): 0-13-186103-4
– Publisher: Prentice Hall, Copyright: 2005
• Secondary textbook: Absolute C++, 3/e
– Walter Savitch
– ISBN-10: 0321468937, ISBN-13: 9780321468932
– Publisher: Addison Wesley Higher Education, Copyright: 2008
CS2001N – Specialist Programming C++
ASSESSMENT:
Coursework 70%;
Examination 30%
The final unit mark will be calculated as an
aggregation of all the assessment elements.
CS2001N – Schedule
Week1: Introduction to Computers and C++ Programming (Chapter 1)
Week2: Control structures (Chapter 2)
Week3: Functions (Chapter 3 )
Week4: Arrays (Chapter 4)
Week5: Pointer and Strings (Chapter 5)
Week6: Classes and Data Abstraction (Chapter 6)
Week7: Classes: Part II (Chapter 7 and 8)
Week8: Object-Oriented Programming: Inheritance and Polymorphism
(Chapter 9 and 10)
Week9: Templates and C++ Stream Input/Output(Chapter 11 and 12)
Week10: File Processing (Chapter 14)
Week11: Revision
Lecture Note 1 - Introduction C++ Programming
Introduction
History of C and C++
C++ Standard Library
Structured Programming
The Key Software Trend: Object Technology
Basics of a Typical C++ Environment
General Notes About C++ and This Book
Introduction to C++ Programming
A Simple Program: Printing a Line of Text
Another Simple Program: Adding Two Integers
Arithmetic
Decision Making: Equality and Relational Operators
Introduction
In this course you will learn
– C and C++
– Structured programming and
object oriented programming
History of C and C++

C++ evolved from C
– C evolved from two other programming languages, BCPL and B

C++ “spruces up” C
– Provides capabilities for object-oriented programming
 Objects are reusable software components that model things in
the real world
 Object-oriented programs are easy to understand, correct and
modify
Why C++
• Widely used (UNIX, Industry, Playstation)
• Access to low level registers
• Object orientated
• Preparation for graphics modules!
C++ Standard Library
 C++ programs
– Built from pieces called classes and functions
 C++ standard library
– Provides rich collections of existing classes and
functions for all programmers to use
Structured Programming
 Structured programming
– Disciplined approach to writing programs
– Clear, easy to test and debug, and easy to modify
 Multitasking
– Many activities to run in parallel
The Key Software Trend:
Object Technology

Objects
– Reusable software components that model real world items
– Meaningful software units
 Date objects, time objects, paycheck objects, invoice objects,
audio objects, video objects, file objects, record objects, etc.
 Any noun can be represented as an object
– More understandable, better organized and easier to maintain than
procedural programming
– Favor modularity
Basics of a Typical C++ Environment
Editor
Phases of C++ Programs:
1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. Execute
The C++
preprocessor obeys
commands called
preprocessor
directives, which
indicate that certain
manipulations are to
be performed on the
program before
compilation. These
manipulations
usually include other
text files to be
compiled and
perform various text
replacements.
Preprocessor
Disk
Program is created in
the editor and stored
on disk.
Disk
Preprocessor program
processes the code.
Compiler
Disk
Linker
Disk
Compiler creates
object
code
(machine
language code) and stores
it on disk.
Primary
Memory
Linker links the object
code with the libraries,
creates a.out and
stores it on disk
Loader
Disk
Loader puts program
in memory.
..
..
..
Primary
Memory
CPU
..
..
..
CPU takes each
instruction and
executes it, possibly
storing new data
values as the program
executes.
General Notes About C++
and This Book
 Book is geared toward novice programmers
 Programming clarity is stressed
 C and C++ are portable languages
– Programs written in C and C++ can run
on many different computers
Introduction to C++ Programming

C++ language
– Facilitates a structured and disciplined approach to
computer program design
 Following are several examples
– The examples illustrate many important features of C++
– Each example is analyzed one statement at a time.
A Simple Program: Printing a Line of Text
1
2
3
4
5
6
7
8
9
10
11
12
// Fig. 1.2: fig01_02.cpp
// A first program in C++.
#include <iostream>
Single-line comments.
Preprocessor directive to
include input/output stream
header file <iostream>.
Function main returns an
integer value.
// function main begins
program execution
Function main appears
int main()
exactly once in every C++
{
program..
Statements end with a
semicolon ;.
std::cout << "Welcome to C++!\n";
Stream insertion operator.
return 0; // indicateName
that program
ended successfully
cout belongs to
fig01_02.cpp
(1 of 1)
namespace std.
} // end function main Keyword return is one of
several means to exit
function; value 0 indicates
program terminated
successfully.
Welcome to C++!
fig01_02.cpp
output (1 of 1)
A Simple Program: Printing a Line of Text
 std::cout
– Standard output stream object
– “Connected” to the screen
– std:: specifies the "namespace" which cout belongs to
• std:: can be removed through the use of using statements
 <<
– Stream insertion operator
– Value to the right of the operator (right operand) inserted
into output stream (which is connected to the screen)
– std::cout << “Welcome to C++!\n”;
 \
– Escape character
– Indicates that a “special” character is to be output
A Simple Program: Printing a Line of Text
Escape Sequence
Description
\n
Newline. Position the screen cursor to the
beginning of the next line.
\t
Horizontal tab. Move the screen cursor to the next
tab stop.
\r
Carriage return. Position the screen cursor to the
beginning of the current line; do not advance to the
next line.
\a
Alert. Sound the system bell.
\\
Backslash. Used to print a backslash character.
\"
Double quote. Used to print a double quote
character.
There are multiple ways to print text
– Following are more examples
•
•
•
•
•
•
•
•
•
•
•
•
•
1
2
3
4
5
6
7
8
9
10
11
12
13
// Fig. 1.4: fig01_04.cpp
// Printing a line with multiple statements.
#include <iostream>
// function main begins program execution
int main()
{
std::cout << "Welcome ";
std::cout << "to C++!\n";
Multiple stream insertion
statements produce one line
of output.
Unless new line ‘\n’ is
specified, the text continues
on the same line.
return 0; // indicate that program ended successfully
} // end function main
Welcome to C++!
fig01_04.cpp
(1 of 1)
fig01_04.cpp
output (1 of 1)
•
•
•
•
•
•
•
•
•
•
•
•
1
2
3
4
5
6
7
8
9
10
11
12
Welcome
to
C++!
// Fig. 1.4: fig01_04.cpp
// Printing a line with multiple statements.
#include <iostream>
// function main begins program execution
int main()
{
Multiple lines can be printed
with one statement.
std::cout << "Welcome\nto\n\nC++!\n";
return 0; // indicate that program ended successfully
} // end function main
fig01_05.cpp
(1 of 1)
fig01_05.cpp
output (1 of 1)
Another Simple Program:
Adding Two Integers
 Variables
– Location in memory where a value can be stored for use by a program
– Must be declared with a name and a data type before they can be used
– Some common data types are:
 int - integer numbers
 char - characters
 double - floating point numbers
– Example: int myvariable;
 Declares a variable named myvariable of type int
– Example: int variable1, variable2;

Declares two variables, each of type int
Another Simple Program:
Adding Two Integers
 >> (stream extraction operator)
– When used with std::cin, waits for the user to input a value and
stores the value in the variable to the right of the operator
– The user types a value, then presses the Enter (Return) key to send the data
to the computer
– Example:
int myVariable;
std::cin >> myVariable;
• Waits for user input, then stores input in myVariable
 = (assignment operator)
– Assigns value to a variable
– Binary operator (has two operands)
–
Example: sum = variable1 + variable2;
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Fig. 1.6: fig01_06.cpp
// Addition program.
#include <iostream>
•
24
} // end function main
// function main begins program execution
int main()
Declare integer variables.
{
int integer1; // first number to be input by user
int integer2; // second number to be input by user
int sum;
// variable in which sum will be stored
Use stream extraction
operator with standard input
to obtain user input.
std::cout << "Enter first integer\n"; // prompt stream
std::cin >> integer1;
// read an integer
std::cout << "Enter second integer\n"; // prompt
std::cin >> integer2;
// read an integer
sum = integer1 + integer2; // assign result to sum
std::cout << "Sum is " << sum << std::endl; // print sum
(1 of 1)
return 0; // indicate that program ended successfully
Enter first integer
45
Enter second integer
72
Sum is 117
Stream manipulator
std::endl outputs a
newline, then “flushes output
buffer.”
fig01_06.cpp
Concatenating, chaining or
cascading stream insertion
operations.
fig01_06.cpp
output (1 of 1)
Arithmetic

Arithmetic calculations
– Use * for multiplication and / for division
– Integer division truncates remainder
 7 / 5 evaluates to 1
– Modulus operator returns the remainder
 7 % 5 evaluates to 2
 Operator precedence
– Some arithmetic operators act before others (i.e., multiplication before
addition)

Be sure to use parenthesis when needed
– Example: Find the average of three variables a, b and c
 Do not use: a + b + c / 3

Use: (a + b + c ) / 3
Arithmetic
Arithmetic operators:
+ Addition
- Subtraction
* Multiplication
/ Division
Integer division truncates remainder
7 / 5 evaluates to 1
% Modulus operator returns remainder
7 % 5 evaluates to 2
Arithmetic
Rules of operator precedence
– Operators in parentheses evaluated first
Nested/embedded parentheses
Operators in innermost pair first
– Multiplication, division, modulus applied next
Operators applied from left to right
– Addition, subtraction applied last
Operators applied from left to right
Operator(s)
Operation(s)
Order of evaluation (precedence)
()
Parentheses
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If
there are several pairs of parentheses “on the same level”
(i.e., not nested), they are evaluated left to right.
*, /, or %
Multiplication Division Evaluated second. If there are several, they re
Modulus
evaluated left to right.
+ or -
Addition
Subtraction
Evaluated last. If there are several, they are
evaluated left to right.
Decision Making: Equality and Relational Operators
 if structure
– Test conditions truth or falsity. If condition met execute, otherwise
ignore

Equality and relational operators
– Lower precedence than arithmetic operators
 Table of relational operators on next slide
Decision Making: Equality and Relational Operators
Sta nd a rd a lg eb ra ic
eq ua lity op era tor or
rela tiona l op era tor
C++ eq ua lity
or rela tiona l
op era tor
Exa m p le
of C++
c ond ition
Mea ning of
C++ c ond ition
>
>
x > y
x is greater than y
<
<
x < y
x is less than y

>=
x >= y
x is greater than or equal to y

<=
x <= y
x is less than or equal to y
=
==
x == y
x is equal to y

!=
x != y
x is not equal to y
Relational operators
Equality operators
Decision Making: Equality and Relational Operators
using statements
– Eliminate the need to use the std:: prefix
– Allow us to write cout instead of std::cout
– To use the following functions without the
std:: prefix, write the following at the top of
the program
using std::cout;
using std::cin;
using std::endl;
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
•
25
// Fig. 1.14: fig01_14.cpp
// Using if statements, relational
// operators, and equality operators.
#include <iostream>
using std::cout; // program uses cout
using std::cin; // program uses cin
using std::endl; // program uses endl
// function main begins program execution
int main()
{
int num1; // first number to be read
from
user cout and cin
Can
write
int num2; // second number to bewithout
read from user
std:: prefix.
Notice the using
statements.
using statements eliminate
need for std:: prefix.
cout << "Enter two integers, and I will tell you\n"
if structure compares values
<< "the relationships they satisfy: ";
of num1 and num2 to test for
cin >> num1 >> num2; // read two integers
equality. If it is true, the body
is executed. If not, body is
if ( num1 == num2 )
cout << num1 << " is equal to " << num2
<< endl;
skipped.
if ( num1 != num2 )
cout << num1 << " is not equal to " << num2 << endl;
fig01_14.cpp
(1 of 2)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
if ( num1 < num2 )
cout << num1 << " is less than " << num2 << endl;
if ( num1 > num2 )
cout << num1 << " is greater than " << num2 << endl;
if ( num1 <= num2 )
cout << num1 << " is less than or equal to "
<< num2 << endl;
if ( num1 >= num2 )
cout << num1 << " is greater than or equal to "
<< num2 << endl;
return 0; // indicate that program ended successfully
} // end function main
Enter two integers, and I will tell you
the relationships they satisfy: 22 12
22 is not equal to 12
22 is greater than 12
22 is greater than or equal to 12
Enter two integers, and I will tell you
the relationships they satisfy: 7 7
7 is equal to 7
7 is less than or equal to 7
7 is great than or equal to 7
fig01_14.cpp
output (2 of 2)
Questions – week 1
1.Write a program to input and convert temperature in degrees centigrade
to corresponding temperature in degrees fahrenheit.
0F = 9.0 / 5.0 x 0C + 32
2. Pizza is sold small medium (10” diameter) and large (12” diameter).
Create a program that computes the size (area) of the pizza and its cost
per square inch. (Area = 3.142 x diameter2 / 4.0)
(Costs July 2003, Medium = £4-50, Large = £5-50)
3. A line in 2D space is defined by its end points (x1,y1) and (x2,y2) where
slope = (y1 - y2) / (x1 - x2)
Write a program to input the two points, calculate the slope and test to
avoid infinite gradient condition.