0% found this document useful (0 votes)
2 views

CS2311-Lec02-basic

The document provides an overview of computer programming concepts, focusing on C++ syntax, data types, variables, constants, and basic input/output operations. It explains the structure of a computer, the role of the CPU, and the differences between programming languages. Additionally, it covers the importance of identifiers, keywords, and the attributes of variables and constants in C++.

Uploaded by

chuigary70866
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CS2311-Lec02-basic

The document provides an overview of computer programming concepts, focusing on C++ syntax, data types, variables, constants, and basic input/output operations. It explains the structure of a computer, the role of the CPU, and the differences between programming languages. Additionally, it covers the importance of identifiers, keywords, and the attributes of variables and constants in C++.

Uploaded by

chuigary70866
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 131

CS2311 Computer Programming

LT02: Data, Operators, and Basic IO

Computer Science, City University of Hong Kong


Semester A 2024-25
Quick Review: What’s a Computer
• von Neumann machine (stored program CPU
computer) Control Unit

Output
Input
• Main Memory: stores both data and program,
i.e., a list of instructions Arithmetic/Logic
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

Machine Language Symbolic Language High-level Language


Language directly English-like abbreviations Close to human language.
understood by the representing elementary Example: a = a + b
computer computer operations [add vales of a and b, and
Defined by ISA store the result in a,
replacing the previous
value]
x86, RISC … Assembly language C/C++, Java, Python

4
Quick Review: Basic Syntax and Program
/* What’s wrong with the following program? */
#include <iostream>
using namespace std;
int main()
{
cout < Hello world! < endl
return 0;
}

5
Today’s Outline
• C++ basic syntax
• Variable and constant
• Operators
• Basic I/O

6
A Simple C++ Program
#include <iostream>
using namespace std;
int main() {
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++ compilers detect any violation of the syntax rules in a program

• C++ compiler collects the characters of the program into tokens, which
form the basic vocabulary of the language

• Tokens are separated by space

8
Tokens in C++
• Tokens in C++ can be categorized into:

Keywords Identifiers Operators

String Numeric
Punctuators
constants constants

9
Tokens in C++: An Example
#include <iostream> preprocessor
using namespace std ; .
keywords
int main ( ) { .
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;
area = 3.1415926 * r * r;
cout << “area is ” << area << endl;
return 0;
}.

11
Keywords (cont’d)
Data type char double float int bool
long short signed unsigned void

12
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

13
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 like using 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;
return 0;
}.

15
Identifiers (cont’d)
• An identifier is composed of a sequence of letters, digits and underscore
• E.g., myRecord, point3D, last_file

• An identifier must begin with either an underscore or a letter


• Valid identifiers: _income, _today_record, record1
• Invalid identifiers: 3D_point, 2ppl_login, -right-
• Identifier is case sensitive

• Always use meaningful names for identifiers

16
Identifiers (cont’d)
float a (float b, float c, float d)
{
return (b + c) * d / 2;
}

17
Identifiers (cont’d)
float a (float b, float c, float d)
{
return (b + c) * d / 2;
}

float trapezoid_area (float upper_edge, float lower_edge, float height)


{
return (upper_edge + lower_edge) * height / 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

• Two categories of data in C++ program


Computer
• Variable: memory storage whose value can Program
be changed during program execution
• Constant: memory storage whose value
does NOT change during program Instructions Data
execution

20
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, needs to be declared
• Type: C++ is a strictly typed language, variables and constants 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

21
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, needs to be declared
• Type: C++ is a strictly typed language, variables and constants 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

22
Address
More details in pointer lectures
(around week 9)

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, needs to be declared
• Type: C++ is a strictly typed language, variables and constants 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

24
Decimal vs Binary

102 101 100


1 0 3

25
Decimal vs Binary

102 101 100 27 26 25 24 23 22 21 20


1 0 3 01100111

26
Decimal vs Binary

102 101 100 27 26 25 24 23 22 21 20


1 0 3 01100111
0+64+32+0+0+4+2+1
= 103
27
Decimal to Binary
• divide the decimal number by 2
• store the remainder
• repeat

• Practice: what’s the binary expression of 30?

28
Hexadecimal
• Express 0 to 15 as:

0123456789abcdef

29
Hexadecimal to Decimal

163 162 161 160


0x 0 1 0 1 = ?

30
Hexadecimal to Decimal

163 162 161 160


0x 0 1 0 1 = 257
0x 0 0 a f = ?
31
Decimal to Hexadecimal
• What’s the hex expression of 4387?

32
Decimal, Binary and Hex
Representations
• In C++, you can represent a value in either decimal, binary, or hex

// For example, a, b, and c below all equal to 31


a = 31; // decimal
b = 0b11111; // binary
c = 0x1f; // hex

33
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, needs to be declared
• Type: C++ is a strictly typed language, variables and constants 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

34
Naming Rules
• Case sensitivity
• myVar and myvar are different identifiers
• Do not use reserved key words
• Must begin with a letter or underscore
• No spaces
• Use meaningful names

35
• Which of the following are valid variable/constant names?
[A] you
[B] CityU_CS
[C] 2U
[D] $cake
[E] \you
[F] CityU-CS

36
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] ;

