specialist programming c++ cs2001n semester 1 2008/9
Post on 21-Dec-2015
217 views
TRANSCRIPT
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
Phases of C++ Programs:
1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. Execute
Loader
PrimaryMemory
Program is created inthe editor and storedon disk.
Preprocessor programprocesses the code.
Loader puts programin memory.
CPU takes eachinstruction andexecutes it, possiblystoring new datavalues as the programexecutes.
Compiler
Compiler createsobject code (machine language code) and storesit on disk.
Linker links the objectcode with the libraries,creates a.out andstores it on disk
Editor
Preprocessor
Linker
CPU
PrimaryMemory
.
.
.
.
.
.
.
.
.
.
.
.
Disk
Disk
Disk
Disk
Disk
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.
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.
fig01_02.cpp(1 of 1)
fig01_02.cppoutput (1 of 1)
1 // Fig. 1.2: fig01_02.cpp
2 // A first program in C++.
3 #include <iostream>
4 5 // function main begins program execution
6 int main()
7 {8 std::cout << "Welcome to C++!\n";
9 10 return 0; // indicate that program ended successfully
11 12 } // end function main
Welcome to C++!
Single-line comments.
Preprocessor directive to include input/output stream header file <iostream>.
Function main appears exactly once in every C++ program..
Function main returns an integer value.
Statements end with a semicolon ;.
Name cout belongs to namespace std.
Stream insertion operator.
Keyword return is one of several means to exit function; value 0 indicates program terminated successfully.
A Simple Program: Printing a Line of Text
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 TextEscape 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 // Fig. 1.4: fig01_04.cpp
• 2 // Printing a line with multiple statements.
• 3 #include <iostream>
• 4 • 5 // function main begins program execution
• 6 int main()
• 7 {• 8 std::cout << "Welcome ";
• 9 std::cout << "to C++!\n";
• 10 • 11 return 0; // indicate that program ended successfully
• 12 • 13 } // end function main
Welcome to C++!
Multiple stream insertion statements produce one line of output. Unless new line ‘\n’ is specified, the text continues on the same line.
fig01_04.cpp(1 of 1)
fig01_04.cppoutput (1 of 1)
• 1 // Fig. 1.4: fig01_04.cpp
• 2 // Printing a line with multiple statements.
• 3 #include <iostream>
• 4 • 5 // function main begins program execution
• 6 int main()
• 7 {• 8 std::cout << "Welcome\nto\n\nC++!\n";
• 9 • 10 return 0; // indicate that program ended successfully
• 11 • 12 } // end function main
Welcome
to
C++!
Multiple lines can be printed with one statement.
fig01_05.cpp(1 of 1)
fig01_05.cppoutput (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 // Fig. 1.6: fig01_06.cpp
• 2 // Addition program.
• 3 #include <iostream>
• 4 • 5 // function main begins program execution
• 6 int main()
• 7 {• 8 int integer1; // first number to be input by user
• 9 int integer2; // second number to be input by user
• 10 int sum; // variable in which sum will be stored
• 11 • 12 std::cout << "Enter first integer\n"; // prompt
• 13 std::cin >> integer1; // read an integer
• 14 • 15 std::cout << "Enter second integer\n"; // prompt
• 16 std::cin >> integer2; // read an integer
• 17 • 18 sum = integer1 + integer2; // assign result to sum
• 19 • 20 std::cout << "Sum is " << sum << std::endl; // print sum
• 21 • 22 return 0; // indicate that program ended successfully
• 23 • 24 } // end function main
Enter first integer
45
Enter second integer
72
Sum is 117
fig01_06.cpp(1 of 1)
fig01_06.cppoutput (1 of 1)
Declare integer variables.
Use stream extraction operator with standard input stream to obtain user input.
Concatenating, chaining or cascading stream insertion operations.
Stream manipulator std::endl outputs a newline, then “flushes output buffer.”
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
/ DivisionInteger division truncates remainder
7 / 5 evaluates to 1
% Modulus operator returns remainder 7 % 5 evaluates to 2
ArithmeticRules 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 Modulus
Evaluated second. If there are several, they re 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
Standard algebraic equality operator or relational operator
C++ equality or relational operator
Example of C++ condition
Meaning of C++ condition
Relational operators
> > 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
Equality operators
= == x == y x is equal to y
!= x != y x is not equal to y
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 // Fig. 1.14: fig01_14.cpp
• 2 // Using if statements, relational
• 3 // operators, and equality operators.
• 4 #include <iostream>
• 5 • 6 using std::cout; // program uses cout
• 7 using std::cin; // program uses cin
• 8 using std::endl; // program uses endl
• 9 • 10 // function main begins program execution
• 11 int main()
• 12 {• 13 int num1; // first number to be read from user
• 14 int num2; // second number to be read from user
• 15 • 16 cout << "Enter two integers, and I will tell you\n"
• 17 << "the relationships they satisfy: ";
• 18 cin >> num1 >> num2; // read two integers
• 19 • 20 if ( num1 == num2 )
• 21 cout << num1 << " is equal to " << num2 << endl;
• 22 • 23 if ( num1 != num2 )
• 24 cout << num1 << " is not equal to " << num2 << endl;
•25
Notice the using statements.using statements eliminate need for std:: prefix.
Can write cout and cin without std:: prefix.
if structure compares values of num1 and num2 to test for equality. If it is true, the body is executed. If not, body is skipped.
fig01_14.cpp(1 of 2)
• 26 if ( num1 < num2 )
• 27 cout << num1 << " is less than " << num2 << endl;
• 28 • 29 if ( num1 > num2 )
• 30 cout << num1 << " is greater than " << num2 << endl;
• 31 • 32 if ( num1 <= num2 )
• 33 cout << num1 << " is less than or equal to "
• 34 << num2 << endl;
• 35 • 36 if ( num1 >= num2 )
• 37 cout << num1 << " is greater than or equal to "
• 38 << num2 << endl;
• 39 • 40 return 0; // indicate that program ended successfully
• 41 • 42 } // 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 77 is great than or equal to 7
fig01_14.cppoutput (2 of 2)
Questions – week 1
1.Write a program to input and convert temperature in degrees centigradeto 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 costper 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 toavoid infinite gradient condition.