You are on page 1of 19

1

Project Assignment- First


Q1. Explain the Panging and Segmentation
Paging is used to get a large linear address space without having to
buy more physical memory. Segmentation allows programs and
data to be broken up into logically independent address spaces and
to aid sharing and protection.

Paging does not distinguish and protect procedures and data


separately.
Segmentation distinguishes and separately protects procedures and
data.

Unlike segmentation, Paging does not facilitate sharing of


procedures.

Paging is transparent to programmers(system handles it


automatically).
Segmentation requires programmer to be aware of memory limits
as programmer
tries to allocate memory to functions and variables or tries to access
read
only memory violation, which results in segmentation fault
(see Segmentation fault for more details on different types of seg.
faults)

Mapping from logical to physical address is different for paging and


segmentation.

Here's an illustration based on 16 bit-address space:


For paging :
The 6-bit page value is used to select a proper entry in process page
table. the 6-bit process entry occupying the six most significant bit
and the 10-bit offset occupying the 10 least significant bit forms a
16-bit physical address.
2

Following are the differences between paging and segmentation.

Sr. No. Paging Segmentation

1 A page is a physical unit of information. A segment is a logical unit of


information.

2 A page is invisible to the user's program. A segment is visible to the user's


program.

3 A page is of fixed size e.g. 4Kbytes. A segment is of varying size.

4 The page size is determined by the A segment size is determined by


machine architecture. the user.

5 Fragmentation may occur. Segmentation eliminates


fragmentation.

6 Page frames on main memory are No frames are required.


required.

Q2. Explain data Encryption and Cryptography Technique?

Cryptography ?
Cryptography defined as "the science and study of secret writing," concerns the
ways in which communications and data can be encoded to prevent disclosure of
their contents through eavesdropping or message interception, using codes (2),
ciphers (3), and other methods, so that only certain people can see the real
message. Although the science of cryptography is very old, the desktop-computer
revolution has made it possible for cryptographic techniques to become widely
used and accessible to nonexperts. David Kahn traces the history of cryptography
from Ancient Egypt into the computer age (4). According to Kahn's research from
Julius Caesar to Mary, Queen of Scots (5) to Abraham Lincoln's Civil War ciphers,
cryptography has been a part of the history. Over the centuries complex computer-
based codes, algorithms and machines were created. During World War I, the
Germans developed the Enigma machine to have secure communications (6).
Enigma codes were decrypted under the secret Ultra project during World War II
by the British.
3

What is Encryption ?
"Encryption is basically an indication of users' distrust of the security of the
system, the owner or operator of the system, or law enforcement
authorities." (7)

Encryption transforms original information, called plaintext or cleartext, into


transformed information, called ciphertext, codetext or simply cipher, which
usually has the appearance of random, unintelligible data. The transformed
information, in its encrypted form, is called the cryptogram. (8)

Encryption algorithm determines how simple or how complex the process of


transformation will be (9). Encryption provides confidentiality, integrity and
authenticity of the information transferred from A to B. It will be a secret
transmission ensuring that its integrity has not been tampered and also it is
authentic, that the information was sent by A. All these three points may be
important for different reasons for the transmission of data over the Internet (10).

Who needs Cryptography ?


The ability to protect and secure information is vital to the growth of electronic
commerce and to the growth of the Internet itself. Many people need or want to use
communications and data security in different areas. Banks use encryption methods
all around the world (11) to process financial transactions. These involve transfer
of huge amount of money from one bank to another. Banks also use encryption
methods to protect their customers ID numbers at bank automated teller machines.

"As the economy continues to move away from cash transactions towards
"digital cash", both customers and merchants will need the authentication
provided by unforgeable digital signatures in order to prevent forgery and
transact with confidence." (12)

This is an important issue related to the Internet users. There are many companies
and even shopping malls selling anything from flowers to bottles of wines over the
Internet and these transactions are made by the use of credit cards and secure
Internet browsers including encryption techniques. The customers over the Internet
would like to be secure about sending their credit card information and other
financial details related to them over a multi-national environment. It will only
work by the use of strong and unforgeable encryption methods.

