CS2311 Lec02 Basic
CS2311 Lec02 Basic
Output
Input
• Main Memory: stores both data and program,
i.e., a list of instructions Arithmetic/Logic
Hard Disk Unit (ALU)
• CPU (Central Processing Unit):
• ALU: performs arithmetic and bitwise operations
• Control Unit: read instructions from memory, Mian Memory
direct ALU to execute instructions
• External storage: (slow) mass storage
External Storage
• Input/output: keyboard, display …
2
Quick Review: What’s a Computer Program
Logic Flow
Computer
Program
Input Process Output
Instructions Data
3
Quick Review: Programming Languages
Compiler
4
Quick Review: Basic Syntax and Program
/* What’s wrong with the following program? */
Refer to
#include <iostream>
include Liostream mistake Study Note
using namespace std;
int main() Basic Ctt
{ Programming
mistake mistake
cout <cHello world! <cendl mistake
return 0;
}
5
Today’s Outline
• C++ basic syntax
• Variable and constant
• Operators
• Basic I/O
6
A Simple C++ Program
#include <iostream>
11 the library of Ctt
using namespace std; 11 importing thestandard of Ctt
int main() { ie cont Cin
float r, area; // the radius and area of the circle
cout << “Input circle radius ”; // print prompt on screen
cin >> r; // let user input r from keyboard
area = 3.1415926 * r * r; // calculate circle area
cout << “Area is ” << area << endl; // print result on screen
return 0;
}
Syntax of C++
• Like any language, C++ has an alphabet and rules for putting together
words and punctuations to make a legal program.
This is called syntax of the language.
• C++ compiler collects the characters of the program into tokens, which
form the basic vocabulary of the language
8
Tokens in C++
• Tokens in C++ can be categorized into:
String Numeric
Punctuators
constants constants
9
Tokens in C++: An Example
#include <iostream> preprocessor
using namespace std ; .
int main ( ) { . keywords
float r , area ; . identifiers
cout << “input circle radius ” ; .
operators
cin >> r ; .
area = 3.1415926 * r * r ; . string constants
cout << “area is ” << area << endl ; .
numeric constants
return 0 ; .
}. punctuators
10
Keywords
• Words reserved by the #include <iostream>.
programming language using namespace std;
int main() {
• Each keyword in C++ has a float r, area;
reserved meaning and cannot
cout << “input circle radius ”;
be used for other purpose
cin >> r;
Bool
Other
11
Keywords (cont’d)
Data type char double float int bool
long short signed unsigned void
Flow control if else switch case while
break default for do continue
Others using namespace true false sizeof
return const class new delete
operator public protected private friend
this try catch throw struct
typedef enum union
14
Identifiers
• Identifiers give unique names to #include <iostream>.
various objects in a program likeusing namespace std;
the name of variables, functions,int main() {
libraries, and namespace float r, area;
cout << “input circle radius ”;
• Keywords cannot be used as
cin >> r;
identifiers
area = 3.1415926 * r * r;
cout << “area is ” << area << endl;
Which of the following
return 0;
is are identifier }.
cont float hello would
using namespace Ans 15
Identifiers (cont’d)
• An identifier is composed of a sequence of letters, digits and underscore
• E.g., myRecord, point3D, last_file
16
Identifiers (cont’d)
float a (float b, float c, float d)
{
return (b + c) * d / 2;
}
18
Today’s Outline
• C++ language syntax
• Variable and constant
• Operators
• Basic I/O
19
Variable and Constant
• Computer programs typically involve data
access Logic Flow
22
Variable/Constant Name
• Which of the following are valid variable/constant names?
[A] you
A valid variable
[B] CityU_CS name must begin
[C] 2U with underscore or
letter Number can
[D] $cake
be included after
[E] \you the first character
[F] CityU-CS of the variable
name
23
Variable and Constant
• Every variable/constant has 5 attributes
• Address: location of data in memory storage
• Value: content in memory storage
• Name: identifier of the variable
• Type: C++ is a strictly typed language,
variable/constant must belong to a data type
• E.g., numerical, character, logic, other…
• Scope: it defines the region within a program
where the variable/constant can be accessed,
and also the conflict domain (more detail soon)
25
Variable Declaration
• Variable and constants must be declared before use
• Variable declaration format
data_type variable_identifier ;
• Optionally, you can set the initial value of variable during declaration
• Examples
int age ;
float bathroom_temperature = 28, bedroom_temperature = 30 ;
char initial ;
char student_name[20] ;
26
C++ Predefined Data Types Type keyword
• Numerical
• int, short, long: integer number
• float, double: real number
• Character
• char: ASCII character (a, e, o, \n) Refer to the
• Logic (next lecture) ASCII Table
• bool: Boolean (true, false)
• Other
• void: empty values (e.g., void main() {…})
27
int
• Typically, an int is stored in 4 bytes (1 byte = 8 bits)
• The most significant bit of an int data type is the sign bit
• 0: positive
• 1: negative
• For example
00000000 00000000 00000000 00001111 = 15
• What’s the decimal value of the following integer?
10000000 00000000 00000000 00000001 = ?
28
int
• C++ uses two’s complement to encode negative numbers
• E.g., for -11
stepI • reverse the sign
00000000 00000000 00000000 00001011
step2• invert the bits (0 goes to 1, and 1 to 0)
11111111 11111111 11111111 11110100
steps
• add 1 to the resulting number
11111111 11111111 11111111 11110101
31
Find the range of 30 bit
int integer that can store
229 and 229 I
• A 32-bit int can store any integer in the range of -231 and 231-1
• i.e., -2147483648 to 2147483647
• max int: 01111111 11111111 11111111 11111111
• min int: 10000000 00000000 00000000 00000000
36
char
• Used to store a single character, enclosed by the single quotation mark
char c = ‘a’; The output of char type is a character
char c = ‘\n’; where c is an integer of the ASCII
code
• Characters are treated as small integers (and vice versa)
• A char type takes 1 byte (8 bits, representing up to 256 characters)
• `a’ is stored as 01100001, equivalent to an integer 97
• `b’ is stored as 01100010, equivalent to an integer 98
• …
37
ASCII Code
38
string
• A string is an array of characters
• Both array and string will be introduced in detail in future lectures
• Strings are delimited by double quotation marks “”, and the identifier must
be followed with [] or begin with *
char course_name[] = “Computer Programming";
char *course_name= “Computer Programming";
char initial[] = "C"; vs. char initial = ‘C’;
39
Floating Types
• Represent real numbers using floating point representation
float height;
double weight = 120.8;
long double number;
• float takes 4 bytes, but is less accurate (7 digits after decimal point)
• double takes 8 bytes, but more accurate (15 digits after decimal point)
• the default type for floating type in C++
• long double is even more precise, but rarely used
• Exponent representation is acceptable, e.g.,
double a = 1.23e3; is 1230
output 42
sizeof
• sizeof can be used to find the #include <iostream>
number of bytes needed to using namespace std;
store an object (which can be int main() {
a variable or a data type) int a = 4;
cout << sizeof(a) << endl;
cout << sizeof(int) << endl;
• Its result is typically returned
cout << sizeof(double) << endl;
as an unsigned integer
cout << sizeof(long double) << endl;
return 0;
}
43
Type Conversion
• Very often, we need to convert data from one type to another
For example:
Each pig weighs 280.3 lbs (float)
Each boat can carry 615.2 lbs (float)
How many pigs a boat can carry? (int)
47
Type Conversion
9. long double
• Explicit type conversion (type-casting) 8. double
int a = 3; 7. float
double b = (int)a;
6. long long
• Demoted values might change or become invalid 5. long
4. int
3. short
double a = 3.1; double a = 3.9;
3.0
int b = (int)a; int b = (int)a; 2. char
cout << b << endl; cout << b << endl;
T 1. bool
Change the type
of a from double to
and to b as the type
50
Example
#include <iostream>
using namespace std;
int main() {
int i = 5; char a = ‘B’;
double x = 1.57;
i = i + x; cout << i << endl;
x = x * a; cout << x << endl;
return 0;
}
51
Constants The type of constant value
can't be changed
• Like variables, constant store data for program access but its value will
NOT be changed after declaration
• You MUST set the initial value of the constant during declaration
const data_type constant_identifier = value ;
52
#include <iostream>
Scope using namespace std;
• Scope of a variable/constant void foo() {
refers to the region of a program int a = 0; .
where the variable/constant is cout << “a in foo: ” << a << endl;
visible (can be accessed)
}
Example I: int main() {
foo();
• The accessibility of variable ‘a’
is within function ‘foo’ cout << “a in main: ” << a << endl;
return 0;
• Trying to access ‘a’ in ‘main’
}
will cause an error
53
#include <iostream>
Scope using namespace std;
• Scope of a variable/constant int main() {
refers to the region of a program int a = 0; .
where the variable/constant is int a = 1; .
visible (can be accessed)
cout << “a in main: ” << a << endl;
Example II: return 0;
}
• Defined two ‘a’ within ‘main’
• Will cause an error due to
conflict domain
54
#include <iostream>
Scope using namespace std;
• Scope of a variable/constant void foo() {
refers to the region of a program int a = 0; .
where the variable/constant is cout << “a in foo: ” << a << endl;
visible (can be accessed)
} 0
Example III: int main() {
int a = 1; .
• Defined two variables with the
same name ‘a’ foo();
cout << “a in main: ” << a << endl;
• Their accessibilities are within
return 0; I
‘foo’ and ‘main’, respectively
}
Th fool a 0 only I
th matric act only
non global 55
#include <iostream>
Scope using namespace std;
• Scope of a variable/constant int a = 0; .
refers to the region of a program void foo() {
where the variable/constant is cout << “a in foo: ” << a << endl;
visible (can be accessed)
}
Example IV: a of int main() {
foo();
• Defined a global variable ‘a’
cout << “a in main: ” << a << endl;
• Its accessibility is the entire return 0;
program
}
58
#include <iostream>
using namespace std;
int a = 0;
namespace level1 {
int a = 1;
namespace level2 {
int a = 2;
}
}
int main() {
int a = 3;
cout << ::a << endl; value a of level O
cout << level1::a << endl; value a of level I
cout << level1::level2::a << endl;
return 0;
} 59
#include <iostream>
using namespace std;
int a = 0;
namespace level1 {
int a = 1;
namespace level2 {
int a = 2;
}
}
int main() {
int a = 3; .
cout << ::a << endl;
cout << level1::a << endl;
cout << level1::level2::a << endl;
return 0; outer level inner level global must be written
} in this way
note that level I contains level 2 60
#include <iostream>
using namespace std;
int a = 0;
namespace level1 {
int a = 1;
namespace level2 {
int a = 2;
}
}
int main() {
int a = 3; .
cout << ::a << endl;
cout << level1::a << endl;
cout << level1::level2::a << endl;
return 0;
} 61
Today’s Outline
• C++ basic syntax
• Variable and constant
• Operators
• Basic I/O
62
Operators
• An operator specifies an operation to be performed on some values
• These values are called the operands of the operator
64
Assignment Operator =
• Generic form: variable = expression ;
• Write the value of expression into the memory storage of variable
• An expression is a combination of constants, variables, and function
calls that evaluate to a result
• Examples:
float a = 2.0 * 4.0 * 8.0; 2 4 8 64
float b = a – sqrt(a); 64
char x = ‘a’;
564 56
65
Assignment Operator =
• An expression itself has a value, e.g.,
a = (b = 2) + (c = 3);
71
Swapping the Values
• If we want to swap the content of two variables, a and b
• What’s the problem of the following program?
int a = 3;
int b = 4;
a = b; update 3 to 4
a from
b = a;
be updated value of a
To swap a and b we need
to define a buffer 72
Swapping the Values
• We need to make use of a temporary variable:
int a = 3;
int b = 4;
int c; // a buffer for value swapping
c = b; // save the old value of b
b = a; // put the value of a into b
a = c; // put the old value of b to a
74
Efficient Assignment Operators
• Generic form of efficient assignment operators
variable op = expression ;
where op is operator; the meaning is
variable = variable op (expression) ;
• Efficient assignment operators include
+=, -=, *=, /=, %=, %=, >>=, <<=, &=, ^=, |=
• Examples
a += 5; // is the same as a = a+5;
a %= 5; // is the same as a = a%5;
a *= b+c; // is the same as a = a*(b+c)
75
Increment & Decrement Operators
• Increment and decrement operators: ++ and --
• k++ and ++k is equivalent to k=k+1;
• k-- and --k is equivalent to k=k-1;
77
Example
#include <iostream>
using namespace std;
int main() {
int x = 3;
cout << ++x; 11 I x Xt 2 Contax
cout << x++; 11
I cont Cx Z X Xt
cout << x;
11 I Contax
return 0;
}
78
Example
#include <iostream>
using namespace std; old x new x cout
int main() {
int x = 3; 3
int x = 3;
cout << ++x; 3 4 4
cout << ++x;
cout << x++; cout << x++; 4 5 4
cout << x; cout << x; 5
return 0;
}
79
What values are printed?
int a = 0, b = 0;
cout << “b = ” << b << endl;
a = 0;
b = 1+(a++); I Delta
cout << “b = ” << b << endl;
Output:
L2 a att
b = 0
cout << “a = ” << a << endl;
b = 1
a = 0; a = 1
b = 1+(++a);
cout << “b = ” << b << endl;
b = 2
cout << “a = ” << a << endl; a = 1
83
a = 0; a = 0;
b = 1 + (a++); b = 1 + (++a);
0 1
1. Evaluates a++, (value:0) 1. Computes a = a+1
2. Computes a = a+1 2. Evaluates ++a (value:1)
3. b = 1 + 0 3. b = 1 + 1
=1 =2
82
Precedence & Associativity of Operators
• An expression may have more than one operators and its precise
meaning depends on the precedence and associativity of the involved
operators
• Precedence: order of evaluation for different operators
• determines how an expression like x R y S z should be evaluated, where
R and S are different operators, e.g., x + y / z.
84
Precedence & Associativity of Operators
• What’s the value of a, b, c after executing the following statements?
int a, b = 2, c = 1;
a = b+++c;
85
Precedence & Associativity of Operators
Operator Precedence (high to low) Associativity
None
highest[] priority
::
. -> Left to right
() ++(postfix) --(postfix) Left to right
+ - ++(prefix) --(prefix) Right to left
* / % Left to right
+ - Left to right
= += -= *= /= etc.
lowest priority
Right to left
8811 1 use or
logic
use and 89
Bitwise Operators (cont’d)
• Bitwise XOR ^ • Bitwise NOT ~
• Compute XOR on every bit of • Takes one number and inverts
two numbers all of its bits
• The result of XOR is 1 if the The result of XOR is 1 if the two
two bits are different bits are different
00 11 11 11 111058 8881
I 0 01
10 10
90
Bitwise Operators (cont’d)
• Left shift << and right shift >>
• a << n: left shifts the bits of a for n digits
• a >> n: right shifts the bits of a for n digits
• Note that whether << or >> is explained as bit shift depends on context
• e.g., in cout << x, << is the output operator
in cout >> x, >> is the input operator
91
Example I
• What’s the output of the following statements?
92
Example II
• Print a char type in binary format
char x = 112;
int b0 = (x >> 0) & 1; int b1 = (x >> 1) & 1;
int b2 = (x >> 2) & 1; int b3 = (x >> 3) & 1;
int b4 = (x >> 4) & 1; int b5 = (x >> 5) & 1;
int b6 = (x >> 6) & 1; int b7 = (x >> 7) & 1;
cout << b0 << b1 << b2 << b3 << b4 << b5 << b6 << b7 << endl;
93
Today’s Outline
• C++ basic syntax
• Variable and constant
• Operators (and punctuators)
• Basic I/O
94
Basic I/O – Keyboard and Screen
• A program can do little if it cannot take input and produce output
• Most programs read user input from keyboard and secondary storage
• After process the input data, result is commonly displayed on screen or
write to storage (disk)
Program
ta
da
of
eam
Str
95
Basic I/O: cin and cout
• C++ comes with an iostream package (library) for basic I/O
• cin and cout are objects defined in iostream for keyboard input and
screen display, respectively
• To read data from cin and write data to cout, we need to use input
operator (>>) and output operator (<<)
96
cout: Output Operator (<<)
• Preprogrammed for all standard C++ data types
• It sends bytes to an output stream object, e.g. cout
• Predefined “manipulators” can be used to change the default format of
arguments
Output Output
Program 18.9 Manipulator 18.90 18.90
Stream Object Device
98
cout: Output Operator (<<)
Type Expression Output
Integer cout << 21 21
Float cout << 14.5 14.5
Character cout << ‘a’; a
cout <<‘H’ << ‘i’ Hi
Bool cout << true 1
cout << false 0
String cout << “hello” hello
New line (endl) cout << ‘a’ << endl << ‘b’; a
b
Tab cout << ‘a’ << ‘\t’ << ‘b’; a b
Special characters cout << ‘\”’ << “Hello” << ‘\”’ <<endl; “Hello”
Expression int x=1; 8
cout << 3+4 +x;
cout: Change the Width of Output
• Calling member function width(width) or using setw manipulator
• setw requires “ipmanip”, i.e., #include <iomanip>
• Leading blanks are added to any value that has fewer characters than ‘width’
• If formatted output exceeds the width, the entire value prints
• Effect lasts for one field only the next field will not
Approach Example be effect
taken into Output (: space key)
1. cout.width(width) cout.width(5); //or cout << setw(5);
cout << 123 << endl; 123
2. setw(width) cout << 123 << endl; 123
101
cout: Floating-Point Precision and Format
• Default precision (6 digits, 5 digits after decimal points) and format
• cout << fixed: always uses the fixed-point notation (6 significant digits after the
decimal point)
Round off the last digit
• cout<< scientific: always uses the scientific notation
Example Default output After cout << fixed; After cout << scientific;
cout << 1.23 << endl; 1.23 1.230000 1.230000e+00
cout << 1.230 << endl; 1.23 1.230000 1.230000e+00
cout << 1.2345678 << endl; 1.23457 1.234568 1.234568e+00
cout << 0.000012345678 << endl; 1.23457e-05 0.000012 1.234568e-05
104
cout: Floating-Point Precision and Format
• Normally, setprecision(n) means output n significant digits
• But with “fixed” or “scientific”, setprecision(n) means output n significant digits
after the decimal point
Example Output
cout << setprecision(2);
cout << 1.234 << endl; 1.2
cout << 0.0000001234 << endl; 1.2e-07
cout << fixed;
cout << 1.234 << endl; 1.23
cout << 0.0000001234 << endl; 0.00
cout << scientific << 1.234 << endl; 1.23e+00
cout << 0.0000001234 << endl; 1.23e-07
106
cout: Other Manipulators
Manipulators Example Output
fill cout << setfill(‘*’);
cout << setw(10); set 10 character
cout << 5.6 << endl; *******5.6
cout << setw(10);
cout << 57.68 << endl; *****57.68
radix cout << oct << 11 << endl; // octal 13
cout << hex << 11 << endl; // hexidecimal b
cout << dec << 11 << endl; 11
110
cin: Input Operator (>>)
111
cin: Input Operator (>>)
112
cin: Input Operator (>>)
113
Expected Outcome
• Describe the basic syntax and data types of C++ language
• Explain the concepts of variable, constant, and their scope
• Declare variable and constant under different scopes
• Perform update on variables via different operators
• Able to output variables’ values to screen with different precision and
format
• Able to read value from keyboard and assign to variable
114