37
Constant Declaration
• Variable and constants must be declared before use
• Constant declaration format
const data_type variable_identifier = value ;
• You MUST assign an initial value to a constant during declaration
• The value of a const CANNOT be changed after declaration
• Examples
const int days_per_year = 365;
days_per_year = 366; // error
const int hrs_per_day; // error
38
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, needs to be declared
• Type: C++ is a strictly typed language, variables and constants 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

39
C++ Data Types
• Numerical
• int, short, long, integer numbers
• unsigned: non-negative integer numbers
• float, double: real numbers
• Character
• char: ASCII character (a, e, o, \n)
• Logic (next lecture)
• bool: Boolean (true, false)
• Other
• void: empty values (e.g., void main() {…})

40
int: Encoding
• 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 = ?

41
int: Encoding
• C++ uses two’s complement to encode negative numbers
• E.g., for -11
• reverse the sign
00000000 00000000 00000000 00001011

42
int: Encoding
• C++ uses two’s complement to encode negative numbers
• E.g., for -11
• reverse the sign
00000000 00000000 00000000 00001011
• invert the bits (0 goes to 1, and 1 to 0)
11111111 11111111 11111111 11110100

43
int: Encoding
• C++ uses two’s complement to encode negative numbers
• E.g., for -11
• reverse the sign
00000000 00000000 00000000 00001011
• invert the bits (0 goes to 1, and 1 to 0)
11111111 11111111 11111111 11110100
• add 1 to the resulting number
11111111 11111111 11111111 11110101

44
int: Range
• 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

45
int: Overflow/Underflow
• When an int is assigned a value greater than its maximum value,
overflow occurs

• Similarly, underflow occurs when a value smaller than the minimum value
is assigned

• However, C++ does not inform you the errors

46
Example
#include <iostream>
using namespace std;
int main() {
int num1 = 2147483647; // i.e., num1=0x7fffffff;
int num2 = num1 + 1;
cout << num2 << endl; // if int is 4-byte, you'll see a
// negative number
return 0;
}

47
short and long
• long is used for large integers (typically 4 bytes on 32-bit machines and 8
bytes on 64-bit machines)
• long stars_in_universe; // about 100 billion, needs 38 bits

• short is used for small integers (typically 2 bytes)


• short minute_per_day; // 60*24=1440, needs 11 bits

48
unsigned
• unsigned is used to declare that the integer data type is non-negative

• For example
unsigned short age;
unsigned int salary;
unsigned long population;

• unsigned integers has no sign bit


• i.e., the range of unsigned int is 0 to 232-1

49
char
• Used to store a single character, enclosed by the single quotation mark
char c = ‘a’;
char c = ‘\n’;

• Characters are treated as small integers


• 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
• …
• For example: char x = 97;
cout << x << endl;

50
ASCII Code

51
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’;

52
Floating Types
• Represent real numbers using floating point representation
float height;
double weight = 120.8;
long double number;

53
Floating Types
• Represent real numbers using floating point representation
float height;
double weight = 120.8;
long double number;
• float typically takes 4 bytes, is less accurate (7 digits after decimal pt)
• double typically takes 8 bytes, is more accurate (15 digits after decimal pt)
• the default type for floating point type in C++
• long double is even more precise, but rarely used

54
Floating Types
• Represent real numbers using floating point representation
float height;
double weight = 120.8;
long double number;
• float typically takes 4 bytes, is less accurate (7 digits after decimal pt)
• double typically takes 8 bytes, is more accurate (15 digits after decimal pt)
• the default type for floating point type in C++
• long double is even more precise, but rarely used
• Exponent representation is acceptable, e.g.,
double a = 1.23e3;
55
sizeof
• sizeof can be used to find the #include <iostream>
number of bytes used to using namespace std;
store an object (which can be int main() {
a variable or a data type) int a = 4;
• Its result is typically returned cout << sizeof(a) << endl;
as an unsigned integer cout << sizeof(int) << endl;
cout << sizeof(double) << endl;
• sizeof of data type varies
across machines and cout << sizeof(long double) << endl;
implementations return 0;
}
56
Default Types
• In C++, the default types of integer numbers is typically int
cout << sizeof(1); // equivalent to cout << sizeof(int)