Also business and commercial companies with trade secrets use or would like to
use encryption against high-tech eavesdropping and industrial espionage.
Professionals such as lawyers, doctors, dentists or accountants who have
4

confidential information throughout their activities will need encryption if they


will rely on the use of Internet in the future. Criminals do use encryption and will
use it to cover their illegal activities and to make untraceable perfect crimes
possible. More important, people need or desire electronic security from
government intrusions or surveillance (13) into their activites on the Internet.

Cryptographic Keys: Private and Public


More complex ciphers use a secret key to control a long sequence of complicated
substitutions (14) and transpositions (15). There are two general categories of
cryptographic keys: Private key and public key systems.

Private Key Cryptography

Private key systems use a single key. The single key is used both to encrypt and
decrypt the information. Both sides of the transmission need a separate key and the
key must be kept secret from. The security of the transmission will depend on how
well the key is protected. The US Government developed the Data Encryption
Standard ("DES") which operates on this basis and it is the actual US standard.
DES keys are 56 bits (16) long. The length of the key was criticised and it was
suggested that the short key was designed to be long enough to frustrate corporate
eavesdroppers, but short enough to be broken by the National Security Agency
("NSA") (17). Export of DES is controlled by the State Department. DES system is
getting old and becoming insecure. US government offered to replace the DES
with a new algorithm called Skipjack which involves escrowed encryption.

Public Key Cryptography

In the public key system there are two keys: a public and a private key. Each user
has both keys and while the private key must be kept secret the public key is
publicly known. Both keys are mathematically related. If A encrypts a message
with his private key then B, the recipient of the message can decrypt it with A's
public key. Similarly anyone who knows A's public key can send him a message by
encrypting it with his public key. A will than decrypt it with his private key. Public
key cryptography was developed in 1977 by Rivest, Shamir and Adleman ("RSA")
in the US. This kind of cryptography is more eficient than the private key
cryptography because each user has only one key to encrypt and decrypt all the
messages that he or she sends or receives.

Project Assignment- Second


Q1. Explain Semaphore and its operation in brief?
5

Answer: Dijkestra proposed a significant technique for managing


concurrent processes for complex mutual exclusion problems. He
introduced a new synchronization tool called Semaphore.

Semaphores are of two types

1. Binary semaphore

2. Counting semaphore

Binary semaphore can take the value 0 & 1 only. Counting semaphore
can take nonnegative integer values.

Two standard operations, wait and signal are defined on the semaphore.
Entry to the critical section is controlled by the wait operation and exit
from a critical region is taken care by signal operation. The wait, signal
operations are also called P and V operations. The manipulation of
semaphore (S) takes place as following:

1. The wait command P(S) decrements the semaphore value by 1. If the resulting value becomes
negative then P command is delayed until the condition is satisfied.

2. The V(S) i.e. signals operation increments the semaphore value by 1.

Mutual exclusion on the semaphore is enforced within P(S) and V(S). If a


number of processes attempt P(S) simultaneously, only one process will
be allowed to proceed & the other processes will be waiting.These
operations are defined as under

P(S) or wait(S):
If S > 0 then

Set S to S-1
Else

Block the calling process (i.e. Wait on S)

V(S) or signal(S):
If any processes are waiting on S

Start one of these processes


Else

Set S to S+1

The semaphore operation are implemented as operating system services


and so wait and signal are atomic in nature i.e. once started, execution
of these operations cannot be interrupted.

Thus semaphore is a simple yet powerful mechanism to ensure mutual


exclusion among concurrent processes.
6

Q2. Explain the methods of handling Deadlocks in


brief.
What are Deadlocks?
Deadlock is a state of a database system having two or more
transactions, when each transaction is waiting for a data item that is
being locked by some other transaction. A deadlock can be indicated by a
cycle in the wait-for-graph. This is a directed graph in which the vertices
denote transactions and the edges denote waits for data items.

For example, in the following wait-for-graph, transaction T1 is waiting for


data item X which is locked by T3. T3 is waiting for Y which is locked by
T2 and T2 is waiting for Z which is locked by T1. Hence, a waiting cycle is
formed, and none of the transactions can proceed executing.

Deadlock Handling in Centralized Systems


