0% found this document useful (0 votes)
5 views

Topic2-Variable and Basic Data Type

Uploaded by

Da Vy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Topic2-Variable and Basic Data Type

Uploaded by

Da Vy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Data structure &

programming i
Topic 2: Variable, Basic Data Type,
Operators and Statements

1
Variable/Identifier

2
Variable/Identifier
What and Why?

▪ A variable (also called identifier) is a holder of value which can be used and
changed throughout the program
▪ It is used to store value and its value can be changed during the program run

t1 = a1 * 4100 rate = 4100


▪ Why need variable? t2 = a2 * 4100
t3 = a3 * 4100
t1 = a1 * rate
t2 = a2 * rate
▪ Understandability and Readability t3 = a3 * rate
▪ Maintainability
▪ Ex: Exchange rate computation

What if the multiplier is changed to 4050?


=>You will need to change 3 times. What if the multiplier is changed to 4050?
What if you have 100 lines using the multiplier (4100)? =>You just need to update value of rate to 4050
=>Change 100 times ???
3
Variable/Identifier
How to create a variable?

▪ A variable is created by variable declaration.


▪ We declare a variable in order to reserve memory space for it

▪ Syntax to declare a variable (for writing algorithm)


▪ Asd
Var list_of_variables : Type of variable
keyword Colon Its type
Variable name
Use comma ( , ) if u have more than one
variable to be created

4
Variable/Identifier
Basic types of variables

▪ Number
▪ Integer : A non-fractional number, e.g: 5, 8, 9, 199
▪ Float : A non-fractional and fractional number (real number), e.g: 4, 4.0 or 5.8
▪ Character : A single letter. It is placed inside a single quote, e.g: ‘M’
▪ Sequence of character : A string ( a set of letters). It is placed inside a double
quote, e.g: “Sok”
▪ NOTE: Different types of variables consume different memory space

Var gender: Character


▪ Examples of variable declaration:
Var age, number: Integer
▪ Asdf
▪ Asdf Var name, title: Sequence of character
▪ asdf Var person_weight: Float
5
Variable or Identifier
Naming a variable

▪Rules of giving
Rule for namingaavariable
variable name
✓ Start with a letter (small or capital is okay) or underscore
✓ Not start with number or any symbol (+, -, @, #, !, &, *, /, ., …. etc)
✓ Don’t use name that already exist with reserved keywords
✓ No space is allowed.
▪ If the name is long, use underscore ( _ , person_weight) or camel case (myVar, personWeight)
▪ Naming convention (good practice)
▪ Name of a variable should reflect the value it will store
▪ The name should be readable and not too short
▪ Examples: Var age: Integer Var 7age: Integer
Var price: Float Var @price: Float
Var name: Sequence of character Var +name: Sequence of character
Var _tel: Integer Var *tel: Integer
Var studentName: Sequence of character Var &student Name: Sequence of character
Var work_position: Sequence of character Var work Position: Sequence of character
6
Variable or Identifier
NOTE: Naming a variable

▪ Name of a variable is case sensitive (Ex: age, Age, AGE are different names)

Var age: Integer


Var Age: Integer
Var aGe: Integer
Var AGE: Integer

▪ Each variable can’t have the same name


▪ Once a name is given to a variable, that name can’t be used for naming another variable

Var sex: Character


Var sex: Sequence of character
Var price: Integer
Var price: Float

7
Variable or Identifier
Assign value to a variable

▪ Assign value to a variable means that you give a value to that variable
▪ Syntax for assigning a value to a variable:
▪ <variable>  <value or other variable (same type) or expression>
▪ The type of value assigning to the variable must be the same as variable’s type
▪ A variable can be used once a value was assigned to that variable
▪ Examples:
▪ Var name, name2 : Sequence of integer
Var name, name2 : Sequence of character Var name, name2 : Sequence of character
Var val▪ :Var val : Integer
Integer Var val : Integer
name  ▪ name
“Sok”  “Sok” name  “Sok”
name2 ▪ name2
“Sao”  “Sao” name  “name2”
name  ▪ name
name2  “name2” name  name2
val ▪ val
5  5 val  name
val ▪ val
val*2  val*2 val  “Dara”

8
Algorithm
Constant

▪ It is a non-changeable value (its value is fixed for all algorithm)


▪ Syntax for declaring a constant:
const(identifier: Type)  value or expression

keyword name Its type Fixed value or result of an operation


▪ Examples:
const(YEAR: Integer)  2018
const(NEXT3YEAR: Integer)  YEAR+3
const(EXCHANGE_RATE: Integer)  4100

▪ Rule for naming a constant and naming convention)