• In C++, the default types of floating pint numbers is typically double


cout << sizeof(1.0); // equivalent to cout << sizeof(double)

• In the above examples, the types of 1 and 1.0 are int and double by
default

57
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)

58
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)

float pig_weight = 280.3, boat_load = 615.2;


int n_pig = boat_load/pig_weight;

int float
59
Type Conversion
9. long double
• Implicit type conversion 8. double
• Binary expression: lower-ranked operand is 7. float
promoted to higher-ranked operand, e.g.,
int r = 2; 6. long long
double pi = 3.14159; 5. long
cout << pi * r * r << “\n”; 4. int
3. short

2. char

1. bool

60
Type Conversion
9. long double
• Implicit type conversion 8. double
• Binary expression: lower-ranked operand is 7. float
promoted to higher-ranked operand, e.g.,
int r = 2; 6. long long
double pi = 3.14159; 5. long
cout << pi * r * r << “\n”; 4. int
3. short
• Assignment: right operand is promoted/demoted
to match the variable type on the left, e.g., 2. char
double a = 1.23;
int b = a; 1. bool

61
Type Conversion
9. long double
• Explicit type conversion (type-casting) 8. double
int a = 3; 7. float
double b = (double)a;
6. long long
5. long
4. int
3. short

2. char

1. bool

62
Type Conversion
9. long double
• Explicit type conversion (type-casting) 8. double
int a = 3; 7. float
double b = (double)a;
6. long long
• Demoted values might change or become invalid 5. long
4. int
3. short
double a = 3.1;
int b = (int)a; 2. char
cout << b << endl;
1. bool

63
Type Conversion
9. long double
• Explicit type conversion (type-casting) 8. double
int a = 3; 7. float
double b = (double)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;
int b = (int)a; int b = (int)a; 2. char
cout << b << endl; cout << b << endl;
1. bool

64
Example
#include <iostream>
using namespace std;
int main() {
char a = ‘A’;
cout << a + 1 << endl;
char b = a + 1;
cout << b << endl;
double x = 1.57 * a;
cout << x << endl;
return 0;
}
65
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, needs to be declared
• Type: C++ is a strictly typed language, variables and constants 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

66
#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

67
#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

68
#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 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;
‘foo’ and ‘main’, respectively
}

69
#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: int main() {
foo();
• Defined a global variable ‘a’
cout << “a in main: ” << a << endl;
• Its accessibility is the entire return 0;
program
}

70
#include <iostream>
Scope using namespace std;
• Scope of a variable/constant int a = 0; .
refers to the region of a program int main() {
where the variable/constant is int a = 1; .
visible (can be accessed)
cout << “a in main: ” << a << endl;
Example V: return 0;
}
• Defined a global variable ‘a’ and
a local variable ‘a’ within ‘main’
• What’s the output of the
program??

71
Define Scope using Namespace
• A scope can be defined in many ways: by {}, functions, classes, and
namespaces

• Namespace is used to explicitly define the scope. A namespace can


ONLY be defined in global or namespace scope.

• The scope operator :: is used to resolve scope for variables of the


same name.

72
#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;
} 73
#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;
} 74
#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;
} 75
Today’s Outline
• C++ basic syntax
• Variable and constant
• Operators
• Basic I/O

76
Operators
• An operator specifies an operation to be performed on some values
• These values are called the operands of the operator

• Some examples: +, -, *, /, %, ++, --, >>, <<

77
Operators
• An operator specifies an operation to be performed on some values
• These values are called the operands of the operator

• Some examples: +, -, *, /, %, ++, --, >>, <<

• Some of these have meanings that depend on the context


• e.g., << means different operations in
cout << a << endl;
int b = a << 1;
78
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;
float b = a – sqrt(a);
char x = ‘a’;

79
Assignment Operator =
• An expression itself has a value, e.g.,
a = (b = 2) + (c = 3);

• An assignment statement has a value equal to the operand


• In the example, the value of assignment statement “b=2” is 2 and “c=3” is 3
• Therefore, “a = …” is 5

80
Assignment Operator =
• An expression itself has a value, e.g.,
a = (b = 2) + (c = 3);

• An assignment statement has a value equal to the operand