There are three classical approaches for deadlock handling, namely

Deadlock prevention.

Deadlock avoidance.

Deadlock detection and removal.

All of the three approaches can be incorporated in both a centralized and


a distributed database system.

Deadlock Prevention
The deadlock prevention approach does not allow any transaction to
acquire locks that will lead to deadlocks. The convention is that when
more than one transactions request for locking the same data item, only
one of them is granted the lock.

One of the most popular deadlock prevention methods is pre-acquisition


of all the locks. In this method, a transaction acquires all the locks before
starting to execute and retains the locks for the entire duration of
7

transaction. If another transaction needs any of the already acquired


locks, it has to wait until all the locks it needs are available. Using this
approach, the system is prevented from being deadlocked since none of
the waiting transactions are holding any lock.

Deadlock Avoidance
The deadlock avoidance approach handles deadlocks before they occur. It
analyzes the transactions and the locks to determine whether or not
waiting leads to a deadlock.

The method can be briefly stated as follows. Transactions start executing


and request data items that they need to lock. The lock manager checks
whether the lock is available. If it is available, the lock manager allocates
the data item and the transaction acquires the lock. However, if the item
is locked by some other transaction in incompatible mode, the lock
manager runs an algorithm to test whether keeping the transaction in
waiting state will cause a deadlock or not. Accordingly, the algorithm
decides whether the transaction can wait or one of the transactions
should be aborted.

There are two algorithms for this purpose, namely wait-die and wound-
wait. Let us assume that there are two transactions, T1 and T2, where
T1 tries to lock a data item which is already locked by T2. The algorithms
are as follows

Wait-Die If T1 is older than T2, T1 is allowed to wait. Otherwise, if T1 is younger than T2, T1 is
aborted and later restarted.

Wound-Wait If T1 is older than T2, T2 is aborted and later restarted. Otherwise, if T1 is younger
than T2, T1 is allowed to wait.

Deadlock Detection and Removal


The deadlock detection and removal approach runs a deadlock detection
algorithm periodically and removes deadlock in case there is one. It does
not check for deadlock when a transaction places a request for a lock.
When a transaction requests a lock, the lock manager checks whether it
is available. If it is available, the transaction is allowed to lock the data
item; otherwise the transaction is allowed to wait.

Since there are no precautions while granting lock requests, some of the
transactions may be deadlocked. To detect deadlocks, the lock manager
periodically checks if the wait-forgraph has cycles. If the system is
deadlocked, the lock manager chooses a victim transaction from each
cycle. The victim is aborted and rolled back; and then restarted later.
Some of the methods used for victim selection are

Choose the youngest transaction.


8

Choose the transaction with fewest data items.

Choose the transaction that has performed least number of updates.

Choose the transaction having least restart overhead.

Choose the transaction which is common to two or more cycles.

This approach is primarily suited for systems having transactions low and
where fast response to lock requests is needed.

Deadlock Handling in Distributed Systems


Transaction processing in a distributed database system is also
distributed, i.e. the same transaction may be processing at more than
one site. The two main deadlock handling concerns in a distributed
database system that are not present in a centralized system
are transaction location and transaction control. Once these
concerns are addressed, deadlocks are handled through any of deadlock
prevention, deadlock avoidance or deadlock detection and removal.

Transaction Location
Transactions in a distributed database system are processed in multiple
sites and use data items in multiple sites. The amount of data processing
is not uniformly distributed among these sites. The time period of
processing also varies. Thus the same transaction may be active at some
sites and inactive at others. When two conflicting transactions are located
in a site, it may happen that one of them is in inactive state. This
condition does not arise in a centralized system. This concern is called
transaction location issue.

This concern may be addressed by Daisy Chain model. In this model, a


transaction carries certain details when it moves from one site to
another. Some of the details are the list of tables required, the list of
sites required, the list of visited tables and sites, the list of tables and
sites that are yet to be visited and the list of acquired locks with types.
After a transaction terminates by either commit or abort, the information
should be sent to all the concerned sites.

Transaction Control
Transaction control is concerned with designating and controlling the
sites required for processing a transaction in a distributed database
system. There are many options regarding the choice of where to process
the transaction and how to designate the center of control, like

