CS2311-Lec02-basic
CS2311-Lec02-basic
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
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++ 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 ; .
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
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;
}
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
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
25
Decimal vs Binary
26
Decimal vs Binary
28
Hexadecimal
• Express 0 to 15 as:
0123456789abcdef
29
Hexadecimal to Decimal
30
Hexadecimal to Decimal
32
Decimal, Binary and Hex
Representations
• In C++, you can represent a value in either decimal, binary, or 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
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
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
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;
49
char
• Used to store a single character, enclosed by the single quotation mark
char c = ‘a’;
char c = ‘\n’;
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 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)
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
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
77
Operators
• An operator specifies an operation to be performed on some values
• These values are called the operands of the operator
79
Assignment Operator =
• An expression itself has a value, e.g.,
a = (b = 2) + (c = 3);
80
Assignment Operator =
• An expression itself has a value, e.g.,
a = (b = 2) + (c = 3);
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.
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;
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
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;
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 (<<)
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 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 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
115
cout: Floating-Point Precision and
Format
• Default precision (6 digits, 5 digits after decimal points) and format
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)
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
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
130
Summary: Basic I/O
• cout:
• print numbers with controlled width, precision, and format
• cin:
• read (multiple) user input of different types
131