• In the example, the value of assignment statement “b=2” is 2 and “c=3” is 3
• Therefore, “a = …” is 5

• = is an assignment operator that is different from the mathematical


equality (which is == in C++)
• More details in the next lecture

81
Examples of Assignment Statements
/* Invalid: left hand side must be a variable */
x + 10 = y;

82
Examples of Assignment Statements
/* Invalid: left hand side must be a variable */
x + 10 = y;
/* Assignment to constant after initialization is not allowed */
const int a = 2;
a = 3;

83
Examples of Assignment Statements
/* Invalid: left hand side must be a variable */
x + 10 = y;
/* Assignment to constant after initialization is not allowed */
const int a = 2;
a = 3;
/* Valid but not easy to understand */
a = (b = 2) + (c = 3);

84
Examples of Assignment Statements
/* Invalid: left hand side must be a variable */
x + 10 = y;
/* Assignment to constant after initialization is not allowed */
const int a = 2;
a = 3;
/* Valid but not easy to understand */
a = (b = 2) + (c = 3);
/* Avoid complex expressions */
b = 2, c = 3;
a = b + c;

85
Swapping 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;
b = a;

86
Swapping Values
• We need to make use of a temporary variable:

int a = 3;
int b = 4;
int c; // a buffer for value swapping

87
Swapping 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

88
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)
89
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;

90
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;
• Post-increment and post-decrement: k++ and k--
• k’s value is altered AFTER the expression is evaluated
e.g., a = k++ is equivalent to (1) a = k, (2) k = k+1
• Pre-increment and pre-decrement: ++k and --k
• k’s value is altered BEFORE the expression is evaluated
e.g., a = ++k is equivalent to (1) k = k+1, (2) a = k

91
Example
#include <iostream>
using namespace std;
int main() {
int x = 3;
cout << ++x; // (1) x = x+1 (2) cout << x
cout << x++; // (1) cout << x (2) x = x+1
cout << x;
return 0;
}

92
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;
}

93
What values are printed?
int a = 0, b = 0;
cout << “b = “ << b << endl;
a = 0;
b = 1+(a++);
cout << “b= “ << b << endl;
cout << “a= “ << a << endl;
a = 0;
b = 1+(++a);
cout << “b= “ << b << endl;
cout << “a= “ << a << endl;

94
a = 0;
b = 1 + (a++);

0
1. Evaluates a++, (value:0)
2. Computes a = a+1
3. b = 1 + 0
=1

95
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

96
What values are printed?
int a = 0, b = 0;
cout << “b = ” << b << endl;
a = 0;
Output:
b = 1+(a++); // (1) b=1+a (2) a=a+1
cout << “b = ” << b << endl; b = 0
cout << “a = ” << a << endl;
b = 1
a = 0; a = 1
b = 1+(++a); // (1) a=a+1 (2) b=1+a
cout << “b = ” << b << endl;
b = 2
cout << “a = ” << a << endl; a = 1

97
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.

• Associativity: order of evaluation for operators with the same precedence