One server may be selected as the center of control.

The center of control may travel from one server to another.


9

The responsibility of controlling may be shared by a number of servers.

Distributed Deadlock Prevention


Just like in centralized deadlock prevention, in distributed deadlock
prevention approach, a transaction should acquire all the locks before
starting to execute. This prevents deadlocks.

The site where the transaction enters is designated as the controlling


site. The controlling site sends messages to the sites where the data
items are located to lock the items. Then it waits for confirmation. When
all the sites have confirmed that they have locked the data items,
transaction starts. If any site or communication link fails, the transaction
has to wait until they have been repaired.

Though the implementation is simple, this approach has some drawbacks

Pre-acquisition of locks requires a long time for communication delays. This increases the time
required for transaction.

In case of site or link failure, a transaction has to wait for a long time so that the sites recover.
Meanwhile, in the running sites, the items are locked. This may prevent other transactions from
executing.

If the controlling site fails, it cannot communicate with the other sites. These sites continue to keep
the locked data items in their locked state, thus resulting in blocking.

Distributed Deadlock Avoidance


As in centralized system, distributed deadlock avoidance handles
deadlock prior to occurrence. Additionally, in distributed systems,
transaction location and transaction control issues needs to be
addressed. Due to the distributed nature of the transaction, the following
conflicts may occur

Conflict between two transactions in the same site.

Conflict between two transactions in different sites.

In case of conflict, one of the transactions may be aborted or allowed to


wait as per distributed wait-die or distributed wound-wait algorithms.

Let us assume that there are two transactions, T1 and T2. T1 arrives at
Site P and tries to lock a data item which is already locked by T2 at that
site. Hence, there is a conflict at Site P. The algorithms are as follows

Distributed Wound-Die

o If T1 is older than T2, T1 is allowed to wait. T1 can resume execution after Site P receives a
message that T2 has either committed or aborted successfully at all sites.
10

o If T1 is younger than T2, T1 is aborted. The concurrency control at Site P sends a message
to all sites where T1 has visited to abort T1. The controlling site notifies the user when T1
has been successfully aborted in all the sites.

Distributed Wait-Wait

o If T1 is older than T2, T2 needs to be aborted. If T2 is active at Site P, Site P aborts and rolls
back T2 and then broadcasts this message to other relevant sites. If T2 has left Site P but is
active at Site Q, Site P broadcasts that T2 has been aborted; Site L then aborts and rolls
back T2 and sends this message to all sites.

o If T1 is younger than T1, T1 is allowed to wait. T1 can resume execution after Site P receives
a message that T2 has completed processing.

Distributed Deadlock Detection


Just like centralized deadlock detection approach, deadlocks are allowed
to occur and are removed if detected. The system does not perform any
checks when a transaction places a lock request. For implementation,
global wait-for-graphs are created. Existence of a cycle in the global
wait-for-graph indicates deadlocks. However, it is difficult to spot
deadlocks since transaction waits for resources across the network.

Alternatively, deadlock detection algorithms can use timers. Each


transaction is associated with a timer which is set to a time period in
which a transaction is expected to finish. If a transaction does not finish
within this time period, the timer goes off, indicating a possible deadlock.

Another tool used for deadlock handling is a deadlock detector. In a


centralized system, there is one deadlock detector. In a distributed
system, there can be more than one deadlock detectors. A deadlock
detector can find deadlocks for the sites under its control. There are
three alternatives for deadlock detection in a distributed system, namely.

Centralized Deadlock Detector One site is designated as the central deadlock detector.

Hierarchical Deadlock Detector A number of deadlock detectors are arranged in hierarchy.

Distributed Deadlock Detector All the sites participate in detecting deadlocks and removing
them.

Subject V- Database Management Systems


Project Assignment- First
Q. 1 Draw an E- R Diagram for a Library Automation
System.
11

Q. 2 What is Functional Dependencies? Explain


Anomalies

Functional Dependency
Functional dependency (FD) is a set of constraints between two
attributes in a relation. Functional dependency says that if two tuples
have same values for attributes A1, A2,..., An, then those two tuples
must have to have same values for attributes B1, B2, ..., Bn.

