Chapter 2

advertisement
Elements of a C++ program
1
Review
 Algorithms
 describe how to solve a problem
 Structured English (pseudo-code)
 Programs
 form that can be translated into machine instructions
 high-level programming language: C++
2
3
“Hello, world!”
preprocessor directive
#include <iostream>
using namespace std;
function
using directive
int main( )
{
//print a sentence
cout << "Hello, world!" << endl;
return 0;
}
comment
output statement
4
Function
 A C++ program is a collection of one or more functions
(subprograms).
 Each function does some specific task in order to solve the problem.
 There must be a function called main()
 Execution always begins with the first statement in
function main()
 Any other functions in your program are subprograms
and are not executed until they are called
Try helloWorldAmerica.cpp
5
returned value type
Function
block
function name
int main( )
parameters
{
cout << "Hello, world!" << endl;
return 0;
}
statement
return value
 A block is a sequence of zero or more statements enclosed
by a pair of curly braces { }
 Each statement is ended by a semicolon ;
 If a function does not return any value, the return value
type should be void
 Otherwise, there must be a return statement:
 return the value
 tell the computer that the function execution is done
 There are some rules to name a function (identifier)
 Parameters send the input to the function
6
The output statement: cout
cout << "Hello, world!" << endl;
 begins with cout
 endl means “end of the line”. (same as ‘\n’)
 It moves the cursor to the next line of the display
 It does not have to be the last thing in a cout statement
 each thing (literal, variable, endl) is preceded with << (insertion operator)
 Put spaces around the insertion operator
 literals must be enclosed with quotation marks
 A blank line can be created in output by using listing two endl statements
 Blank spaces results when adding spaces between quotation marks
Play with helloWorld.cpp
7
The input statement: cin
string name;
cin >> name;
cout << “Hello, “ << name << “!” << endl;
 cin reads the next string you type on the keyboard and stores it into
the variable name.
 >> (extraction operator) can be used several times in a single input
statement:
string firstName, lastName;
cin >> firstName >> lastName;
cout << “Hello, “ << firstName << “ “ << lastName << “!” << endl;
 the input will be divided by space or newline into multiple variable
values.
8
Interactive Input/Output
 Make a nice Human Computer Interface (HCI)
 Prompt for input
 Display the result with meaningful explanations
 Make the screen look nice!
Please input the student ID: 1001
The student information is as following:
* first name: John
* last name: Smith
* major:
Computer Science
* email:
smithj@university.edu
Can you print a 3*3 blank table?
9
Comments
 Comments are explanations of the program, function,




statement, etc.
It is part of the documentation.
It starts with //.
In one line, anything after // is ignored by the
compiler.
Another style:
/* comments */
 Read the C++ Programming Ground Rules
10
Preprocessor directive
#include <iostream>
 Insert the contents of a file named iostream into the program.
 A file whose name is in #include directive is a header file.
 A preprocessor will preprocess the codes before the compiler by
 inserting included header files
 removing all comments.
11
Using directive
using namespace std;
 so that we can use cin,
cout, endl,
etc;
 This statement should be placed before the main
function, if iostream is used.
12
13
What is a computer?
Network
Input
CPU
Output
MEMORY
Storage
14
Hardware
 CPU
 Memory
 Keyboard
 Monitor
 Disk
…
15
How to Store Data in Computer
Bit
Electronic Device
On / Off
Value: 1 / 0
Byte
8 bits
Possible combinations
256
28
16
How to Store Data in Computer
Binary Number: 10001111
27
1
27
128
26 25 24
23 22 21 20
0
1
0
0
1
1
1
+ 23 + 22 + 21 + 20
+8 +4 +2 +1
Decimal Number: 143
17
How to Store Data in Computer
Integers
Binary Numbers
Characters
ASCII
Unicode
Float Numbers?
Negative numbers?
18
How to Store Data in Computer
KB
1024 Bytes
210
MB
1024 * 1024 Bytes
220
GB
1024 * 1024 * 1024 Bytes
230
TB…
19
Declaration Statements
string name;
string firstName, lastName;
int num = 10;