▪ Same as variables’ rules, but
▪ All letters should be capitalized
9
Algorithm
Entering data / Get user’s inputs

▪ Syntax for entering a data:

read(<list of variables>)

keyword Variable name


If more than one, use comma ( , )

▪ It is an instruction to get input from user and assign to a variable


▪ Examples:
▪ read(number) : ask a user for an input and store it in a variable named number
▪ read(name, surname) : ask a user for two inputs and store it in the variables namely
name, surname
▪ read(age) : ask a user for an input and store it in the variable named age

10
Algorithm
Displaying the information or data

▪ It is an instruction to display information


▪ Syntax for displaying a data:
write(“static text”, <variables, constants, or expression>)

keyword Display what you write Placeholder/value


(placed inside double quotes) (just put a variable name or constant name or an
▪ Examples: expression/operation)
▪ write(“Enter a number: ”)
▪ read(number) //Suppose user inputs number 7 here
▪ write(“This is the input from user: ”, number)
▪ This is the input from user: 7

▪ write(“The sum of ”, number, “ and 3 ”, “is ”, number+3)


▪ The sum of 7 and 3 is 10 11
Examples of Algorithms
How to add two numbers
▪ Writing an algorithm for adding input two numbers. Then display the result.

Var num1, num2: integer


Var result: integer
Begin
write(“Enter the first number: ”)
read(num1)
write(“Enter the second number: ”)
read(num2)

result  num1 + num2


write(“The sum is: ”, result)
write(“The sum of ”, num1, “ and ”, num2, “is: ”, result)
End

Output: …? 12
More Examples of Writing Algorithms
Ex1: Calculate a given price with tax

▪ Suppose that the tax is 3% and a user is required to input a price. As a result
we calculate and display the final price including the tax.

Var .........: …Type…


Begin

....

End

13
More Examples of Writing Algorithms
Ex1: Calculate a given price with tax

▪ Suppose that the tax is 3% and a user is required to input a price. As a result
we calculate and display the final price including the tax.
const(TAX: int)  3
const(TITLE: string)  “Result”
Var price, priceWithTax: float
Begin
write(“Give me the price exclude tax:”)
read(price)
priceWithTax  price + (price*TAX)/100
write(TITLE)
write(price, “dollars exclude tax.”, priceWithTax, “dollars include tax”)
End

Output: …? 14
Examples of Algorithms
Ex2: Student information

▪ Ask a student’s information (name, department, birth’s year). Then greet


him/her with the following information:
Enter your name: Var name, department: Sequence of characters
Which department are you from?: Var year_birth: Integer
Which year were you born?: Var age: Integer
Begin
write(“Enter your name: ”)
Hello <name>! Welcome to <department>.
read(name)
You are <age> years old. write(“Which department are you from?: ”)
read(department)
write(“Which year were you born?”: )
read(year_birth)

age  2021 – year_birth


write(“Hello”, name, “! Welcome to ”, department, “.”)
write(“You are ”, age, “years old.”)
End
15
Examples of Algorithms
Ex3: Currency exchange program

▪ Write an algorithm for computing an exchange rate USD-Riel. Suppose that 1USD= 4100 R. A
user is required to input an amount of money in USD then a program will convert it into riel
currency and display the following information

How much in US dollars do you want CONST(RATE: Float)  4100


to exchange?: Var amountUSD: Float
Your exchange amount of Var amountRiel: Float
Begin
<amountUSD> dollars are equal to:
write(“How much in US dollars do you want to exchange?: ”)
<amountRiel> when the exchange
read(amountUSD)
rate is 1 USD = 4100 riels amountRiel  amountUSD * RATE
write(“Your exchange amount of ”, amountUSD, “ dollars are
equal to: ”, amountRiel, “when the exchang rate is
1 USD = ”, RATE, “riels”)
End

