LT2: Language Syntax, Variable and Basic I/O
Computer Programming
Computer Program
2
Logic Flow
Computer
Program
Instructions Data
A program is somewhat similar to the recipes used in cooking!
Ingredients ?
Volume ?
Variables ?
Data Size ?
Add / Sub… Mix / Heat…
if (i<0) cout<<“Negative”; Flip the egg if it is browned conditional while (i>0) { x=x+i; i–; }
Keep stirring until dissolved
repetition
check
something
I
a
While week 5
week2
Outlines
3
! C++ Language Syntax
! Constant and Variable Declaration
! Data types (integers, real numbers, true/false, string…)
! Operators (e.g. + – * / %)
! cin and cout from
operators
X 3
operators
4
operand operand operand
int float
4
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.
Syntax of C++
5
! 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 ;
Template (just like “to whom this may concern” in English)
6
#include
using namespace std;
int main(){
return 0;
}
/* Place your code here! */
Important!: no semi-colon here
Syntax – Tokens
7
! 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 ,
I
string constants
operand
constant
variable is not unknown I
Xt1 4
ft shxt le update constant
I
no
Keywords
8
it
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)
10
! 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
11
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)
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..
K treater as I i
IIA result is ok
hard to know it Y Z
too long
! 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:
!
! 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
What is a variable? Data int mustint
FEETello t ERR
ta
Declaration - Variable
14
! 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 )
havactor
15
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.
Declaration – Variable (Local)
16
#include
using namespace std;
int main() {
int number1=12;
int number2=3;
int result;
result=number1+number2;
return 0;
}
We consider the variables local as they’re
enclosed by the brackets { } of main
1
2
The variables could be read / written
from here… (open brackets)
Up to here… (close brackets)3
4
If you put cout<
using namespace std;
int number1=12;
int number2=3;
int main(){
int result;
result=number1+number2;
return 0;
}
We consider the variables global as they
are NOT enclosed by the brackets { }
1
Global variables could also be accessed
inside functions (like main() ), as
long as their names are different from
that of local variables!
(FYI: If their name crash with the local
vars, then you always read the local vars,
global vars will be inaccessible)
2
3 Of course, number1 can also be accessed
after here ! (by some other functions) since it
does not belongs to main()
usually avoid global variable
18
Scope of function variables
int number1=12;
int number2=3;
int min( int x , int y ){
if (x>y){
return y;
}else{
return x;
}
}
int main(){
int result;
result=min(number1,number2);
return 0;
}
x and y are alive only in function
min(), between the brackets { }
x and y not accessible
outside brackets { }
main() could not read x and y
as well since they’re dead after
the execution of function
(We’ll re-visit the detail syntax of function in later weeks…)
19
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
Account balance X
20
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’
21
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’;
! const char student [] =”Amy Li”;
If you later write maxValue=1;
or cin>>maxValue; it will be
syntax error and Visual Studio
will not compile your code!
Data type int
About 2*109, not
as large as you
think !
22
! 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;)
same
withdy
easy
maintain
us int
23
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)
32bits 64 double size 80
a
1 103 1000 If EYEcont R
default big fig
24
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!
25
ASCII Code
26
Conversions
! cout automatically detects data type and prints accordingly
! char x = ‘A’; int y=x;
! cout<
() ++(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!
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.
38
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
FEE xt5
xÉ m x
39
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
40
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;
}
41
Swapping the values
! We need to make use of a temporary variable
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*/
a b c
a b c
a b c
a b c
a b c
a b c
42
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++)
Basic I/O – Keyboard and Screen
43
! 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
Basic I/O – cin and cout
44
! 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 (<<)
cout: Insertion Operator (<<)
45
! 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.
! cout<< “\n”; (need quotation mark) or
! cout<
! 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
cout.width(width) cout.width(10);
cout << 5.6 << endl;
cout.width(10);
cout <<57.68 << endl;
5.6
57.68
setw(width) cout << setw(5) << 1.8;
cout << setw(5) << 23 <
! 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);
cout << 1 <
51
! 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
! cin by default skips over those white spaces
! For Example, when running cin>>x;
! User press
! x will be 5, all
! Therefore, if you’d like to input a string with internal spaces
(e.g. user name), you cannot use cin>> but rather you use
cin.getline(); (will be mentioned later)
Extraction Operator
52
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];
char y[20];
cin >> x; hello hello
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
for future cin request (i.e. not waiting for user to input next time)
53
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)
54
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.
55
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.
56
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
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