Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
CHAPTER 2
Introduction to the C++ Language
MNAZ / Department of Computer Science, KICT / Sem 1 2008/2009
Objectives
2.1 Background 2.2 C++ Programs 2.3 Identifiers 2.4 Data Types 2.5 Variables 2.6 Constant 2.7 Coding Constant 2.8 Reading and Writing Data 2.9 Programming Examples
7/14/2008 2
2.1
Background
7/14/2008
7/14/2008
Figure 2-1
2.2
C++ Programs
7/14/2008
7/14/2008
Figure 2-2
Figure 2-3
7/14/2008
7/14/2008
Figure 2-4
Examples of comments
Figure 2-5
7/14/2008
7/14/2008
10
2.3
2.4
Identifiers
The first character must be alphabetic character or underscore Must consists only alphabetical characters, digits or underscore The identifier cannot duplicate a reserved words.
Data Types
7/14/2008
11
7/14/2008
12
Figure 2-6
Figure 2-7
Integer types
7/14/2008
13
7/14/2008
14
Figure 2-8
Floating-point types
Note:
A character in C++ can be interpreted as a small integer (between 0 and 255). For this reason, C++ often treats a character like an integer.
7/14/2008
15
7/14/2008
16
2.5
Note:
In C++ the Boolean constants are true and false. Additionally, following traditional standards, any nonzero number is considered true, and zero is considered false.
Variables
7/14/2008
17
7/14/2008
18
Figure 2-9
Variables in memory
Note: When a variable is defined, it is not initialized. The programmer must initialize any variable requiring prescribed data when the function starts.
7/14/2008
19
7/14/2008
20
cout << "Welcome. This program adds\n"; cout << "three numbers. Enter three numbers\n"; cout << "in the form: nnn nnn nnn <return>\n"; cin >> a >> b >> c; // Numbers are now in a, b, and c. Add them. sum = a + b + c; cout << "\nThe total is: " << sum << "\n"; cout << "\nThank you. Have a good day.\n"; return 0; } // main
7/14/2008 22
2.6
Note: A character constant is enclosed in single quotes.
Constants
7/14/2008
23
7/14/2008
24
Note: Use single quotes for character constants. Use double quotes for string constants.
Note: The only bool types constants are true, printed as 1, and false, printed as 0.
7/14/2008
25
7/14/2008
26
Figure 2-10
Some strings
Figure 2-11
"" "h" "Hello World!\n" "HOW ARE YOU?" "Good Morning!" "'Good' Morning!" "\"Good\" Morning!"
// A null string
\0
7/14/2008
27
7/14/2008
28
2.7
Coding Constants
7/14/2008
29
7/14/2008
30
2.8
Figure 2-12
Standard streams
2.9
*/ #include <iostream> using namespace std; int main () { // Statements cout << 24 << " -> This is an integer\n"; // Print an integer cout << 12.3 << " -> This is a float\n"; // Print a float cout << 'A' << " -> This is a character\n"; // Print a character cout << "Hello World!" << " ->This is a string\n"; // Print a string system("PAUSE"); return 0; } // main
7/14/2008 33 7/14/2008
Programming Examples
Page 60 - 64
34