16
Practise
Write an algorithm for each of the question below:

1. Read a last name and first name from a user. Then display a phrase as follows:
What is your last name?
What is your first name?
Welcome <lastname> <firstname>!

2. Read a number from a user and calculate square of that number then display
its result.
Enter a number:
The square of <number> is ….

3. Read two numbers (say n1 and n2) from a user then display their summation,
subtract, and multiplication. Enter the first number:
Enter the second number:
The summation of <n1> and <n2> is: …
The subtraction of <n1> and <n2> is: …
The multiplication of <n1> and <n2> is: …
17
The division of <n1> and <n2> is: …
Practise
Write an algorithm for each of the question below:

4. A program to ask user for firstname, lastname and department. Then display
this message:
Welcome to department, lastname firstname!

5. Ask a user to input height and base of a triangle. Calculate the surface of this
triangle and display.

6. Ask a user for a, b and c length of a triangle. Calculate its surface using heron
formula.

18
Types of Variables

19
Overview
Outline

▪ Integer ▪ String

▪ Real ▪ Functions for string

▪ Boolean ▪ Operators
+, -, *, /, DIV, MOD
▪ Character
▪ Relational operators
▪ ASCI code

▪ Functions for character

20
Basic data type: Integer
Integer

▪ Integer is a positive or negative number without fraction number


▪ …, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,…
▪ Declaration
▪ Var <identifier> : Integer
▪ Example:
▪ Var age: Integer
▪ Var x, y, z: Integer

21
Basic data type: Integer
Operators for Integer

▪ Operations: / DIV MOD ▪ Operations: + - *


▪ / : find a result of a division operation ▪ + : summation
▪ DIV : find a quotient of a division operation (not ▪ - : subtraction
include fractional part)
▪ * : multiplication
▪ MOD : find a remainder of a division operation

▪ Examples:
▪ x  10+2 => x is 12
▪ y  x-7 => y is 12-7=5
▪ z  y/2 => z is 5/2=2.5
▪ z  y MOD 2 => z is 5 MOD 2 = 1
▪ z  y DIV 2 => z is 5 DIV 2 = 2

22
Practice 1

▪ Let try to predict values of a, b, and c below

No. Suppose: Inspecting values:


1 a  5 a is 5, but b and c are unknown
2 b  8 a is 5, b is 8, but c is unknown
3 c  10 a is 5, b is 8 and c is 10
4 a  b MOD 3 a is 2, b is 8 and c is 10
5 b  b DIV 3 a is 2, b is 2 and c is 10
6 b  a DIV 3 a is 2, b is 0 and c is 10
7 c  c DIV 3 a is 2, b is 0 and c is 3
8 b  c MOD 2 a is 2, b is 1 and c is 3
9 c  c DIV 4 a is 2, b is 1 and c is 0

23
Basic data type: Real number
Real number

▪ Real is a general number including fraction number


…, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,…
▪ Declaration
Var <identifier> : Float
Var <identifier> : Double
▪ Examples:
Var height: Float
Var a, b, c: Double
▪ Operation: +, -, *, /
a  10.5 – 2.5 => a is 8.0
b  a*3.9 => b is 31.2
c  b/a => c is 3.9
24
Boolean
Definition

▪ Boolean is a logic variable that contains either true or false


▪ Declaration
Var <identifier>: Boolean
▪ Examples:
Var is_primary: Boolean Variable Value (T:True, F:False)
Var p, q, r: Boolean p T
▪ Operations: AND, OR, NOT q F
p AND q F
Let a, b be boolean values where a NOT(p) F
is true and b is false
➢ a AND b : yields true when both NOT(NOT(q)) F
a and b are true
➢ a OR b : yields true when either
a or b is true
25
Practice 2
Boolean operator

▪ Example

Var p, q, r: Boolean Value:


Begin
p  true p=True
q  NOT(p)
q=False
r  (p AND q) OR (NOT(p) AND NOT(NOT(q)))
End r=False

Let a true and b true


Period: 3mn c <- a AND b TRUE
d <- a AND NOT(c) FALSE
e <- c AND D FALSE
26
Boolean
Relational operators

▪ The relational operators allow you to write relational expressions


▪ Some relational operators: Do relational Boolean
==, !=, >, <, >=, <= operator