Functional dependency is represented by an arrow sign () that is, XY,


where X functionally determines Y. The left-hand side attributes
determine the values of attributes on the right-hand side.

Normalization
If a database design is not perfect, it may contain anomalies, which are
like a bad dream for any database administrator. Managing a database
with anomalies is next to impossible.

Update anomalies If data items are scattered and are not linked to each other properly, then it
could lead to strange situations. For example, when we try to update one data item having its copies
scattered over several places, a few instances get updated properly while a few others are left with
old values. Such instances leave the database in an inconsistent state.

Deletion anomalies We tried to delete a record, but parts of it was left undeleted because of
unawareness, the data is also saved somewhere else.

Insert anomalies We tried to insert data in a record that does not exist at all.

Normalization is a method to remove all these anomalies and bring the


database to a consistent state.

Project Assignment- Second


Q. 1 What is Object Oriented Data Model?
12

Object Oriented Database (OODB) provides all the facilities associated with object oriented
paradigm. It enables us to create classes, organize objects, structure an inheritance hierarchy and
call methods of other classes. Besides these, it also provides the facilities associated with standard
database systems. However, object oriented database systems have not yet replaced the RDBMS
in commercial business applications.

Following are the two different approaches for designing an object-oriented


database:

Designed to store, retrieve and manage objects created by programs written in some object
oriented languages (OOL) such as C++ or java.

Although a relational database can be used to store and manage objects, it does not understand
objects as such. Therefore, a middle layer called object manager or object-oriented layer software
is required to translate objects into tuples of a relation .

Designed to provide object-oriented facilities to users of non object-oriented programming


languages (OOPLs) such as C or Pascal.

The user will create classes, objects, inheritance and so on and the database system will store and
manage these objects and classes. This second approach, thus, turns non-OOPLs into OOPLs. A
translation layer is required to map the objects created by user into objects of the database
system.

Advantages and Disadvantages of OODBMSS

OODBMSs can provide appropriate solutions for many types of advanced database applications.
However, there are also disadvantages.

Enriched modeling capabilities

The object-oriented data model allows the 'real world' to be modeled more closely. The object,
which encapsulates both state and behavior, is a more natural and realistic representation of real-
world objects. An object can store all the relationships it has with other objects, including many-
to-many relationships, and objects can be formed into complex objects that the traditional data
models cannot cope with easily.

Extensibility

OODBMSs allow new data types to be built from existing types. The ability to factor out common
properties of several classes and form them into a superclass that can be shared with subclasses
can greatly reduce redundancy within system is regarded as one of the main advantages of object
orientation. Further, the reusability of classes promotes faster development and easier
maintenance of the database and its applications.

Capable of handling a large variety of data types


13

Unlike traditional databases (such as hierarchical, network or relational), the object oriented
database are capable of storing different types of data, for example, pictures, voice video,
including text, numbers and so on.

Removal of impedance mismatch

A single language interface between the Data Manipulation Language (DML) and the
programming language overcomes the impedance mismatch. This eliminates many of the
efficiencies that occur in mapping a declarative language such as SQL to an imperative 'language
such as 'C'. Most OODBMSs provide a DML that is computationally complete compared with SQL,
the 'standard language of RDBMSs.

More expressive query language

Navigational access from the object is the most common form of data access in an OODBMS. This
is in contrast to the associative access of SQL (that is, declarative statements with selection based
on one or more predicates). Navigational access is more suitable for handling parts explosion,
recursive queries, and so on.

Support for schema evolution

The tight coupling between data and applications in an OODBMS makes schema evolution more
feasible.

Support for long-duration, transactions

Current relational DBMSs enforce serializability on concurrent transactions to maintain database


consistency. OODBMSs use a different protocol to handle the types of long-duration transaction
that are common in many advanced database application.

Applicability to advanced database applications

There are many areas where traditional DBMSs have not been particularly successful, such as,
Computer-Aided Design (CAD), Computer-Aided Software Engineering (CASE), Office
Information System(OIS), and Multimedia Systems. The enriched modeling capabilities of
OODBMSs have made them suitable for these applications.

Improved performance

There have been a number of benchmarks that have suggested OODBMSs provide significant
performance improvements over relational DBMSs. The results showed an average 30-fold
performance improvement for the OODBMS over the RDBMS.

Disadvantages of OODBMSs

There are following disadvantages of OODBMSs:


14

Lack of universal data model: There is no universally agreed data model for an OODBMS,
and most models lack a theoretical foundation. This .disadvantage is seen as a significant
drawback, and is comparable to pre-relational systems.

Lack of experience: In comparison to RDBMSs the use of OODBMS is still relatively limited.
This means that we do not yet have the level of experience that we have with traditional systems.
OODBMSs are still very much geared towards the programmer, rather than the nave end-user.
Also there is a resistance to the acceptance of the technology. While the OODBMS is limited to a
small niche market, this problem will continue to exist

Lack of standards: There is a general lack of standards of OODBMSs. We have already


mentioned that there is not universally agreed data model. Similarly, there is no standard object-
oriented query language.

Competition: Perhaps one of the most significant issues that face OODBMS vendors is the
competition posed by the RDBMS and the emerging ORDBMS products. These products have an
established user base with significant experience available. SQL is an approved standard and the
relational data model has a solid theoretical formation and relational products have many
supporting tools to help .both end-users and developers.

Query optimization compromises encapsulations: Query optimization requires. An


understanding of the underlying implementation to access the database efficiently. However, this
compromises the concept of incrassation.

Locking at object level may impact performance Many OODBMSs use locking as the basis
for concurrency control protocol. However, if locking is applied at the object level, locking of an
inheritance hierarchy may be problematic, as well as impacting performance.