• means whether an expression like x R y R z, where R is an operator,
e.g., x + y + z should be evaluated `left-to-right’ i.e. as (x R y) R z or ‘right-
to-left' i.e. as x R (y R z);

98
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;

• Which of the following interpretation is right?


a = (b++) + c;
or a = b + (++c);

99
Precedence & Associativity of Operators
Operator Precedence (high to low) Associativity
:: None
. -> [] Left to right
() ++(postfix) --(postfix) Left to right
+ - ++(prefix) --(prefix) Right to left
* / % Left to right
+ - Left to right
= += -= *= /= etc. Right to left

100
Precedence & Associativity of Operators
Operator Precedence (high to low) Associativity
:: None
. -> [] Left to right
() ++(postfix) --(postfix) Left to right
+ - ++(prefix) --(prefix) Right to left
* / % Left to right
+ - Left to right
= += -= *= /= etc. Right to left

Example I: a=b+++c
a=(b++)+c; or
a=b+(++c);
101
Precedence & Associativity of Operators
Operator Precedence (high to low) Associativity
:: None
. -> [] Left to right
() ++(postfix) --(postfix) Left to right
+ - ++(prefix) --(prefix) Right to left
* / % Left to right
+ - Left to right
= += -= *= /= etc. Right to left

Example I: a=b+++c Example II: int a, b=1;


a=(b++)+c; or a=b=3+1;
a=b+(++c);
102
Bitwise Operators
• Bitwise AND & • Bitwise OR |
• Compute AND on every bit of • Compute OR on every bit of
two numbers two numbers
• The result of AND is 1 only if • The result of OR is 1 as long
both bits are 1 as one of the bits is 1

short a = 3, b = 5, c = a & b; short a = 3, b = 5, c = a | b;


cout << c << endl; // 1 cout << c << endl; // 7
// a = 00000011 // a = 00000011
// b = 00001001 // b = 00001001
// c = 00000001 // c = 00001011
103
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

short a = 3, b = 5, c = a ^ b; char a = 254; int b = ~a;


cout << c << endl; // 6 cout << b << endl; // 1
// a = 00000011 // a = 11111110
// b = 00001001 // b = 00000001
// c = 00001010
104
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

int a = 3, b = 1;
int c = a << b, d = a >> b;
cout << c << endl; // 6
cout << d << endl; // 1
105
Example I
• What’s the output of the following statements?

char x = 6;

int a = (x >> 1) & 1;


cout << a << endl;

int b = (x >> 3) & 1;


cout << b << endl;

106
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;

107
Today’s Outline
• C++ basic syntax
• Variable and constant
• Operators (and punctuators)
• Basic I/O

108
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

d ata
of
eam
Str

109
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 (<<)

Input Input Stream Output Output


1.72 56 Program 18.9 BMI
Device Object Stream Object Device

cin >> weight


cin >> height
cout << “bmi”
cout <<weight/height/height

110
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 Stream Output


Program 18.9 18.9
Object Device

Output Output
Program 18.9 Manipulator 18.90 18.90
Stream Object Device

111
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 Stream Output


Program 18.9 18.9
Object Device

Output Output
Program 18.9 Manipulator 18.90 18.90
Stream Object Device

112
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

Approach Example Output (w: space key)


1. cout.width(width) cout.width(5); //or cout << setw(5);
cout << 123 << endl; ww123
2. setw(width) cout << 123 << endl; 123

cout << setw(5); //or cout.width(5);


cout << 1234567 << endl; 1234567
cout: Floating-Point Precision and
Format
• You can control the precision and format of floating point print
• Must #include <iomanip>
• Floating-point precision is 6 digits by default
• Use fixed, scientific and setprecision manipulators to change the
precision value and printing format
• Effect is permanent

115
cout: Floating-Point Precision and
Format
• Default precision (6 digits, 5 digits after decimal points) and format

Example Default output


cout << 1.23 << endl; 1.23
cout << 1.230 << endl; 1.23
cout << 1.2345678 << endl; 1.23457
cout << 0.000012345678 << endl; 1.23457e-05

116
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)

Example Default output After cout << fixed;


cout << 1.23 << endl; 1.23 1.230000
cout << 1.230 << endl; 1.23 1.230000
cout << 1.2345678 << endl; 1.23457 1.234568
cout << 0.000012345678 << endl; 1.23457e-05 0.000012

117
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)
• 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

118
cout: Floating-Point Precision and
Format
• Normally, setprecision(n) means output n significant digits

Example Output
cout << setprecision(2);
cout << 1.234 << endl; 1.2
cout << 0.0000001234 << endl; 1.2e-07

119
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
120
cout: Other Manipulators
Manipulators Example Output
fill cout << setfill(‘*’);
cout << setw(10);
cout << 5.6 << endl; *******5.6
cout << setw(10);
cout << 57.68 << endl; *****57.68
cout: Other Manipulators
Manipulators Example Output
fill cout << setfill(‘*’);
cout << setw(10);
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
cout: Other Manipulators
Manipulators Example Output
fill cout << setfill(‘*’);
cout << setw(10);
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

alignment cout << setiosflags(ios::left);


cout << setw(10);
cout << 5.6 << endl; 5.6
cin: Input Operator (>>)
• Preprogrammed for all standard C++ data types
• Get bytes from an input stream object
• Depend on white space to separate incoming data values

Input Input Stream


1.72 56 Program
Device Object

cin >> weight


cin >> height

124
cin: Input Operator (>>)

125
cin: Input Operator (>>)

126
cin: Input Operator (>>)

127
Summary
• C++ basic syntax
• Variable and constant
• Operators
• Basic I/O

128
Summary: Variable & Constant
• Address
• Value: representation and integer encoding
• Name: naming & declaration rules
• Type: range (overflow/underflow issues) and type conversion
• Scope

129
Summary: Operator
• =: efficient assignment, swapping values

• ++ and --: post and pre

• Operator precedence & associativity

130
Summary: Basic I/O
• cout:
• print numbers with controlled width, precision, and format

• cin:
• read (multiple) user input of different types

131

You might also like