Data Types and Variables
Numeral Types, Text Types and Type Conversion
SoftUni Team
Technical Trainers
Software University
[Link]
Table of Contents
1. Data Types and Variables
2. Integer Types
3. Real Number Types
4. Type Conversion
5. Boolean Type
6. Character Type
7. String Type
2
Data Types and Variables
How Computing Works?
▪ Computers are machines that process data
▪ Instructions and data are stored
in the computer memory
10110
4
Variables
▪ Variables have name, data type and value
▪ Assignment is done by the operator "="
▪ Example of variable definition and assignment in C#
Variable name
Data type
int count =
Variable value
5;
▪ When processed, data is stored back into variables
5
What is a Data Type?
▪ A data type:
▪ Is a domain of values of similar characteristics
▪ Defines the type of information stored in the
computer memory (in a variable)
▪ Examples:
▪ Positive integers: 1, 2, 3, …
▪ Alphabetical characters: a, b, c, …
▪ Days of week: Monday, Tuesday, …
6
Data Type Characteristics
▪ A data type has:
▪ Name (C# keyword or .NET type)
▪ Size (how much memory is used)
int: sequence of 32
▪ Default value bits in the memory
▪ Example:
▪ Integer numbers in C# int: 4 sequential bytes
in the memory
▪ Name: int
▪ Size: 32 bits (4 bytes)
▪ Default value: 0 7
Naming Variables
▪ Always refer to the naming conventions of a
programming language - for C# use camelCase
▪ Preferred form: [Noun] or [Adjective] + [Noun]
▪ Should explain the purpose of the variable (Always
ask yourself "What does this variable contain?")
firstName, report, config, fontSize,
maxSpeed
foo, bar, p, p1, LastName, last_name,
LAST_NAME
8
Variable Scope and Lifetime
▪ Scope == where you can access a variable (global, local)
▪ Lifetime == how long a variable stays in memory
Accessible in the [Link]
string outer = "I'm inside the Main()";
for (int i = 0; i < 10; i++)
{
string inner = "I'm inside the
loop"; Accessible only in the loop
}
[Link](outer);
9
Variable Span
▪ Variable span is how long before a variable is called
▪ Always declare a variable as late as possible (e.g. shorter span)
string outer = "I'm inside the
[Link]";
for (int i = 0; i < 10; i++) "outer"
string inner = "I'm inside the variable span
loop";
[Link](outer);
// [Link](inner); Error
10
Keep Variable Span Short
▪ Shorter span simplifies the code
▪ Improves its readability and maintainability
for (int i = 0; i < 10; i++)
{
string inner = "I'm inside the "outer" variable
loop"; span – reduced
}
string outer = "I'm inside the
[Link]";
[Link](outer);
11
Integer Types
Integer Types
Defaul
Type t Min Value Max Value Size
Value
sbyte 0 -128 (-27) 127 (27-1) 8 bit
byte 0 0 255 (28-1) 8 bit
short 0 -32768 (-215) 32767 (215 - 1) 16 bit
usho
0 0 65535 (216-1) 16 bit
rt
int 0 -2147483648 (-231) 2147483647 (231 – 1) 32 bit
uint 0 0 4294967295 (232-1) 32 bit
-
922337203685477580
922337203685477580
long 0 7 64 bit
8
(263-1)
(-263) 13
Centuries – Example
▪ Depending on the unit of measure we can use different data types:
byte centuries = 20;
ushort years = 2000;
uint days = 730484;
ulong hours = 17531616;
[Link](
"{0} centuries = {1} years = {2} days = {3} hours.",
centuries, years, days, hours);
// 20 centuries = 2000 years = 730484 days = 17531616
hours.
14
Beware of Integer Overflow!
▪ Integers have range (minimal and maximal value)
▪ Integers could overflow 🡪 this leads to incorrect values
byte counter = 0; 1
for (int i = 0; i < 260; i+ 2
+) …
{ 25
counter++; 5
0
[Link](counter); 1
}
15
Integer Literals
▪ Examples of integer literals:
▪ The '0x' and '0X' prefixes mean a hexadecimal value
▪ E.g. 0xFE, 0xA8F1, 0xFFFFFFFF
▪ The 'u' and 'U' suffixes mean a ulong or uint type
▪ E.g. 12345678U, 0U
▪ The 'l' and 'L' suffixes mean a long
▪ E.g. 9876543L, 0L
16
Real Number Types
What Are Floating-Point Types?
▪ Floating-point types:
▪ Represent real numbers, e.g. 1.25, -0.38
▪ Have range and precision depending on the
memory used
▪ Sometimes behave abnormally in the calculations
▪ May hold very small and very big values like
0.00000000000001 and
10000000000000000000000000000000000
.0
18
Floating-Point Numbers
▪ Floating-point types are:
▪ float (±1.5 × 10−45 to ±3.4 × 1038)
▪ 32-bits, precision of 7 digits
▪ double (±5.0 × 10−324 to ±1.7 × 10308)
▪ 64-bits, precision of 15-16 digits
▪ The default value of floating-point types:
▪ Is 0.0F for the float type
▪ Is 0.0D for the double type
19
PI Precision – Example
▪ Difference in precision when using float and double:
float floatPI = 3.141592653589793238f; 3.141593
double doublePI = 3.141592653589793238;
[Link]("Float PI is: {0}", floatPI);
[Link]("Double PI is: {0}",
doublePI); 3.14159265358979
▪ NOTE: The "f" suffix in the first statement
▪ Real numbers are by default interpreted as double
▪ One should explicitly convert them to float
20
Problem: Convert Meters to Kilometres
▪ Write a program that converts meters to kilometers
formatted to the second decimal point
▪ Examples: 185 1.8 798 0.8
2 5 0
int meters = [Link]([Link]());
float kilometers = meters / 1000.0f;
[Link]($"{kilometers:f2}");
Check your solution here: [Link] 21
Problem: Pounds to Dollars
▪ Write a program that converts British pounds to US dollars
formatted to 3-th decimal point
▪ 1 British Pound = 1.31 Dollars
80 104.80 39 51.090
0
double num = [Link]([Link]());
double result = num * 1.31;
[Link]($"{result:f3}");
Check your solution here: [Link] 22
Scientific Notation
▪ Floating-point numbers can use scientific notation, e.g.
▪ 1e+34, 1E34, 20e-3, 1e-12, -6.02e28
double d =
10000000000000000000000000000000000.0;
[Link](d); // 1E+34
double d2 = 20e-3;
[Link](d2); // 0.02
double d3 = [Link];
[Link](d3); // 1.79769313486232E+308
23
Floating-Point Division
▪ Integral division and floating-point division are different:
[Link](10 / 4); // 2 (integral
division)
[Link](10 / 4.0); // 2.5 (real
division)
[Link](10 / 0.0); // Infinity
[Link](-10 / 0.0); // -Infinity
[Link](0 / 0.0); // NaN (not a number)
[Link](8 % 2.5); // 0.5 (3 * 2.5 + 0.5 24
Floating-Point Calculations – Abnormalities
▪ Sometimes floating-point numbers work incorrectly!
[Link](100000000000000.0 + 0.3);
// 100000000000000 (loss of precision)
double a = 1.0f, b = 0.33f, sum = 1.33;
[Link]("a+b={0} sum={1} equal={2}",
a+b, sum, (a+b == sum));
// a+b=1.33000001311302 sum=1.33 equal = False
double one = 0;
for (int i = 0; i < 10000; i++) one += 0.0001;
[Link](one); // 0.999999999999906
25
Decimal Floating-Point Type
▪ There is a special decimal floating-point real number type in
C#:
▪ decimal (±1,0 × 10-28 to ±7,9 × 1028)
▪ 128-bits, precision of 28-29 digits
▪ Used for financial calculations
▪ Almost no round-off errors
▪ Almost no loss of precision
▪ The default value of decimal type is:
▪ 0.0M (M is the suffix for decimal numbers) 26
Problem: Exact Sum of Real Numbers
▪ Write program to enter n numbers and print their exact sum:
2
10000000000000000 1000000000000000005
00
5
2
0.00000000003 333333333333.300000000
333333333333.3 03
Check your solution here: [Link] 27
Solution: Exact Sum of Real Numbers
▪ This code works, but makes rounding mistakes sometimes:
int n = [Link]([Link]());
double sum = 0;
for (int i = 0; i < n; i++) {
sum +=
[Link]([Link]()); }
[Link](sum);
▪ Change double with decimal and check the differences
Check your solution here: [Link] 28
Live Exercises
Integer and Real Numbers
Type Conversion
Type Conversion
▪ Variables hold values of certain type
▪ Type can be changed (converted) to another type
▪ Implicit type conversion (lossless): variable of bigger type
(e.g. double) takes smaller value (e.g. float)
float heightInMeters = 1.74f; Implicit type
double maxHeight = conversion
heightInMeters;
▪ Explicit type conversion (lossy) – when precision can be lost:
double size = 3.14; Explicit type
int intSize = (int) size; conversion
31
Problem: Centuries to Minutes
▪ Write program to enter an integer number of centuries and
convert it to years, days, hours and minutes
1 centuries = 100 years = 36524
Centuries =
days = 876576 hours = 52594560
1
minutes
5 centuries = 500 years = 182621
Centuries =
days = 4382904 hours = 262974240
5
minutes
The output is on one row
Check your solution here: [Link]
32
Solution: Centuries to Minutes
int centuries = [Link]([Link]());
Tropical year has
int years = centuries * 100; 365.2422 days
int days = (int)(years * 365.2422);
int hours = 24 * days;
(int) converts
int minutes = 60 * hours; double to int
[Link](
"{0} centuries = {1} years = {2} days = {3} hours = {4}
minutes",
centuries, years, days, hours, minutes);
Check your solution here: [Link]
33
Boolean Type
Boolean Type
▪ Boolean variables (bool) hold true or false:
int a = 1;
int b = 2;
bool greaterAB = (a > b);
[Link](greaterAB); // False
bool equalA1 = (a == 1);
[Link](equalA1); // True
35
Problem: Special Numbers
▪ A number is special when its sum of digits is 5, 7 or 11
▪ For all numbers 1…n print the number and if it is special
1 -> False 8 -> False 15 -> False
2 -> False 9 -> False 16 -> True
3 -> False 10 -> False 17 -> False
20 4 -> False 11 -> False 18 -> False
5 -> True 12 -> False 19 -> False
6 -> False 13 -> False 20 -> False
7 -> True 14 -> True
Check your solution here: [Link]
36
Solution: Special Numbers
int n = [Link]([Link]());
for (int num = 1; num <= n; num++)
{
int sumOfDigits = 0;
int digits = num;
while (digits > 0)
{
sumOfDigits += digits % 10;
digits = digits / 10;
}
// TODO: check whether the sum is special
}
Check your solution here: [Link] 37
'A'
Character Type
The Character Data Type
▪ The character data type in C#
▪ Represents symbolic information
▪ Is declared by the char keyword
▪ Gives each symbol a corresponding integer code
▪ Has a '\0' default value
▪ Takes 16 bits of memory (from U+0000 to U+FFFF)
▪ Holds a single Unicode character (or part of character)
39
Characters and Codes
▪ Each character has a unique Unicode value (int):
char ch = 'a';
[Link]("The code of '{0}' is: {1}", ch, (int)
ch);
ch = 'b';
[Link]("The code of '{0}' is: {1}", ch, (int)
ch);
ch = 'A';
[Link]("The code of '{0}' is: {1}", ch, (int)
ch);
40
Problem: Reversed Chars
▪ Write a program that takes 3 lines of characters and prints
them in reversed order with a space between them
▪ Examples:
A 1
B C B L & L
C A & 1
Check your solution here: [Link]
41
Solution: Reversed Chars
char firstChar = [Link]([Link]());
char secondChar = [Link]([Link]());
char thirdChar = [Link]([Link]());
[Link]($"{thirdChar} {secondChar}
{firstChar}");
Check your solution here: [Link]
42
Escaping Characters
▪ Escaping sequences are:
▪ Represent a special character like ', " or \n (new line)
▪ Represent system characters (like the [TAB] character \t)
▪ Commonly used escaping sequences are:
▪ \' 🡪 for single quote \" 🡪 for double quote
▪ \\ 🡪 for backslash \n 🡪 for new line
▪ \uXXXX 🡪 for denoting any other Unicode symbol
43
Character Literals – Examples
char symbol = 'a'; // An ordinary character
symbol = '\u006F'; // Unicode character code in a
// hexadecimal format (letter
'o')
symbol = '\u1F3B8'; // 🎸 (guitar)
symbol = '\''; // Assigning the single quote
character
symbol = '\\'; // Assigning the backslash character
symbol = '\n'; // Assigning new line character
symbol = '\t'; // Assigning TAB character 44
"ABC"
String
Sequence of Characters
The String Data Type
▪ The string data type in C#
▪ Represents a sequence of characters
▪ Is declared by the string keyword
▪ Has a default value null (no value)
▪ Strings are enclosed in quotes:
string text = "Hello,
C#";
▪ Strings can be concatenated
▪ Using the + operator
46
Verbatim and Interpolated Strings
▪ Strings are enclosed in quotes "":
The backslash \
string file = "C:\\Windows\\ is escaped by \\
[Link]";
▪ Strings can be verbatim (no escaping):
The backslash \
string file = @"C:\Windows\ is not escaped
[Link]";
▪ You can use verbatim strings with $ interpolation:
string os = "Windows";
string file = "[Link]";
string path = $@"C:\{os}\{file}";
47
Problem: Concat Names
▪ Read first and last name and delimiter
▪ Print the first and last name joined by the delimiter
John Lind
Smit John- a Linda=>Terr
h >Smith Terr y
-> y
Jan =>
Lee
Whit Jan<- Lewi Lee---
e >White s Lewis
<-> ---
Check your solution here: [Link] 48
Solution: Concat Names
string firstName = [Link]();
string lastName = [Link]();
string delimiter = [Link]();
string result = firstName + delimiter + lastName;
[Link](result);
Second<->First
49
Summary
▪▪Variables
… – store data
▪▪Numeral types:
…
▪ Represent numbers
▪ …
▪ Have specific ranges for every type
▪ String and text types:
▪ Represent text
▪ Sequences of Unicode characters
▪ Type conversion: implicit and explicit
50
Questions?
© SoftUni – [Link] Copyrighted document. Unauthorized copy, reproduction or use is not permitted.