FP - Topic 2 - Types, Operators and Expressions
FP - Topic 2 - Types, Operators and Expressions
Fundamentals of Programming
Rev.240901
HCM City 1
Content
• Variable
– Concepts
– Declare and use variables
– Constant
• Datatypes
• Expression
• Statement
• Library
2
Variable
3
Variable
• A variable is a storage location in memory
that holds data during program execution
– The data is stored in a specific location in the
computer's memory.
– To access this data, we use a variable name,
which acts as a reference or alias to the memory
address where the data is stored.
4
Characteristics of variables
• A variable needs a name to identify it.
• It must point to a specific memory address.
• In some languages, a variable needs a data
type. Why?
– Each data type has its own implementation.
– Ex: +, -, *, / work with numbers but not characters.
5
Why is it called "variable"?
• Because:
– You can access and change its value.
7
Variable name
• Variable name is called an identifier.
– Example: int x;
– Here, the variable with the identity "x" may hold the value
12.
• In some languages or contexts, a variable can
have multiple identifiers (aliases).
– E.g. x as new_name
8
Name variables
• Depending on the programming language,
variable naming is limited by a number of rules.
• For C/C++:
– Variable names using characters and numbers: A-Z,
a-z, 0-9, _
– Variable name must start by character ("_" sign is
also considered character)
– Variable names must not match reserved
words/language keywords. For example: if, while,
int, ...
– Variable names are case sensitive. For example:
myname is different from Myname.
9
The art of naming variables
• Programs can have many variables, so naming
impacts code readability and maintainability.
10
The art of naming variables
• Programs can have many variables, so naming
impacts code readability and maintainability.
11
The art of naming variables
• Some basic rules:
– A variable name should be
descriptive of its role or value.
– Names should be short, easy
to read, remember, and not
ambiguous.
– Use naming conventions for
consistency in groups of
variables.
▪ E.g: use _ to denote system
variables, or lowercase for
regular variables, etc.
– ...
12
Contain data in variables
• When declaring variables, what is the value of the
variable?
E.g.: int x; // x = ???
– Depending on the language and data type, variables may
be assigned default values such as null, 0, empty strings, or
even "garbage" (uninitialized memory values).
– To avoid unpredictable values, we use the "=" operator to
explicitly assign a value.
13
Contain data in variables
• When containing data, keep in mind:
– Assign values that match the variable's data type.
– In some languages, automatic type casting may
occur, but it's important to avoid mismatched types.
• E.g.
char* fullName = 1084; //incorrect: assigning a number to a
string pointer.
int age = “Twenty six”; //incorrect: assigning a string to an
integer variable.
double price = 9; // Ok. Automatically cast from int to double (9
becomes 9.0).
14
Variable scope
• Variable scope determines the area in the program
where a variable can be accessed.
15
Variable scope
16
Variable scope
• There are two main types of scope:
– Global variable: accessible throughout the entire program.
– Local variable: accessible only within the block or function
where it is declared.
• In some contexts, variable scope can also refer to
the lifetime or extent of the variable, meaning how
long the variable exists in memory.
17
Variable scope
18
Variable scope
int x = 3;
void main()
{
int y = 2;
x = x + 2;
int sum1 = x+y;
int x = 10;
int sum2 = x+y;
}
Let give the value of the sum1 and sum2 variables after
running the program.
19
Constant
Syntax
<Data Type> <name> = <value>;
Normal
Constant
For example
int a = 1506; // 150610
int b = 01506; // 15068
int c = 0x1506; // 150616 (0x or 0X)
float d = 15.06e-3; // 15.06*10-3 (e or E)
20
Constant
Syntax
#define <const_name> <value>
Constant Or use const keyword.
Example
#define MAX 100 // Without ;
#define PI 3.14 // Without ;
const int MAX = 100;
const float PI = 3.14;
21
Constant
• Macro Constants (using #define)
– Properties:
▪ Substituted by the preprocessor before compilation.
▪ No type checking during compilation.
▪ No scope limitations (applies throughout the program).
• Constant Variables (using const)
– Properties:
▪ Type checking during compilation.
▪ Scope is limited to the block where it is declared.
▪ Memory allocation similar to a regular variable.
22
Constant
23
Constant
24
What is the output?
25
Content
• Variable
• Datatypes
– Interger Number
– Real Number
– Character
– Boolean
– void
• Expression
• Statement
• Library
26
Datatype
• Datatype determines the format of the value
as well as the actions allowed on it.
• C has 5 base datatypes:
– Interger number: Its values are integers like 1, 2,
3, -1, -2, …
– Floating point type: its values are real numbers
like 5.3, ...
– Logical type: true or false value.
– Character type: 256 characters in ASCII
encoding.
– void type: special type.
27
Integer type
• Integer type (sign)
– n bit with sign: –2n – 1 … +2n – 1 – 1
29
Floating point
• Floating-point
– For example: 17.06 = 1.706*10 = 1.706*101
30
Boolean
• Boolean
– C implicitly:
▪ false: 0.
▪ true: the value is nonzero, usually 1.
– C++: bool
• For example
– 0 (false), 1 (true), 2 (true), 2.5 (true)
– 1 > 2 (0, false), 1 < 2 (1, true)
31
Character type
• Character type
– Datatype: char
– Range: 256 characters in ASCII encoding.
• Why is char also an integer type?
– All data is stored as numbers.
– It doesn’t store the character directly, but stores
the ASCII code of that character.
– E.g.
▪ The number 65 is stored as the character 'A'.
▪ The number 97 is stored as the character 'a'.
32
Character type
33
Character type
• C++ provides many types of characters:
– char: uses 8 bits (1 byte).
– wchar_t: larger size to hold more characters, such
as Unicode characters.
– char16_t: uses 16-bit storage for characters,
typically used for UTF-16 encoding.
– char32_t: Uses 32-bit storage for characters,
typically used for UTF-32 encoding.
34
void type
• void – special type: used to indicate
– A function does not return any value.
– A pointer to an unknown type of object.
• For example:
void main() … // main function does not return a value.
void *p; // p is a pointer to an unknown type
(generic pointer).
void x; //error: variables cannot be of type void.
void &x: //error: cannot reference void type.
35
Content
• Variable
• Datatypes
• Expression
– Operator, Operand
– Priority
• Statement
• Library
36
Expression
• Expression:
– An operator affects the values of the operands
and produces a result of a certain type.
– Operator: +, –, *, /, %….
– Operand: constant, variable, function call...
• For example:
2 + 3, a / 5, (a + b) * 5, …
37
Assignment Operator
• Concept
– Used to store a value in a variable.
• Syntax
variable = value;
variable = variable;
variable = expression;
38
Assignment Operator
• For example
void main()
{
int a, b, c, d, e, result;
a = 10;
b = a;
result = a / b;
a = b = c = d = e = 156;
e = 156;
d = e;
c = d;
b = c;
a = b;
}
39
Mathematical operators
• Unary operator
– An expression with only one operand.
++ (increase by 1 unit), -- (decrease by 1 unit)
▪ ++x or --x: perform increase/decrease before use.
▪ x++ or x--: perform increase/decrease after use.
• For example
– x = 10; y = x++; // y = 10 and x = 11
– x = 10; y = ++x; // x = 11 and y = 11
40
Example
• What will be the output of the following code?
41
Mathematical operators
• Binary operator
– An expression with two operands.
+, –, *, /, % (modulus: divide and get the remainder)
x = x + y x += y;
• For example
a = 1 + 2; b = 1 – 2; c = 1 * 2; d = 1 / 2;
e = 1*1.0 / 2; f = float(1) / 2; g = float(1 / 2);
h = 1 % 2;
x = x * (2 + 3*5); x *= 2 + 3*5;
42
Quiz
43
Bitwise operators
• Bitwise operators
– Effect on bits of operand (integers).
& (and), | (or), ^ (xor), ~ (not or one's complement)
>> (shift right), << (shift left)
– &=, |=, ^=, ~=, >>=, <<=
& 0 1 | 0 1
0 0 0 0 0 1
1 0 1 1 1 1
^ 0 1 ~ 0 1
0 0 1 1 0
1 1 0
44
Bitwise operators
• Example
void main()
{
int a = 5; // 0000 0000 0000 0101
int b = 6; // 0000 0000 0000 0110
46
Relational operators
• Relational operators
– Compare two expressions.
– Returns 0 (false) or 1 (true)
==, >, <, >=, <, <=, !=
• For example
s1 = (1 == 2); s2 = (1 != 2);
s3 = (1 > 2); s4 = (1 >= 2);
s5 = (1 < 2); s6 = (1 <= 2);
47
Logical operators
• Logical operators
– Used to combine or modify Boolean expressions.
– && (and), || (or), ! (not)
&& 0 1 || 0 1
0 0 0 0 0 1
1 0 1 1 1 1
• For example
s1 = (1 > 2) && (3 > 4);
s2 = (1 > 2) || (3 > 4);
s3 = !(1 > 2);
48
The conditional operator
• The conditional operator
– Ternary Operator
<exp1> ? <exp2> : <exp3>
▪ If <exp1> is true then return <exp2>.
▪ If <exp1> is false then return <exp3>.
• Example
s1 = (1 > 2) ? 2912 : 1706;
int s2 = 0;
1 < 2 ? s2 = 2912 : s2 = 1706;
49
Comma operator
• Comman operator
– Expressions are separated by commas
– Sub-expressions are calculated from left to right.
– The result is the value of the expression on the
rightmost.
• For example
x = (a++, b = b + 2);
a++; b = b + 2; x = b;
50
Quiz
51
Priority of operators
Operators Priority
() [] -> . →
! ++ -- - + * (cast) & sizeof
* / % →
+ - →
<< >> →
< <= > >= →
== != →
& →
| →
^ →
&& →
|| →
?:
= += -= *= /= %= &= …
,
52
Priority of operators
• Rules
– Execute the deepest () expression first.
– Follow the priority of operators.
• For example
n = 2 + 3 * 5;
=> n = 2 + (3 * 5);
a > 1 && b < 2
=> (a > 1) && (b < 2)
53
Coding convention
• x is greater than or equal to 3
x >= 3
• a and b have the same sign
((a>0) && (b>0)) || ((a<0) && (b<0))
(a>0 && b>0) || (a<0 && b<0)
• p equals q equals r
(p == q) && (q == r)
(p == q && q == r)
• –5 < x < 5
(x > –5) && (x < 5)
(x > –5 && x < 5)
54
Quiz
55
Content
• Variable
• Datatypes
• Expression
• Statement
– Concepts
– Types
• Library
56
Statement
• Statement
– A statement tells the computer to perform a
specific task.
– The compiler ignores spaces, tabs, or line breaks
between statements.
• For example
a=2912;
a = 2912;
a
=
2912;
57
Statement
• Types of statements
– Single statement: contains only one statement.
– Complex statement (block of statements):
consists of multiple statements enclosed in { }.
• For example
{ // Block of statements
a = 2912;
b = 1706;
}
58
Quiz
59
Content
• Variable
• Datatypes
• Expression
• Statement
• Library
– Concept
– Input/output library
– Mathematical library
– Character library
60
Libraries
• To save effort, programmers can reuse predefined
functions (program segments) available during
program development.
61
Input/output library in C
• Declare libary
– #include <stdio.h> (standard input/output)
• Output function:
– printf(<string formatting>[, <arg1>, <arg2>, …]);
<string formatting> specifies how to format and
present output.
▪ Literal text
▪ Escape sequence
▪ Conversion specifier
62
String Formatting
• Literal text
– Output exactly as it was typed in the format
string.
• For example
– Output string: Hello World
➔ printf(“Hello ”); printf(“World”);
➔ printf(“Hello World”);
– Output string: a + b
➔ printf(“a + b”);
63
String Formatting
• Escape sequence
– Include a \ and a character as shown in the
following table:
Control characters Meaning
\a Ring tone
\b Go back
\n Newline
\t Tab
\\ Print \
\? Print ?
\” Print “
• For example
printf(“\t”); printf(“\n”);
printf(“\t\n”); 64
String Formatting
• Conversion specifier
– Include the % sign and one character.
– Determine the type of variable / value you want to
export.
– The main arguments are the variables / values you want
to output, listed in comma-separated order.
float x = 15.06;
printf(“%f”, x); ➔ output 15.060000
printf(“%f”, 1.0/3); ➔ output 0.333333
66
String Formatting
• Syntax
– Interger Formatting: %nd
– Real number formatting: %n.kd
int a = 1706;
float x = 176.85;
printf(“%10d”, a);printf(“\n”);
printf(“%10.2f”, x);printf(“\n”);
printf(“%.2f”, x);printf(“\n”);
1 7 0 6
1 7 6 . 8 5
1 7 6 . 8 5
67
String Formatting
int a = 1, b = 2;
Output “1 plus 2 equal 3” and newline.
▪ printf(“%d”, a); // Export the value of the variable a
▪ printf(“ plus ”);
▪ printf(“%d”, b);
▪ printf(“ equal ”);
▪ printf(“%d”, a + b);
▪ printf(“\n”);
➔ printf(“%d plus %d equal %d\n”, a, b, a+b);
68
Input function
• Library
– #include <stdio.h> (standard input/output)
• Input function
scanf(<string formatting>[, <arg1>, <arg2>, …]);
The arguments are the names of the variables
that will contain the input value and are preceded
by the &
69
Input function
• Example, give a and b integer types
scanf(“%d”, &a); // Enter value for variable a
scanf(“%d”, &b); // Enter a value for the variable b
➔ scanf(“%d%d”, &a, &b);
The following statements are incorrect
▪ scanf(“%d”, a); // &
▪ scanf(“%d”, &a, &b); // %d for b
▪ scanf(“%f”, &a); // a is a variable of integer
▪ scanf(“%9d”, &a); // is not formatted
▪ scanf(“a = %d, b = %d”, &a, &b”);
70
Quiz
71
Input/output in C++
72
Input and Output in C++
• cin (input)
– Used for input from the standard input
(keyboard).
– It reads data until a space or newline character
is encountered.
– Syntax: cin >> variable;
• cout (output)
– Used for output to the standard output (screen).
– It displays text and values.
– Syntax: cout << value;
73
Libraries
• Math library
#include <math.h> or #include <cmath> (for C++)
Most functions in the math library accept parameters
of type double and return double.
▪ acos, asin, atan, cos, sin, …
▪ exp, log, log10
▪ sqrt
▪ ceil, floor
▪ abs, fabs
Some functions receive two parameters
▪ double pow(double x, double y)
74
Examples
• Examples
int x = 4, y = 3, z = -5;
double t = -1.2;
double result1 = sqrt(x1);
double result2 = pow(x, y);
double result3 = pow(x, 1/3);
double result4 = pow(x, 1.0/3);
double result5 = abs(z);
double result6 = fabs(t);
75
Math library
Functions Description
double sqrt(double x); 𝑥
double pow(double x, double y); 𝑥 𝑦 (𝑥 > 0)
double exp(double x); 𝑒 𝑥 (𝑒 ≈ 2,71828)
double log(double x); ln 𝑥
double log10(double x); log10 𝑥
int abs(int x); 𝑥 (x type is int)
long labs(long x); 𝑥 (x type is long)
double fabs(double x); 𝑥 (x type is double)
76
Examples
Functions Description
Functions Description
bool isupper(char ch); Check ch whether is upper-
bool iswupper(wchar_t ch); case?
char toupper(char ch); Convert ch to upper-case
wchar_t towupper(wchar_t ch);
bool islower(char ch); Check ch whether is lowercase?
bool iswlower(wchar_t ch);
char tolower(char ch); Convert ch to lower-case
wchar_t towlower(wchar_t ch);
78
Example
79
Exercises
• Write C/C++ program as follow:
– Enter person name and birth-year.
– Compute person age and print result.
Notes: enter string with spaces:
▪ C: scanf(“%[^\n]”), fgets.
▪ C++: std::cin.getline.
• Input format:
Name = Nguyen Van A
Birth-year = 2005
• Output format:
Hello Nguyen Van A, now you are 19 years old.
80
Exercises
• Write C/C++ program to compute lucky
number of a car as follow:
– Enter car registration number (a 5-digit positive
integer).
– Compute and print the lucky number.
• Input format:
– Car Number: 17950
• Output format:
– Lucky number: 4
81
Exercises
• Write C/C++ program to convert temperature
degree as follow:
– Enter temperature degree in Celsius.
– Convert to Fahrenheit and Kelvin degrees, and print
results.
– Notes:
▪ Fahrenheit = Celsius * 1.8 + 32.
▪ Kelvin = Celsius + 273.
• Input format:
– Celsius = 25.5
• Output format:
– Fahrenheit = 77.9
– Kelvin = 298.5
82
Exercises
• Write C/C++ program to compute distance of
2 points of time in a day:
– Enter 2 points of time in a day T1 and T2 (hour,
minute, second).
– Compute distance (seconds) and print result.
• Input format:
– T1 (h m s) = 11 3 26
– T2 (h m s) = 14 25 18
• Output format:
– Distance = 12112
83
Exercises
• Cubic equation 𝑥 3 + 𝑝2 𝑥 + 𝑞 = 0 has only
one solution: