Sunteți pe pagina 1din 14

3.

1 DATA REPRESENTATION AHMED THAKUR

3.1.1 USER-DEFINED DATA TYPES

 Understanding of why user-defined types are necessary

PROGRAMMING PARADIGM
A programming paradigm is a fundamental style of computer programming, serving as a way of
building the structure and elements of computer programs. Capabilities and styles of various
programming languages are defined by their supported programming paradigms; some
programming languages are designed to follow only one paradigm, while others support multiple
paradigms.

Programming paradigms that are often distinguished include imperative, declarative, functional,
object-oriented, procedural, logic and symbolic programming. With different paradigms, programs
can be seen and built in different ways; for example, in object-oriented programming, a program is
a collection of objects interacting in explicitly defined ways, while in declarative programming the
computer is told only what the problem is, not how to actually solve it.

USER-DEFINED DATA TYPES:


 Non-Composite
 Composite

 Define and use non-composite types: enumerated, pointer

NON-COMPOSITE DATA TYPES


 Pointer
 Enumerated

Pointer
A pointer is a data type whose value refers directly to (or "points to") another value stored elsewhere
in the computer memory using its address.

Pointers are incredibly important computing concepts as we need pointers to create many of the
ADTs (Abstract Data Types) we are going to talk about. Some languages don't allow you to directly
manipulate them, but all languages use them. For this section of the book you need to be familiar
with the concept of pointers as we'll be using them heavily when we talk about linked lists, queues
and stacks.

COMPUTER SCIENCE https://www.facebook.com/groups/OAComputers/


ahmed_thakur@hotmail.com, 0300-8268885 Page 1
9608
3.1 DATA REPRESENTATION AHMED THAKUR

3.1.1 USER-DEFINED DATA TYPES

Quick examples of pointers might include the next free memory location in an array, or the location
in memory that an array is stored at.

Example: Pointers
Let's take a look at how pointers are used in the C programming Language.
We are going to deal with two variables:

a
ptr

We are also going to meet two key characters:

& - where &a would return the address location of variable a


* - where *ptr = 8 means follow the memory address stored in ptr and set that
location to 8

Assume that a is located at address 0x8130 in memory and ptr at 0x8134; also assume this is a
32-bit machine such that an int is 32-bits in size. The following is what would be in memory after
the following code snippet is executed:

int a = 5;
int *ptr = NULL;

Address Contents
0x8130 0x00000005
0x8134 0x00000000

(The NULL pointer shown here is 0x00000000.) By assigning the address of a to ptr :

ptr = &a;

yields the following memory values:


Address Contents
0x8130 0x00000005
0x8134 0x00008130

Then by dereferencing ptr by coding:

*ptr = 8;

the computer will take the contents of ptr (which is 0x8130), 'locate' that address, and assign 8
to that location yielding the following memory:
Address Contents
0x8130 0x00000008

COMPUTER SCIENCE https://www.facebook.com/groups/OAComputers/


ahmed_thakur@hotmail.com, 0300-8268885 Page 2
9608
3.1 DATA REPRESENTATION AHMED THAKUR

3.1.1 USER-DEFINED DATA TYPES

0x8134 0x00008130

Clearly, accessing a will yield the value of 8 because the previous instruction modified the
contents of a by way of the pointer ptr .

Enumerated Data Types


If you are using lots of constants in your program that are all related to each other it is a good idea
to keep them together using a structure called an Enum. For example you might want to store the
names of each set of cards in a deck, instead of writing:

Const heart as integer = 1


Const club as integer = 2
Const spade as integer = 3
Const diamond as integer = 4

dim cardset as string


cardset = spade

We can bring them together in a nice neat structure called an enum:

Enum suits
HEARTS = 1
CLUBS = 2
SPADES = 3
DIAMONDS = 4
End Enum
dim cardset as suits
cardset = suits.HEARTS

This allows you to set meaningful names to the enum and its members, meaning it easier to
remember and makes your code more readable.

We might also create separate constants to store the points of football results

Const Win as Integer = 3


Const Draw as Integer = 1
Const Lose as Integer = 0

With enums we can create a datatype called Result and store the points within it, under easy to
remember name:

Enum Result
Win = 3
Lose = 1
Draw = 0
End Enum

dim ManUvChelsea as Result


ManUvChelsea = Result.Win
Console.Writeline("ManU scored " & ManUvChelsea & " points" )

COMPUTER SCIENCE https://www.facebook.com/groups/OAComputers/


ahmed_thakur@hotmail.com, 0300-8268885 Page 3
9608
3.1 DATA REPRESENTATION AHMED THAKUR

3.1.1 USER-DEFINED DATA TYPES

Exercise

Question:
Declare an enum called months that holds the months along with how many days
in each for a non-leap year

Answer:
Enum months
January = 31
February = 28
March = 31
April = 30
May = 31
June = 30
July = 31
August = 31
September = 30
October = 31
November = 30
December = 31
End Enum

COMPOSITE DATA TYPES


A composite data type is any data type which can be constructed in a program using the
programming language's primitive data types and other composite types. The act of constructing a
composite type is known as composition.

Using composite data, we can manage multiple pieces of related data as a single datum. For
example if you wanted to store information about a person you could store there date of birth, sex,
address etc. as single variables but then when you wanted to add another person you would have
to remember to create all the variables but with slightly different names. As the number of people
increased so would the complexity of your naming and the relationship between the variables would
be lost. In ActionScript you could create an object called person which had properties to store the
date of birth, sex, address etc, you would then create instances of that object. The composite data
types that ActionScript supports are:
 (array.
 object.
 movie clip.
 functions.)

 set,
 record
 class/object

SET
It is a composite data type that can store data in any particular order, in which each element is
indexed. Sets cannot have data items repeated more than once

Constructing Sets
One way to construct sets is by passing any sequential object to the "set" constructor.

>>> set([0, 1, 2, 3])


set([0, 1, 2, 3])
>>> set("obtuse")

COMPUTER SCIENCE https://www.facebook.com/groups/OAComputers/


ahmed_thakur@hotmail.com, 0300-8268885 Page 4
9608
3.1 DATA REPRESENTATION AHMED THAKUR

3.1.1 USER-DEFINED DATA TYPES

set(['b', 'e', 'o', 's', 'u', 't'])

We can also add elements to sets one by one, using the "add" function.

>>> s = set([12, 26, 54])


>>> s.add(32)
>>> s
set([32, 26, 12, 54])

Note that since a set does not contain duplicate elements, if we add one of the members of s to s
again, the add function will have no effect. This same behavior occurs in the "update" function,
which adds a group of elements to a set.

>>> s.update([26, 12, 9, 14])


>>> s
set([32, 9, 12, 14, 54, 26])

Note that you can give any type of sequential structure, or even another set, to the update function,
regardless of what structure was used to initialize the set.

The set function also provides a copy constructor. However, remember that the copy constructor
will copy the set, but not the individual elements.

>>> s2 = s.copy()
>>> s2
set([32, 9, 12, 14, 54, 26])

Membership Testing
We can check if an object is in the set using the same "in" operator as with sequential data types.

>>> 32 in s
True
>>> 6 in s
False
>>> 6 not in s
True

We can also test the membership of entire sets. Given two sets S1 and S2, we check if S1 is a subset or
a superset of S2.

>>> s.issubset(set([32, 8, 9, 12, 14, -4, 54, 26, 19]))


True
>>> s.issuperset(set([9, 12]))
True

COMPUTER SCIENCE https://www.facebook.com/groups/OAComputers/


ahmed_thakur@hotmail.com, 0300-8268885 Page 5
9608
3.1 DATA REPRESENTATION AHMED THAKUR

3.1.1 USER-DEFINED DATA TYPES

Note that "issubset" and "issuperset" can also accept sequential data types as arguments

>>> s.issuperset([32, 9])


True

Note that the <= and >= operators also express the issubset and issuperset functions respectively.

>>> set([4, 5, 7]) <= set([4, 5, 7, 9])


True
>>> set([9, 12, 15]) >= set([9, 12])
True

Like lists, tuples, and string, we can use the "len" function to find the number of items in a set.

Removing Items
There are three functions which remove individual items from a set, called pop, remove, and discard.
The first, pop, simply removes an item from the set. Note that there is no defined behavior as to which
element it chooses to remove.

>>> s = set([1,2,3,4,5,6])
>>> s.pop()
1
>>> s
set([2,3,4,5,6])

We also have the "remove" function to remove a specified element.

>>> s.remove(3)
>>> s
set([2,4,5,6])

However, removing a item which isn't in the set causes an error.

>>> s.remove(9)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 9

If you wish to avoid this error, use "discard." It has the same functionality as remove, but will simply do
nothing if the element isn't in the set
We also have another operation for removing elements from a set, clear, which simply removes all
elements from the set.

>>> s.clear()
>>> s

COMPUTER SCIENCE https://www.facebook.com/groups/OAComputers/


ahmed_thakur@hotmail.com, 0300-8268885 Page 6
9608
3.1 DATA REPRESENTATION AHMED THAKUR

3.1.1 USER-DEFINED DATA TYPES

set([])

Iteration over Sets


We can also have a loop move over each of the items in a set. However, since sets are unordered,
it is undefined which order the iteration will follow.

>>> s = set("blerg")
>>> for n in s:
... print n,
...
r b e l g

Set Operations
Python allows us to perform all the standard mathematical set operations, using members of set.
Note that each of these set operations has several forms. One of these forms, s1.function(s2) will
return another set which is created by "function" applied to S1 and S2. The other form,
s1.function_update(s2), will change S1 to be the set created by "function" of S1 and S2. Finally, some
functions have equivalent special operators. For example, s1 & s2 is equivalent to s1.intersection(s2)

Intersection
Any element which is in both S1 and S2 will appear in their intersection.

>>> s1 = set([4, 6, 9])


>>> s2 = set([1, 6, 8])
>>> s1.intersection(s2)
set([6])
>>> s1 & s2
set([6])
>>> s1.intersection_update(s2)
>>> s1
set([6])

Union
The union is the merger of two sets. Any element in S1 or S2 will appear in their union.

>>> s1 = set([4, 6, 9])


>>> s2 = set([1, 6, 8])
>>> s1.union(s2)
set([1, 4, 6, 8, 9])
>>> s1 | s2
set([1, 4, 6, 8, 9])

Note that union's update function is simply "update" above.

Symmetric Difference
The symmetric difference of two sets is the set of elements which are in one of either set, but not in
both.

COMPUTER SCIENCE https://www.facebook.com/groups/OAComputers/


ahmed_thakur@hotmail.com, 0300-8268885 Page 7
9608
3.1 DATA REPRESENTATION AHMED THAKUR

3.1.1 USER-DEFINED DATA TYPES

>>> s1 = set([4, 6, 9])


>>> s2 = set([1, 6, 8])
>>> s1.symmetric_difference(s2)
set([8, 1, 4, 9])

>>> s1 ^ s2
set([8, 1, 4, 9])
>>> s1.symmetric_difference_update(s2)
>>> s1
set([8, 1, 4, 9])

Set Difference
Python can also find the set difference of and , which is the elements that are in but not
in .

>>> s1 = set([4, 6, 9])


>>> s2 = set([1, 6, 8])
>>> s1.difference(s2)
set([9, 4])
>>> s1 - s2
set([9, 4])
>>> s1.difference_update(s2)
>>> s1
set([9, 4])

Multiple sets
Starting with Python 2.6, "union", "intersection", and "difference" can work with multiple input by using
the set constructor. For example, using "set.intersection()":

>>> s1 = set([3, 6, 7, 9])


>>> s2 = set([6, 7, 9, 10])
>>> s3 = set([7, 9, 10, 11])
>>> set.intersection(s1, s2, s3)
set([9, 7])

frozenset
A frozenset is basically the same as a set, except that it is immutable - once it is created, its members
cannot be changed. Since they are immutable, they are also hashable, which means that frozensets
can be used as members in other sets and as dictionary keys. frozensets have the same functions as
normal sets, except none of the functions that change the contents (update, remove, pop, etc.)
are available.

>>> fs = frozenset([2, 3, 4])


>>> s1 = set([fs, 4, 5, 6])
>>> s1
set([4, frozenset([2, 3, 4]), 6, 5])
>>> fs.intersection(s1)

COMPUTER SCIENCE https://www.facebook.com/groups/OAComputers/


ahmed_thakur@hotmail.com, 0300-8268885 Page 8
9608
3.1 DATA REPRESENTATION AHMED THAKUR

3.1.1 USER-DEFINED DATA TYPES

frozenset([4])
>>> fs.add(6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'

Exercises
1. Create the set {'cat', 1, 2, 3}, call it s.
2. Create the set {'c', 'a', 't', '1', '2', '3'}.
3. Create the frozen set {'cat', 1, 2, 3}, call it fs.
4. Create a set containing the frozenset fs, it should look like {frozenset({'cat', 2, 3, 1})}.

Record - a value that contains other values, indexed by names

Field - an element of a record

Records are collections of data items (fields) stored about something. They allow you to combine
several data items (or fields) into one variable. An example at your college they will have a database
storing a record for each student. This student record would contain fields such as ID, Name and
Date of Birth. The following example that DOESN'T USE RECORDS might be simple enough for one
student:

Dim studentID As Integer


Dim studentName As String
Dim studentDoB As Date

Sub Main()
Console.write("insert the id: ")
newStudentid = console.readline()
console.write("insert the name: ")
newStudentname = console.readline()
console.write("insert the Date of Birth: ")
newStudentDoB = console.readline()

console.writeline("new record created: " & newStudentid & " " &
newStudentname & " " & newStudentDoB)
End Sub

For the following input:

COMPUTER SCIENCE https://www.facebook.com/groups/OAComputers/


ahmed_thakur@hotmail.com, 0300-8268885 Page 9
9608
3.1 DATA REPRESENTATION AHMED THAKUR

3.1.1 USER-DEFINED DATA TYPES

But what if your college has more than one student, we'd have to write:

Dim studentID1 As Integer 'field


Dim studentName1 As String 'field
Dim studentDoB1 As Date 'field
Dim studentID2 As Integer 'field
Dim studentName2 As String 'field
Dim studentDoB2 As Date 'field
Dim studentID3 As Integer 'field
Dim studentName3 As String 'field
Dim studentDoB3 As Date 'field
...
...
Dim studentID2400 As Integer 'field
Dim studentName400 As String 'field
Dim studentDoB400 As Date 'field

It would take an awfully long time to declare them all, let alone saving writing data to them. So how
do we solve this? Well we need to combine two things we have learnt about so far, the record and
the array. We are going to make an array of student records:

Structure student 'record declaration


Dim id As Integer 'field
Dim name As String 'field
Dim DoB As Date 'field
End Structure

Sub Main()
Dim newStudents(400) As student 'declare an array of student
records, a school with 401 students

for x = 0 to 400 'insert the details for each student


Console.WriteLine("insert the id")
newStudents(x).id = Console.ReadLine()
Console.WriteLine("insert the name")

COMPUTER SCIENCE https://www.facebook.com/groups/OAComputers/


ahmed_thakur@hotmail.com, 0300-8268885 Page 10
9608
3.1 DATA REPRESENTATION AHMED THAKUR

3.1.1 USER-DEFINED DATA TYPES

newStudents(x).name = Console.ReadLine()
Console.WriteLine("insert the Date of Birth")
newStudents(x).DoB = Console.ReadLine()
next
for x = 0 to 400 'print out each student
Console.WriteLine("new record created: " & newStudents(x).id & "
" & newStudents(x).name & " " & newStudents(x).DoB)
next
End Sub

This seems to solve our problem, you might want to try it out yourself but decrease the number of
students slightly!

Exercise: Records
Declare a record called player to store the following Role Playing Game attributes: health,
name, characterclass (barbarian, wizard, elf), gold, gender

Answer

Enum type
WIZARD
BARBARIAN
ELF
End Enum

Structure player 'remember Visual Basic uses structure instead of record


name as string
health as integer
gold as integer
gender as char
' class as string ' you might have already noticed, the word class is
'reserved'
' this means it is has a special purpose in VBNET and we'll have to use
another
characterclass as type 'a string would work, but it's better to use an enum
End player

Exercise
Creates 2 characters, Gandolf and Conan using the player record

Answer :

'you can of course give them different attributes


Dim Gandolf As player

COMPUTER SCIENCE https://www.facebook.com/groups/OAComputers/


ahmed_thakur@hotmail.com, 0300-8268885 Page 11
9608
3.1 DATA REPRESENTATION AHMED THAKUR

3.1.1 USER-DEFINED DATA TYPES

Gandolf.name = "Gandolf"
Gandolf.health = 70
Gandolf.gold = 50
Gandolf.gender = "m"
Gandolf.characterclass = type.WIZARD

Dim Conan As player


Conan.name = "Conan"
Conan.health = 100
Conan.gold = 30
Conan.gender = "m"
Conan.characterclass = type.BARBARIAN

CLASS
In object-oriented programming , a class is a template definition of the method s and variable s in a
particular kind of object . Thus, an object is a specific instance of a class; it contains real values
instead of variables.

Classes
Structures are very similar to Classes in that they collect data together. However, classes extend this
idea and are made from two different things:

Attributes - things that the object stores data in, generally variables.

Methods - Functions and Procedures attached to an Object and allowing the object to perform
actions

Let's take a look at the following example:

class car
private maxSpeed as integer
public fuel as integer

COMPUTER SCIENCE https://www.facebook.com/groups/OAComputers/


ahmed_thakur@hotmail.com, 0300-8268885 Page 12
9608
3.1 DATA REPRESENTATION AHMED THAKUR

3.1.1 USER-DEFINED DATA TYPES

public sub setSpeed(byVal s as integer)


maxSpeed = s
end sub
public function getSpeed() as integer
return maxSpeed
end function
public sub refuel(byVal x as integer)
console.writeline("pumping gas!")
fuel = fuel + x
end sub
public function getFuel() as integer
return fuel
end function
public sub drive()
fuel = fuel - 1
end sub
end class

You can see that the class is called car and it has:

 two attributes: maxSpeed, fuel


 five methods
 three procedures: setSpeed, refuel, drive
 two functions: getSpeed, getFuel

Remember this is a class and therefore only a template, we need to 'create' it using an object

Attributes
These store information about the object. In the example above we store the fuel and maxSpeed.
The attributes are attached to the classes, and if there are several instances (objects) of the classes
then each will store its own version of these variables. Note that instead of the usual dim, there is the
word private or public, we'll cover that in the encapsulation section.

Methods

COMPUTER SCIENCE https://www.facebook.com/groups/OAComputers/


ahmed_thakur@hotmail.com, 0300-8268885 Page 13
9608
3.1 DATA REPRESENTATION AHMED THAKUR

3.1.1 USER-DEFINED DATA TYPES

Unlike structures, OOP allows you to attach functions and procedures to your code. This means that
not only can you store details about you car (the attributes), you can also allow for sub routines such
as drive() and refuel, which are attached to each class.

1. Question:
What is the difference between a class and an object?

Answer :
 A class is a template which cannot be executed
 An object is an instance of a class which can be executed
 one class can be used to make many objects

2. Question:
What are the main components of a class?

Answer :
methods and attributes

3. Question:
What is the difference between a structure and a class

Answer :
Structures don't have methods

Premitive Data Type: either of the following:


 A basic type is a data type provided by a programming language as a basic building block.
Most languages allow more complicated composite types to be recursively constructed starting
from basic types.
 A built-in type is a data type for which the programming language provides built-in support.

In most programming languages, all basic data types are built-in. In addition, many languages also
provide a set of composite data types. Opinions vary as to whether a built-in type that is not basic
should be considered "primitive"

Classic basic primitive types may include:


 Character (character, char);
 Integer (integer, int, short, long, byte) with a variety of precisions;
 Floating-point number (float, double, real, double precision);
 Fixed-point number (fixed) with a variety of precisions and a programmer-selected scale.
 Boolean, logical values true and false.
 Reference (also called a pointer or handle), a small value referring to another object's address
in memory, possibly a much larger one.

COMPUTER SCIENCE https://www.facebook.com/groups/OAComputers/


ahmed_thakur@hotmail.com, 0300-8268885 Page 14
9608

S-ar putea să vă placă și