Computer Programming
LT2: Language Syntax, Variable and Basic I/O
Computer Program
A program is somewhat similar to the recipes used in cooking!
conditional repetition
if (i<0) cout<<“Negative”;
Logic Flow while (i>0) { x=x+i; i--; }
Flip the egg if it is browned Keep stirring until dissolved
Computer
Program
Instructions Data
Add / Sub… Mix / Heat… Variables ? Ingredients ?
2 Data Size ? Volume ?
Outlines
C++ Language Syntax
Constant and Variable Declaration
Data types (integers, real numbers, true/false, string…)
Operators (e.g. + - * / %)
cin and cout from <iostream> library
3
Outcomes
Describe the basic syntax and data types of C++ language.
Explain the concepts of constant, variable 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 formats.
Able to read value from keyboard and assign to variable.
4
Syntax of C++
Like real-life languages, C++ has grammatical rules for
putting together words and punctuation to make legal
program; that is called syntax of the language
C++ compilers detect any violation of the syntactic rule
within the program
In C++, vocabularies (keywords) are separated by space
and punctuations
Most C++ commands end with semi-colon ;
5
Template (just like “to whom this may concern” in English)
#include <iostream> Important!: no semi-colon here
using namespace std;
int main(){
/* Place your code here! */
return 0;
}
6
Syntax - Tokens
Tokens in C++ can be categorized into:
keywords, e.g., return, int, float, double…etc.
identifiers, e.g., user-defined names for variable/functions…
data constants, e.g., (string) “Hello”, (number) 123…etc.
operators, e.g., + - * / %
punctuations, e.g., ; and ,
7
Keywords
8
Keywords (reserved words)
-covered in this course-
Data type char double float int bool
long short signed unsigned void
Flow control if else switch case
break default for do
while 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
9
Keywords (cont’d)
Each keyword in C++ has a reserved meaning.
When a programmer needs to give name to variables or
functions, the name should NOT be the same as those
reserved keywords.
Just like in English… If you give yourself a name “Happy”,
then the meaning of “I am Happy” would be ambiguous.
Most of the keywords given in the previous page will be
covered in this course; No need to be hurry in memorizing
them all NOW, you’ll learn them over weeks
The list in last page is partial, some keywords are
deliberately omitted
10
Identifiers
Identifiers are unique names given to various items in a program, like
functions (command block) and variable (data storage)
Similar to keywords, identifiers are also case sensitive
(i.e. SALARY and Salary are considered different)
As mentioned in the previous page, reserved keywords like float and
int cannot be used as identifiers
An identifier is composed of a sequence of letters, digits and
underscore (e.g. myRecord, point3D, last_file…)
Avoid foreign characters (Chinese/Japanese…etc)
11
To get a good name…
Variable names in C++ are case sensitive
(so abc, ABC, Abc are three different and unrelated variables)
It may contains alphabet (a-z A-Z), digits (0-9), underscore ( _ ),
but… NO SPACE, NO HYPHEN !
(finalResult, final_result and result0_9 are ok, but final result is not!)
First character must be non-digit (i.e. not 0-9)
(result_1A is ok, but 1A_result is not!)
The Rule is: assign a name which is self-explanatory & just enough!
Names like x, y, z are too simple to understand what they’re for
(it is considered worldwide that it’s a bad programming habit,
some lecturers deduce mark for that!)
A name like total_sales_in_year_2020_to_2021 is self-explanatory…but..
What is a variable?
Variable is a named place to store information. It is similar to the
unknowns (e.g. x) in your Math lessons, but…
Variables could have longer names (e.g. finalResult )
could change value as program runs (at first it was 1, but then it became 10)
could store something other than number (e.g. user name, address...etc)
To create a variable, write:
<type> <name>; (e.g. int a; ) or
<type> <name> = <value>; (e.g. int a = 5; )
Note, however, that variable is NOT the unknowns in Math…
You may write cout<<-a; (which gives -5), but writing cout<<2a; is WRONG!
The equal sign (=) means ASSIGN (i.e. copy value from right to left),
but not EQUALITY, therefore writing 5 = a; is WRONG!
IMPORTANT: Don’t quote the variables. cout<<“a”; will show just the a
character, but not the internal value 5
Declaration - Variable
Variable and constant must be declared before use.
Declaration actually asks compiler to reserve memory space for you.
Examples:
int age ;
float volume ;
char initial ;
char student_name[30];
Optionally, the initial value of a variable can be set with declaration.
int age=18;
float volume=15.4;
Do NOT try to read from a variable before its value is set!
Declarations could be written in:
Beginning of program, outside all functions (i.e. outside main() {..} )
Beginning of a function (i.e. inside the { } of main )
14
Declaration – Global vs. Local
Variables actually have life-span. There are restrictions on
when and where it could be read…
Scope of a variable refers to the accessibility of a variable:
Two major types: Global vs. Local
Global variable
A variable defined in the global declaration sections of a
program, i.e. defined outside functions.
can be accessed anywhere by all functions
Local variable
Declare in a block and can be only accessed within the block.
Try to access a local variable outside the block will produce
error.
15
Declaration – Variable (Local)
#include <iostream> 2 The variables could be read / written
using namespace std; from here… (open brackets)
int main() {
1
int number1=12; We consider the variables local as they’re
int number2=3; enclosed by the brackets { } of main
int result;
result=number1+number2;
3 Up to here… (close brackets)
return 0;
}
4 If you put cout<<result; here, after
the brackets { }, it is syntax error and
16 Visual Studio won’t compile your code!
Declaration – Variable (Global)
#include <iostream>
1
using namespace std;
We consider the variables global as they
are NOT enclosed by the brackets { }
int number1=12;
int number2=3;
2
int main(){ Global variables could also be accessed
inside functions (like main() ), as
int result; long as their names are different from
that of local variables!
result=number1+number2;
(FYI: If their name crash with the local
vars, then you always read the local vars,
global vars will be inaccessible)
return 0;
}
3 Of course, number1 can also be accessed
17 after here ! (by some other functions) since it
does not belongs to main()
Scope of function variables
(We’ll re-visit the detail syntax of function in later weeks…)
int number1=12;
int number2=3; x and y are alive only in function
min(), between the brackets { }
int min( int x , int y ){
if (x>y){
return y;
}else{
return x;
}
}
x and y not accessible
int main(){ outside brackets { }
int result;
result=min(number1,number2);
return 0;
} main() could not read x and y
as well since they’re dead after
the execution of function
18
C++ Predefined Data type
Numerical
Integer (+/- number without decimal place)- 1, -999, 123456
int (most common)
short, long, unsigned (less common)
Floating point (+/- num wit dot, or scientific notation) – 0.25, 3.01e-5
double (more accurate), float (less accurate)
Character – ‘a’, ‘e’, ‘o’, ‘\n’
char (actually char can be used to store small integer (rare))
Boolean – true, false
bool
19
Constants (i.e. give the value directly)
Constants can be numeric-, character- or string-based, e.g.,
13, 7.11, ‘\n’, “Tuesday”
Numbers are represented in decimal system. Although NOT
COMMON, but octal (base-8)(preceded by 0) or hexadecimal
(base-16) integers (preceded by 0x) are also possible.
e.g., the following number are equal to a decimal 26
032 /* octal integer, Important ! It is not 32 (thirty two) */
0x1a /* hexadecimal integer */
Character constant is enclosed by single quotation marks,
e.g., ‘a’, ‘\n’, ‘\t’
20
Declaration – Named constants
Allow us to give a name to special value. (easier to understand..)
Value MUST be given at the same time it is declared
Value could not be changed further
Format:
const Data_type variable/constant identifier = value;
Examples:
const float pi=3.14159;
const int maxValue=500;
const char initial=‘D’; If you later write maxValue=1;
const char student [] =”Amy Li”; or cin>>maxValue; it will be
syntax error and Visual Studio
21 will not compile your code!
About 2*109, not
as large as you
Data type int think !
Typically, an int is stored in four bytes (or 32bits, as 1 byte = 8 bits).
64bit CPU uses 8 bytes. It may be some other sizes in future CPUs
The length of an int data type restricts the range of number it can
store. A 32-bit int can store numbers in the range of -231 to 231 -1
(i.e. -2147483648 to +2147483647)
We can optionally put the unsigned keyword before int, by doing so
we will give up the negative range and double the positive range
e.g. When we write: unsigned int x; x has range 0 to 232 -1
When an int is assigned a value greater than its maximum bound,
overflow occurs and this ends up with incorrect result
Note: C++ does not inform you that overflow error occurred!
(Let’s try cout << 90000 * 90000;)
22
The floating types
float, double and long double are floating point types.
(i.e. numbers with decimal point or in scientific notation)
Numeric constants with decimal point (e.g. 3.14) by default is
in double type (not float !)
Scientific notation is also acceptable, e.g., 1.23e3 and 3.367e-4
(means 1.23*103 and 3.367*10-4 respectively)
A constant is considered floating point if dot or exponent exist!
(e.g. 1000.0 and 1e3 are floating point, while 1000 is integer)
23
Characters & data type char
In C++, a char takes one byte or 8 bits of memory to store.
Although char is considered as character, but just like other variables,
it’s just a sequence of binary 0 & 1 in memory
(i.e. can also be considered as binary NUMBER)
e.g. char x = ‘a’; is (of course) OK
char y = ‘A’ + 1; is also OK! (y will store ‘B’)
char z = 97; is also OK! (z will store ‘a’) (see next page !)
The relationship (mapping) of the character against the binary number
is listed in the ASCII table (It is international standard used by major PCs!).
Therefore if you write int w = x; w will store 97 !
Conclusion: char and small integers are interchangeable!
24
ASCII Code
25
Conversions
cout automatically detects data type and prints accordingly
char x = ‘A’; int y=x;
cout<<x; shows ‘A’ (as character) but cout<<y; shows 65
(as integer) despite that both are storing the same number!
If explicit conversion is need, you may use type casting, by
putting the type name in parenthesis:
cout<<(char)y; now shows ‘A’ (as character)
Note that casting may cause data loss
E.g. double a = (int)3.14; a will be 3 (fractions removed!)
26
Operators and punctuations
Punctuations are used to separate language elements:
Semi-colon ; is used to signal the end of a statement
int a; int b=5; cout<<“Hello”;
Comma , is used to join up statements, like:
int a, b = 5; (same effect as 2 statements, note int is written once)
Single quotation marks ’ are used to enclose character (length=1)
char grade=’A’;
Double quotation marks ” are used to enclose string
(length can be 0, 1, or even up to millions)
char name[]=”Kenneth”;
27
Operators and punctuations
Operator is referred to the symbol placed between numbers
(variable / constant) when performing calculation (e.g. + - * /)
Binary operators (work with TWO values, one in front, one after)
Addition: + Subtraction: - Multiply: * Divide: / Modulus: %
e.g. Ans = 5 * y; (5 is before *, y is after *)
Similar to Math definitions, + - is having lower precedence than * / %
% is Modulus, but NOT percentage! It returns the integer remainder after
division. (e.g. 10 % 3 is 1, as the remainder of 10 divide by 3 is 1)
IMPORTANT: If both dividend and divisor are integers, the result (quotient)
is always integer! (e.g. 9/2 gives 4 (integer) but not 4.5)
Besides operators for calculation, there’re also operators for some other
operations like input/output
E.g. cin>>hour; cout<<“Hi”; Those >> and << are also operators
28
Operators and punctuations
Unary operators (work with ONE value)
Negation -
e.g. int x = 5; int y = -x; (y is having a value of -5)
Besides the – operator, C++ also defines: ++ and --
Which applies only to integers
++ is increment by one.
k++ and ++k are equivalent to k=k+1 (increase the value by 1)
-- is decrement by one.
k-- and - -k are equivalent to k=k-1 (decrease the value by 1)
29
Increment & decrement operators
++ and - - are special. Unlike addition (+):
It cannot be applied to constant. (e.g. ++5 is wrong!)
It can be placed before (++x) or after (x++) a variable.
Difference between writing in front / after ?
Post-increment and post-decrement: k++ and k--
k’s value is altered AFTER the expression is evaluated
int k=1, j;
j=k++; /* result: j==1, k==2 */
Pre-increment and pre-decrement: ++k and --k
k’s value is altered BEFORE evaluating the evaluation
int k=1, j;
j=++k; /* result: j==2, k==2 */
30
Self Test 1
What is the output of the following program?
(let’s verify with Visual Studio)
int x=3;
cout<< x;
cout<< ++x;
cout<< x;
cout<< x++;
cout<< x;
31
Self Test: Solution
Old x New x Output
int x=3; 3 3 --
cout<< x; 3 3 3
cout<< ++x; 3 4 4
cout<< x; 4 4 4
cout<< x++; 4 5 4
cout<< x; 5 5 5
32
Self Test 2
What is the output of the following program?
(let’s verify with Visual Studio)
int a=0,i=0;
cout<<"i="<<i<<endl;
a=0;
i=1+(a++);
cout<<"i="<<i<<endl;
cout<<"a="<<a<<endl;
a=0;
i=1+(++a);
cout<<"i="<<i<<endl;
cout<<"a="<<a<<endl;
33
Self Test 2: Solution
int a=0,i=0;
cout<<"i="<<i<<endl;
a=0;
i=1+(a++); Output
cout<<"i="<<i<<endl;
i=0
cout<<"a="<<a<<endl;
i=1
a=1
a=0;
i=2
i=1+(++a);
cout<<"i="<<i<<endl;
a=1
cout<<"a="<<a<<endl;
34
Precedence & associativity of operators
an expression may have more than one operator and its precise
meaning depends on the precedence and associativity of the
involved operators
Example: In 1+2*3, multiplication is done first, we say that the
precedence of * is higher than that the precedence of +
Difficult & Ambiguous case:
What is the value of variables a, b and c after the execution of the
following statements ?
int a, b = 2, c = 1;
a = b+++c;
Which of the following interpretation is correct?
a = (b++) + c; /* correct */
or a = b + (++c); /* wrong */
35
Precedence & associativity of operators
Operator Precedence (high to low) Associativity
:: None
. -> [] Left to right
() ++(postfix) --(postfix) Left to right
+(unary) -(unary) ++ (prefix) -- (prefix) Right to left
* / % Left to right
+ - Left to right
= += -= *= /= etc. Right to left
Precedence: order of evaluation for different operators.
Associativity: order of evaluation for operators with the same precedence
Conclusion: Use parenthesis ( ) if you’re not sure,
no need to get yourself into trouble!
36
Use of parenthesis
You may use parenthesis ( ) to force the evaluation order
E.g. In 2*(3+4), + (in parenthesis) is evaluated before *
You may use as many ( ) as you want: e.g. ((2)*((3)+(4)))
Regardless of the number of levels, we use only ( )
Writing {[(1+2)*3]/4}-5 is WRONG!
It should be (((1+2)*3)/4)-5 as [ ] and { } have special meanings
Parenthesis in functions e.g. int main( ) and if ( ) clause
e.g. if (mark>30) cout<<“Pass”; and loops e.g. while (i>0).. have
special meanings, they are NOT optional and cannot be omitted.
Assignment operators (=)
Generic form
variable = expression;
Note that = is assignment, not equality
The meaning of a=5 is
Get the value 5 (right-hand-side) and PUT IT into a (left).
It does NOT mean: a is equals to 5
Therefore writing 5=a is WRONG ! (why?)
Advanced Use:
An expression itself has a value, e.g.,
a = (b = 32) + (c = 23);
Treated as 32 Treated as 23, so a=32+23; i.e. 55
38
Examples on assignment statements
/* Invalid: left hand side must be a variable */
a + 10 = b;
/*assignment to constant is not allowed*/
2=c;
/* valid but not easy to understand */
int a, b, c;
a = (b = 2) + (c = 3);
/* suggested: avoid using complex expressions*/
int a, b, c;
b = 2;
c = 3;
a=b+c
39
Swapping the values
If we want to swap the content of two variables, a
and b.
What's the problem for the following program?
int main(){
int a=3, b=4;
a=b;
b=a;
return 0;
}
40
Swapping the values
We need to make use of a temporary variable
c=b; /*save the old value of b*/
a b c a b c
b=a; /*put the value of a into b*/
a b c a b c
a=c; /*put the old value of b to a*/
a b c a b c
41
Assignment operators (continued)
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);
a *= b+c; is the same as a = a * (b+c);
= is an assignment operator that has nothing to do with
mathematical equality (which is == in C++)
42
Basic I/O – Keyboard and Screen
A program can do little if it can’t take input and
produce output
Most programs read user input from keyboard and
secondary storage
After process the inputted data, result is commonly
display on screen or write to secondary storage
43
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 extraction operator (>>) and insertion operator (<<)
44
cout: Insertion Operator (<<)
Preprogrammed for all standard C++ data types
It sends data to an output stream object, e.g. cout
Data printed immediately appends the previous content
it’s not printing on new line unless otherwise specified
To print new line (i.e. <Enter>)
cout<< “\n”; (need quotation mark) or
cout<<endl; (no quotation mark) both are identical.
Predefined “manipulators” can be used to change the
default format of argument
E.g. change the number of decimal places to be printed
45 E.g. change the field width or the alignment of output
cout: Insertion 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;
46
cout – Change the Width of Output
Must #include <iomanip>
Change the width of output
Calling member function width( ) or using setw( ) manipulator
Leading blanks are added to output with shorter length
(Hence data is aligned to the right)
If formatted output exceeds the width, the entire value is printed
Effect last for one field only
Approach Example Output
[Link](width) [Link](10); 5.6
cout << 5.6 << endl; 57.68
[Link](10);
cout <<57.68 << endl;
setw(width) cout << setw(5) << 1.8; 1.823
cout << setw(5) << 23 <<endl; 6.711
cout << setw(5) << 6.71;
47 cout << setw(5) << 1 <<endl;
cout – Set the Precision and format of
floating point Output
Must #include <iomanip>
Floating-point precision is at most six by default
Use setprecision, fixed and scientific manipulators to change the precision value and
printing format.
Effect is permanent until being changed again
It applies to floating point output (e.g. cout<<123.0;) but it does not affect Integer
output (e.g. cout<<123;)
Example Output
cout << setprecision(2); 1
cout << 1 <<endl; 1.3
cout << 1.3 <<endl; 1.3
cout << 1.34 <<endl; 1.3e-008
cout << 0.0000000134 << endl; 0.00
cout <<fixed; 5.00e-004
cout << 0.0000000134 << endl;
48 cout << scientific << 0.0005 << endl;
cout – Set the Precision and format of
floating point Output
By default (without setprecision), C++ prints the field in the shortest form
e.g. It prints 1.2 instead of 1.20
For very small num, it switches to scientific notation without asking you!
Use setprecision() alone (without fixed or scientific) forces the number of
significant figures, NOT decimal places.
For example, setprecision(2) << 1.234 keeps only 1.2
For example, setprecision(2) << 1234.0 changes to 1.2e+003
fixed forces the use of [Link] format, regardless how small the number is
scientific forces the use of scientific notation
If fixed or scientific is used, the number in setprecision() is consider as
decimal places, NOT significant figures.
For example, setprecision(2)<<fixed<< 1.234 is 1.23 (not 1.2 as above)
For example, setprecision(2)<<scientific<< 1234.0 is 1.23e+003
49
cout – Other Manipulators
Manipulators Example Output
fill cout << setfill(‘*’); *******5.6
cout << setw(10); *****57.68
cout << 5.6 << endl;
cout << setw(10);
cout <<57.68 << endl;
radix cout << oct << 11 << endl; 13
cout << hex << 11 << endl; b
cout << dec << 11 << endl; 11
alignment cout << setiosflags(ios::left); 5.6*
cout << setw(10);
cout << 5.6 <<‘*’;
50
cin: Extraction Operators (>>)
Preprogrammed for all standard C++ data types
Get data from an input stream object
Depend on white spaces to separate incoming data values
“White spaces” also includes <Enter> and <Tab>
cin by default skips over those white spaces
For Example, when running cin>>x;
User press <Enter><Enter>, followed by <space>5<Enter>
x will be 5, all <Enter>s and <space>s in front are skipped.
Therefore, if you’d like to input a string with internal spaces
(e.g. user name), you cannot use cin>> but rather you use
[Link](); (will be mentioned later)
51
Extraction Operator
Type Variable Expression Input x y
Integer int x,y; cin >> x; 21 21
cin >> x >> y; 5 3 5 3
Float float x,y; cin >> x; 14.5 14.5
Character char x,y; cin >> x; a a
cin >> x >> y; Hi H i
String char x[20]; cin >> x; hello hello
char y[20];
cin >> x >> y Hello World Hello World
If user input less than required, cin waits for further input
If user input more than required, those excess data will be used
52 for future cin request (i.e. not waiting for user to input next time)
Programming styles
Programmers should write code that is
understandable to other programmers as well
Meaningful variable names
Which one is more meaningful ?
c=a*b;
tax=price*tax_rate;
Meaningful Comments
Write comments as you're writing the program
Indentation (i.e. shift content inward to the right)
53
Programming styles
At the top of the program
Include information such as the name of organization,
programmer’s name, date and the purpose of program
What is achieved by the function, the meaning of the
arguments and the return value of the function
Short comments should occur to the right of the statements
when the effect of the statement is not obvious and you want
to illuminate what the program is doing
Programming Style (indentation, comments, variable names…etc)
is also assessed in the assignment.
54
Appendix: sizeof operator
Depending on the compiler, the amount of memory used
by int and other type may differs. (e.g. in Turbo C, int is 16
bits, in Visual Studio, int is 32 bits)
sizeof can be used to find the number of bytes needed to
store data variable e.g.,
int len1, len2;
float x;
len1 = sizeof(int); //4 in 32-bit system
len2 = sizeof(x); //4 bytes
sizeof is usually used in file read/write, memory block copy
/ allocation…etc. We do not use it frequently in our course.
55
Summary
Most computer programs access data during its execution. Data are
stored in main memory as variable and constant
Variables and constant are referred by their identify.
In C++, variable and constant must be typed.
The place when variable/constant is defined determined its scope
and hence determined its accessibility.
Variable is updated by operators.
cin and cout are objects defined in <iostream>. They represent the
keyboard and screen display respectively.
program uses
extraction operator >> to read input from cin
Insertion operator << to write output to cout
Manipulator can be added to cout for output formatting
(need #include <iomanip> )
56