▪ The results of relational operators are Boolean a<3 ? F


a==b ? F
▪ Syntax: b<100 ? T
expression1 operator expression2
a==10 ? T
a>=10 ? T
▪ Examples: a>10 AND b<100 ? F
a  10 a != 100 ? T
b  20

27
Character
Definition

▪ A character is a single lowercase/uppercase letter, number, punctuation mark,


space, tab, newline and other special operation, which is written in single
quote ‘ ’
▪ E.g: ‘a’, ‘B’, ‘+’, ‘.’, ‘8’, …
Examples
Function Description
What? Output

▪ Declaration next(character) Give the next character next(‘b’) ‘c’


Var <identifier>: Character after character
▪ Examples: prev(character) Give the previous prev(‘E’) ‘D’
character before character
Var sex, grade: Character
ord(character) Give the ASCII code of ord(‘A’) 65
sex  ‘M’
character
chr(integer) Give the character of the chr(65) ‘A’
ASCII code integer

28
Function
What?
▪ A function is used to achieve/do something
▪ A function may take no input/parameter/argument
▪ A function may take one or more parameters

▪ A function may be used to calculate and return a value


▪ A function may return a value or not return any value.
▪ Once defined, a function can be called anytime

▪ A function can be:


▪ Built-in function : existing function
▪ Custom function : user newly defines it (user-defined function)

29
Character
ASCII CODE

▪ ASCII: American Standard Code for Information Interchange


▪ Each character has its equivalent numeric code (integer)
▪ The basic ASCII characters represent in 7 bits
▪ There are 128 possible characters (from 0 to 127)
▪ Example ASCII Code Table

Var c: Character Output:


Var n: Integer
Begin
c  ‘A’
write(c) A
write(‘c’) c
write(ord(c)) 65
n  ord(c)+1
write(n) 66
End 30
ASCII Code

http://www.asciitable.com/
31
32
String
Definition

▪ String is a sequence of character and it is written inside double quotes “ ”


▪ E.g: “Hello”, “1234”, “I’m fine”
▪ Declaration:
▪ Var identifier: Sequence of character
▪ Examples
▪ Var name, surname: Sequence of character
▪ name  “Marry”
▪ write(name) “Marry”
▪ write(name[0]) ‘M’

index 0 1 2 3 4
name M a r r y

33
String
Functions

▪ String functions Examples


Function Description
E.g: Output
concat(string1, string2) concatenate two concat(“Hel”, “lo”) “Hello”
strings together
length(string) Find number of length(“hello ”) 6
character in string length(“”) 0
length(concat(“Thank”, “ you”)) 9
substring(p, n, string) Find substring substring(2, 4, “Algorithm”) “gori”
positioning at p substring(0, 5, “I am fine” “I am ”
upward for n substring(6, 1, “I am find” “i”
characters from a
string
identifier[index] Find a character name  “Marry”
positioning at index name[0] ‘M’

index 0 1 2 3 4
name M a r r y 34
String
Functions

▪ String functions Examples


Function Description
E.g: Output
stringcomp(string1, Compare two strings stringcomp(“Hi”, “Hi”) 0
string2) • 0: if they are same
• Otherwise, they are
different
stringcopy(des, source) Copy a string Var var1: Sequence of character “Hi”
stringcopy(var1, “Hi”)

string2lowercase(string) Convert string into string2lowercase(“Hello”) “hello”


lowercase
string2uppercase(string) Convert string into string2uppercase(“Hello”) “HELLO”
uppercase

35
Summary
Revision
▪ Integer : non-fractional number Integer
▪ Real : real number Float, Double
▪ Character : a single character written in a single quote ‘ ’
▪ Boolean : true or false value
▪ String : a sequence of character written in a double quote “ ”
▪ Operators :+ - * / DIV MOD
▪ Relational operators : == > < >= <= !=
▪ Functions for Character : next, prev, ord, chr
▪ Functions for String : concate, length, substring, stringcmp,
stringcopy, string2lowercase, string2uppercase

36
Q&A
37
Practice
Exercises

1. Write an algorithm to determine DIV and MOD of two input numbers from a user

2. Write an algorithm to calculate the summation of two input of real numbers from
a user and identify the integer part and fractional part

3. Suppose we have: a true, b false. What is the value for each of:
▪ NOT(a), NOT(b), a OR b , NOT(a) OR NOT (b), NOT(a) AND b, a AND b

4. Write an algorithm that allows a user to input two string. Copy the second string to the first
one then covert first string to uppercase.

38
Practice

▪ Suppose we have: a true, b false. What is the value for each of:
▪ NOT(a), NOT(b), a OR b , NOT(a) OR NOT (b), NOT(a) AND b, a AND b

39
Practice

▪ Write an algorithm that allows a user to input two string. Copy the second
string to the first one then covert first string to uppercase.

40
Practice
1. Write an algorithm to ask for firstname and lastname from a user. Then make another variable username. This
variable is the result of contatenation between firstname, underscore ( _ ), and lastname.
E.g: If input for firstname and last name are Jack and Rose, then username should be Jack_Rose

2. Write an algorithm to convert an input string, entered by a user, to uppercase and lowercase. E.g: If a user inputs the
word Apple, then the output of the program should be APPLE, apple

3. Write an algorithm to find the length of an input string. E.g: If a user inputs the word Book, then the output of the
program should be The length of the word “Book” is 4.

41
Practice
4. Write an algorithm to display the first character and the last character of an input string entered by a user. E.g: If a
user inputs the word Banana, then the output of the program should be In word “Banana”, the first character is ‘B’
and the last character is ‘a’

5. Suppose we have: a=50, b=-50, then what is the Boolean value of each expression below
▪ A) a>50, B) b>=50, C) a==50 AND b==50, D) a==50 OR b==50,