DataType Identifier , Identifier, … ;
Variable: a memory location to store data
Variable value: the content in the location
Identifier: the symbolic name of a variable
Data Type: the type of data the variable is for
 A declaration tells the compiler to allocate enough
memory to hold a value of this data type and to associate
the identifier with this location
20
Variables
 Variables can have initial values
int num1, total = 0;
 Variables can have different values
cin >> num1;
num1 = 58;
total = total + num1;
Identifier
 An identifier is the name used for a data object(a
variable or a constant), or for a function, in a C++
program
 Beware: C++ is a case-sensitive language
 Using meaningful identifiers is a good
programming practice
22
Good Identifiers
 An identifier must start with a letter or underscore, and be
followed by zero or more letters
(A-Z, a-z), digits(0-9), or underscores
 VALID
age_of_dog
PrintHeading
taxRateY2K
ageOfHorse
 NOT VALID (Why?)
age#
2000TaxRate
Age-Of-Cat
 Identifiers should be meaningful!!!
 BAD
a
bbb
s_1234
23
C++ Data Types
simple
integral
enum
structured
floating
array struct union class
char short int long bool
float double long double
address
pointer reference
24
Numerical Data Types
 On a 32 bit architecture:
char: 1 byte
int:
2 bytes
long: 4 bytes
float: 4 bytes
double: 8 bytes
(character)
(integer)
(real number)
 Storage (and Range) is machine/system
dependent
25
char
 One Byte
01000011
What is the value of the byte?
 As integer:
67
 As ASCII char:
‘C’
26
ASCII Code Table
0
1
2
3
4
5
6
7
4
5
2
3
4
5
6
6
8
9
0
1
7
8
9
A
B
C
D
E
7
F
G
H
I
J
K
L
M
N
O
8
P
Q
R
S
T
U
V
W
X
Y
9
Z
a
b
c
10
d
e
f
‘C’: 67
‘Y’: 89
‘9’: 57
All upper case letters together
All lower case letters are together
All digits 0 through 9 are together
lower case = upper case + 32
27
ASCII Code
Char
‘C’:
‘D’:
‘B’:
‘e’:
‘0’:
‘5’:
ASCII Code
67
?
?
?
48
?
28
char and string
// char : 1 byte
// describes a letter, a digit or a special symbol
char theChar = ‘A’;
// string: one byte for each char
//
one more byte at the end to
//
indicate the end
// a sequence of characters
string myString = “CS 143”; What is the length of myString?
A string must be typed entirely on one line!
What would happen if it’s not?
29
String Operations
string course = “CS 143”;
cout << course.length() << endl;
cout << course.size() << endl;
cout << course.substr(0,2) << endl;
6
6
CS
both string.length() and string.size() return the size of a string,
that is, how many characters are contained in the string.
This size does NOT consider the end byte!
string.substr (pos, len) returns the substring of at most len charactors,
starting at position pos of the string.
The position index starts with 0!
30
C++ Data Types and Storage
int num1, num2;
int Sum;
float average;
num1
4
num2
Sum
5
9
num1 = 4;
num2 = 5;
average
Sum = num1 + num2;
average = Sum / 2.0;
4.5
char grade = ‘A’;
string courseName;
courseName
courseName = “CS143”;
C S 1 4 3
grade
\0
A
31
Symbolic Constant
const DataType Identifier = LiteralValue;
const int
MAX_CREDIT_PER_SEMESTER = 21;
const char
BLANK = ‘ ‘;
const string COURSE_NAME = “Programming in C++”;
 The value of a constant never changes.
 Why using constant? No Magic Numbers!
 The identifier of a constant:
 ALL UPPER CASE
 separate the English words with an underscore _
 Comment your constant declarations
32
Is it OK?
const string COURSE_NAME = “Programming in C++”;
.
.
.
cin >> COURSE_NAME;
//Is it OK?
COURSE_NAME = “CS 143”; //Is it OK?
The values of constants CANNOT be changed!
Note: in HiC, string constant is not supported!
33
Summary
 function
 input/output
 comment
 #include
 data type
 variable
 identifier
 constant
 declaration
34
Download