0% found this document useful (0 votes)
33 views83 pages

CS2311 Lec02 Basic

This document provides an overview of basic concepts in C++ programming including data types, operators, and input/output. It first reviews what a computer system consists of including the CPU, main memory, external storage, and input/output devices. It then discusses what a computer program is in terms of instructions and data. Programming languages like machine language, assembly language, and high-level languages are also introduced. The document proceeds to cover basic C++ syntax including tokens, keywords, identifiers, and variable declaration. It concludes by outlining the topics to be covered in the lecture including variables and constants, operators, and basic input/output.

Uploaded by

Hello HK World
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views83 pages

CS2311 Lec02 Basic

This document provides an overview of basic concepts in C++ programming including data types, operators, and input/output. It first reviews what a computer system consists of including the CPU, main memory, external storage, and input/output devices. It then discusses what a computer program is in terms of instructions and data. Programming languages like machine language, assembly language, and high-level languages are also introduced. The document proceeds to cover basic C++ syntax including tokens, keywords, identifiers, and variable declaration. It concludes by outlining the topics to be covered in the lecture including variables and constants, operators, and basic input/output.

Uploaded by

Hello HK World
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

CS2311 Computer Programming

LT02: Data, Operators, and BasicIO

Computer Science, City University of Hong Kong


Semester A 2022-23
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
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

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? */
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++ 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 ; .
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;

Types of keywords area = 3.1415926 * r * r;


cout << “area is ” << area << endl;
Data type return 0;
Flow control }.

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

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

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++ proggram


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

Explain the difference of variable and 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

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

• 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 Please refer
to the output of num2 th next page 33
Example
#include <iostream>
using namespace std;
int main() {
int num1 = 2147483647;
int num2 = num1 + 1;
cout << num2 << endl;
return 0;
} Remark Due to overflow issue num 2 2 s Anant
hum2 10000000 00000000 00000000
00000000
Try to modify num2 numtl and see 34
I

short, long and unsigned


• long is used for large integers (8 bytes) 64 bit f bit for I byte
• short is used for small integers (2 bytes)
• For example: short minute_of_day;
• unsigned is used to declare that the integer data type is non-negative
• For example
unsigned short a;
unsigned long b;
unsigned int c;
• unsigned integers has no sign bit
• i.e., the range of unsigned int is 0 to 232-1

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)

float pig_weight = 280.3, boat_load = 615.2;


int n_pig = boat_load/pig_weight;
the ou put will
int float be an integer
only float changeto45
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

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 ;

• Constants can be any data type we just studied, e.g.,


const double light_speed = 299792.458; // km per second
const int days_per_week = 7;
const char[] my_email = “[email protected]”;

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
}

a 0 th the whole program as a is


a global variable 56
#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??

Precedence local variable global variable 57


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.

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

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

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

• 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++)
for proving whether
• Introduced in detail in the next lecture
something to equals
to something
only
67
Examples of Assignment Statements
/* Invalid: left hand side must be a variable */
x + 10 = y;
/* Assignment to constant 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;

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;

• 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

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.

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

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;

• Which of the following interpretation is right?


a = (b++) + c;
or 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

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


a=(b++)+c; or a=b=3+1;
a=b+(++c);
88
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 QQ D 8111 9 0011 6 0101

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

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


cout << c << endl; // 2 cout << b << endl; // 1

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

int a = 3, b = 1; 00117 I 20001


int c = a << b, d = a >> b;
cout << c << endl; // 6 001141 0110
cout << d << endl; // 1

91
Example I
• What’s the output of the following statements?

char x = 6; // 0000 1010

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


cout << a << endl;

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


cout << b << endl;

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

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

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


Program 18.9 18.9
Object Device

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

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

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

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

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

You might also like