Complexity: The increased functionality provided by the OODBMS (such as the illusion of a
single-level storage model, pointer sizzling, long-duratipntransactions, version management, and
schema evolution--makes the system more complex than that of traditional DBMSs. In
complexity leads to products that are more expensive and more difficult to use.

Lack of support for views: Currently, most OODBMSs do not provide a view mechanism,
which, as we have seen previously, provides many advantages such as data independence,
security, reduced complexity, and customization.

Lack of support for security: Currently, OODBMSs do not provide adequate security
mechanisms. The user cannot grant access rights on individual objects or classes.

If OODBMSs are to expand fully into the business field, these deficiencies must be rectified.

Q. 2 Explain difference between Outer Join Versus


Inner joins

The INNER JOIN


15

A INNER JOIN creates a new result table by combining column values of


two tables (table1 and table2) based upon the join-predicate. The query
compares each row of table1 with each row of table2 to find all pairs of
rows which satisfy the join-predicate. When the join-predicate is
satisfied, column values for each matched pair of rows of A and B are
combined into a result row.

An INNER JOIN is the most common type of join and is the default type
of join. You can use INNER keyword optionally.

Following is the syntax of INNER JOIN

SELECT ... FROM table1 [INNER] JOIN table2 ON conditional_expression ...

To avoid redundancy and keep the phrasing shorter, INNER JOIN


conditions can be declared with a USING expression. This expression
specifies a list of one or more columns

SELECT ... FROM table1 JOIN table2 USING ( column1 ,... ) ...

A NATURAL JOIN is similar to a JOIN...USING, only it automatically


tests for equality between the values of every column that exists in both
tables

SELECT ... FROM table1 NATURAL JOIN table2...

Based on the above tables, we can write a INNER JOIN as follows

sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT

ON COMPANY.ID = DEPARTMENT.EMP_ID;

Above query will produce the following result

EMP_ID NAME DEPT


---------- ---------- ----------

1 Paul IT Billing
2 Allen Engineerin

7 James Finance

The OUTER JOIN


The OUTER JOIN is an extension of the INNER JOIN. Though SQL
standard defines three types of OUTER JOINs: LEFT, RIGHT, and FULL but
SQLite only supports the LEFT OUTER JOIN.

The OUTER JOINs have a condition that is identical to INNER JOINs,


expressed using an ON, USING, or NATURAL keyword. The initial results
16

table is calculated the same way. Once the primary JOIN is calculated, an
OUTER join will take any unjoined rows from one or both tables, pad
them out with NULLs, and append them to the resulting table.

Following is the syntax of LEFT OUTER JOIN

SELECT ... FROM table1 LEFT OUTER JOIN table2 ON conditional_expression ...

To avoid redundancy and keep the phrasing shorter, OUTER JOIN


conditions can be declared with a USING expression. This expression
specifies a list of one or more columns

SELECT ... FROM table1 LEFT OUTER JOIN table2 USING ( column1 ,... ) ...

Based on the above tables, we can write a inner join as follows

sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT

ON COMPANY.ID = DEPARTMENT.EMP_ID;

Above query will produce the following result

EMP_ID NAME DEPT


---------- ---------- ----------

1 Paul IT Billing
2 Allen Engineerin

Teddy
Mark

David
Kim

7 James Finance

Subject VII-Programming in Visual Basic


Practical Assignment- First
Q.1 Write a program in VB to convert of centigrade to
Fahrenheit and Vice- versa.

Dim c As Double
Dim f As Double
Private Sub CmdClr_Click()
TxtInput.Text =
TxtInput.SetFocus
End Sub

Private Sub Command1_Click()


c = Val(TxtInput.Text)
If Val(c) = 0 And TxtInput = Then
17

MsgBox Enter Any number, vbInformation, Result


TxtInput.SetFocus
Else
f = 9 * c \ 5 + 32
MsgBox Fahrenheit : & & f, vbInformation, Result

End If

End Sub

Private Sub Command2_Click()


f = Val(TxtInput.Text)
If Val(c) = 0 And TxtInput = Then
MsgBox Enter Any number, vbInformation, Result
TxtInput.SetFocus
Else
c = (f 32) * 5 \ 9
MsgBox Celsius : & & c, vbInformation, Result

End If
End Sub

Q.2 Write a program to find the Prime Number?


Private Sub Command1_Click()
Dim N, D As Single
Dim tag As String

N = Val(TxtNumber.Text)

Select Case N
Case Is < 2
Lbl_Answer.Caption = "It is not a prime number"

Case Is = 2
Lbl_Answer.Caption = "It is a prime number"

Case Is > 2
D=2
Do
If N / D = Int(N / D) Then
Lbl_Answer.Caption = "It is not a prime number"
tag = "Not Prime"
Exit Do
End If
D=D+1

Loop While D <= N - 1


If tag <> "Not Prime" Then
Lbl_Answer.Caption = "It is a prime number"
End If
End Select
End Sub
Practical Assignment- Second
Q.1 Write a program for Matrix Multiplication?
Private Sub Command1_Click()
Dim a(2, 2), b(2, 2), c(2, 2)
For i = 0 To 2
18

For j = 0 To 2
a(i, j) = InputBox("ENER THE ELEMENNTS OF 1st MATRIX")
Next j
Next i

For i = 0 To 2
For j = 0 To 2
b(i, j) = InputBox("ENER THE ELEMENNTS OF 2nd MATRIX")
Next j
Next i

For i = 0 To 2
For j = 0 To 2
c(i, j) = 0
For k = 0 To 2
c(i, j) = c(i, j) + a(i, k) * b(k, j)
Next k
Next j
Next i

For i = 0 To 2
For j = 0 To 2
Print c(i, j)
Next j
Next i
End Sub
Q.2 Write a program in VB to find largest and smallest element in
an array.
Module MaxMin

Sub Main()
Dim n, i, min, max As Integer
Console.Write("Enter the number of Elements: ")
n = CInt(Console.ReadLine())
Dim arr(n) As Integer
For i = 0 To n - 1
Console.Write("Enter the " & (i + 1).ToString & "th element: ")
arr(i) = CInt(Console.ReadLine())
Next
Console.WriteLine("Array Contains...")
For i = 0 To n - 1
Console.Write(arr(i) & " ")
Next
min = arr(0)
max = arr(0)
For i = 0 To n - 1
If arr(i) < min Then
min = arr(i)
End If

Next
For i = 0 To n - 1
If arr(i) > max Then
max = arr(i)
End If

Next
Console.WriteLine()
Console.WriteLine("Minimum=" & min)
Console.WriteLine("Maximum=" & max)
Console.ReadLine()
19

End Sub

End Module

You might also like