▪ E) a>50 AND b<0, F) a<0 OR b<0, G) a>0 AND b<0,

▪ H) NOT((NOT(a>50) AND (a>0)) AND NOT(b<0))

6. By taking a look at the ASCII code tables, answer the question below:
▪ What are the ASCII codes for the letters a, b, c, …., z ?

▪ What are the ASCII codes for the letters A, B, C, …, Z?

▪ What are the ASCII codes for the numbers 0, 1, 2, …, 9?

▪ What are the ASCII codes for these characters é è ç É È ?


42
Examples in C programming using string functions
#include <string.h>
String functions

s1&s2 are strings (sequence of character)

▪ strupr( s1) : convert string to uppercase

▪ strlwr( s1) : convert string to lowercase

▪ strlen( s ) : find length of a s

▪ strcpy(s1, s2) : copy string

▪ strcat(s1, s2) : concatenate string

▪ strcmp(s1, s2) : compare strings

▪ strrev(s1) : reverse string

43
Examples in C programming using string functions
#include <string.h>

String functions

s1&s2 are strings (sequence of character)

▪ strupr( s1) : convert string to uppercase

▪ strlwr( s1) : convert string to lowercase

▪ strlen( s ) : find length of a s

▪ strcpy(s1, s2) : copy string

▪ strcat(s1, s2) : concatenate string

▪ strcmp(s1, s2) : compare strings

▪ strrev(s1) : reverse string

44
Examples in C programming using string functions
#include <string.h>
String functions

s1&s2 are strings (sequence of character)

▪ strupr( s1) : convert string to uppercase

▪ strlwr( s1) : convert string to lowercase

▪ strlen( s ) : find length of a s

▪ strcpy(s1, s2) : copy string

▪ strcat(s1, s2) : concatenate string

▪ strcmp(s1, s2) : compare strings

▪ strrev(s1) : reverse string

45
Assignment Deadline: 1 week
1. Write a C program to concatenate a string. The user is required to input the name of a student and the name of a
course enrolled by that student. For example, the message sample is defined as follows:

Welcome studentName to the course courseName.

2. Write a C program to convert an input string, entered by a user, to uppercase and lowercase. E.g: If a user inputs the
word Apple, then the output of the program should be APPLE, apple

3. Write a C program to find the length of an input string. E.g: If a user inputs the word Book, then the output of the
program should be The length of the word “Book” is 4.

4. Write a C program to display the first character and the last character of an input string entered by a user. E.g: If a
user inputs the word Banana, then the output of the program should be In word “Banana”, the first character is ‘B’
and the last character is ‘a’

46

You might also like