Computer 12 Class Notes (Book)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 254

f

DATA BASICS
Qi - What is data and information also discuss different operations performed on
data?
Ans .
Data :
* Raw facts and figures are called data ,
* Data is used to perform certain operation in an organization .
* It gives the status of past activities and enables us to make better decisions.
* It is an input for any system .
Example: Data may be numerical like inventory figures, test scores etc . Data may be
non -numerical like your name and address.
Information:
* Processed data is called Information .
* It is usually output of a process and is meaningful .
* It can be reproduced again and again easily.
Example: The grade of a student in a particular subject in a semester precisely gives the
complete information of the performance of a student.
Operations
Manipulation of data is called operation .
In first step, data can be captured from any source.
Then operations are performed on that data .
After operations data become information .
To convert data into information software is used .
Example : Addition of two numbers . Perform any type of sorting or searching.
Data processing activities
* Manipulation of data to achieve required objectives is called data processing .
* Operations carried out on data to convert it into useful information is called data
processing ,

* Data processing activities can be divided into three categories .


[Ch # i ] Data Basics Computer Science Part-1 ]
1 , Data capturing
* Data must be given to the computer before processing.
* Data can be given to the computer in the form of text using keyboard or in sonic
other shape using some other input device.
2, Data manipulation
* The process to perform various operations on data in order to change its appearance is
called data manipulation.
* Data can be manipulated in the following forms,
• Classification
o Classification includes the division of data in the form of different classes or
groups.
o After this division different codes are assigned to the data .
o These codes can be numeric, alphabetic or alphanumeric .
Example : Students in a college are divided into different sections and the
section name is the code of a particular group/class of students.
• Calculations
o Data can be calculated arithmetically or logically
Example: Addition of two numbers to find the total amount or comparing two
numbers to find which one is the larger
* Sorting
o This involves arrangement of data into a particular sequence to facilitate
processing.
o Arranged data can be in ascending or descending sequence .
Example: For instance, soiling the banks deposits according to account no
will speed up processing. Sorting can also be performed on names as well as
numbers. The people attending the aerobics class can be stored alphabetically
by last names.
* Summarizing
o A large amount of data can be reduced to a concise, usable form.
Example: A top management report summarizing a company’ s accounting
data will help to determine its profit performance.
[Ch # i ] Data Basics Computer Science Part-1 ]
Grades of all students in all classes can be summarized by grade point
average. It helps to find the list of those students who deserve dean ’ s
scholarship .
3. Managing the output results
Output data can be stoned for future use or communicated some where for reproduction.
* Storing and retrieval .
o Data can be stored on some storage device e.g. disk, magnetic tape or
microfilm . This stored data can be used in future as per the requirement.
• Communication and reproduction.
o Data can be communicated to one or more than one destinations at the same time ,

o To communicate or transfer from one place to another a copy of the data is


made and then transmitted.
Q 2. What is a traditional tile system? What are the problems faced in traditional
file system ? Briefly describe the basic units of information.
Ans .
Traditional File System
* A file system is a method for storing and organizing computer files and the data they contain .
* Files are easily accessed using file system.
* It maintains the physical location of the files on storage device.
* The data was kept in files ,

* Each unit of the organization had its own files and each file had a specific set of
programs that were used to manipulate data in that file .
* Each department collects and maintains the required data. This usually resulted in
duplication of data because each record of an employee is maintained by every
department separately.
* Files are stored on storage media .
* Each file consists of records and each record consists of fields. Each field contains
data of one item .
[Ch # i ] Data Basics 4 Computer Science Part-1]

Problems
* Data redundancy

* Data inconsistency
* Data sharing
* Data dependency
* Data security
Basic Units of Information :
Field
* Each column of the table in relational database is called a field.
* Field is a column heading of a table.
Example : Roll Number, Name or Class can be a column heading if we want to store
student ’ s information in a table named student.

Roll Number Name Class


1 Adnan ICS

2 Adil FSc
3 Umer I . Com

Record
[Ch # i ] Data Basics Computer Science Part-1 ]

* A collection of related fields treated as a single unit is ealled a record ,


* In the following table each row of the table is called a record because it is
representing the related data to a particular student.

Roll Number I
Name Adnan
Class ICS
DOB 10 - 03- 1992
Phone 417582

File
* A collection of related records treated as a single unit is called a file or data set ,

* If we collect the information of the students then it becomes the file of student information.

Roll Number 1
Name Adnan
Roll Number 2
Name Adil
Roll Number 3
Name Fazal
Roll Number 4
Name Gafoor
Class TCS
DOB 03 - 04- 1991
Phone 745241

Q3* How data is stored and retrieved in FMS?


Ans .

File organization on storage media


[Ch # i ] Data Basics Computer Science Part-1 ]
Files are organized on storage media for quick and efficient acceess It is also kept
,

in view while organizing files on storage media that how efficient it is to create or delete
a file . To achieve these objectives following points are kept in view .
1. Each file is given a unique name and this name represents the typo of data in a file.
2. This unique name is used to access the file for additions deletions or modifications.
,

3. File is a collection of records and records comprise of fields ,


4. Records in a file are placed next to each other . These records may be of fix length
or variable length ,
5. Each field is given a unique name .
6. The starting address of each field and its length Is used to identify its storage
location.
7. To access the contents of the field its name is used.
[Ch # i ] Data Basics Computer Science Part-1 ]

Q.4 Discuss different types of files.


Ans * There are three wys to classify computer flies
(1) File Types ( Usage Point of View)
(2 ) File Types ( Functional Point of View)
( 3) File Types (Storage Point of View)
File Types (Usage Point of View)
o Master File
These file are latest updated files and never become empty .
When the information in records is changed it is updated in Master Files ,

o Transaction File
In these files data is kept before processing.
These can be temporary files ,
Data in these flies retained till the master Hie is updated ,

o Backup File
These are permanent like master files . It is used to keep copy of data .
These files are created using some software utilities.
These files are used to protect data .
It is usually stored on external storage device.
File Types ( Functional Point of View)
* According to functional point of view files are given proper names like first .doc.
* The first part is called name of file and second is called extension which is assigned
by the software.
0 Program Files
These files contain software instruction . Program files contain source code or object
code.
Example; Source program files and executable files. The extension of source and
executable files are .com and . exe respectively.
o Data Files
These files contain data used by program files.
These files are created by the software being used.
Example: Files having extensions like .daf .doc, - xls, mdb etc .
«

Software File types


Word Processor doc, .rtf
Spread sheet .xls, .wks
Database .dat . dbf and . mdb
ASCII Txt
Image files dif, JP & cps . gif, hmp
?

Audio files wav, mid


,

Video files .avi, .mpg


[Ch # i ] Data Basics Computer Science Part-1 ]

File Organization ( Storage Point of View )


The physical arrangement of records of a file on secondary storage devices is
called file organization . There arc a lot of methods to store files on secondary storage. All
the methods have their own advantages and disadvantages. The different type of file
organizations are.
L Sequential files
2. Direct or random access files
3. Indexed sequential files.
o Sequential Files
These file store data as it arrives one after another in the sequence,
These files take more time to store data,

The data stored in these Hies arc accessed sequentially ,


If you w'ant to go to the last record in a sequential file, you w ill have to read all
the preceding records before reach.
The best reason for using sequential files is their degree of portability to other
programs.
The file organization is very efficient when large number of records are accessed
sequentially .
The drawback of sequential files is that you only have sequential access to your
data. You access one line at a time, starting with the first line
,

o Direct or Random Files


Record in this type of file is stored on a calculated address.
Each record is accessed directly.
These are stored in particular location and each location has a unique address,
data is accessed using these addresses.
In random files the data is stored exactly as it appears in memory, thus saving
processing time. This organization is suitable for storing data on disk ,

Random access files can be wasteful of disk space ,

o Indexed Sequential Files


The data in this type of file can be accessed sequentially as well as randomly
based on a key value,
In index sequential file each record is stored along w- ith its location for these
,

perpose index is created to store the location of each record,


Usually the index is created in a new file called index file.
The index file is updated when a record is added or deleted.
Its processing is as fast as random files.
[Ch # i ] Data Basics Computer Science Part-1 ]
As records arc stored in the form of key-pointer pair in the index file, therefore, it
requires more space on the disk as compared to random files.
Q 5. What is a database and DBMS? Give examples of database and facilities of
databases.
A ns .
Databases
* Database is a collection of logically related data stored in an efficient and compact
manner ,

* Ffficient means stored data can be accessed very easily and quickly . Compact means
that stored data takes up as little space as possible ,

* A database is a structured collection of records or data that is stored in a computer so


that a program can consult it to answer queries ,

* The records retrieved in response of queries become information that can be used to
make decisions ,

* All data of an organization is related and database provides the facility to link related
data ,

DBMS:
* The software, which is used to create access and manipulate the database, is called
database management system or DBMS. It controls all the working of the database.
Example :
In a bank there are separate files to keep information about clients and their accounts ,
* Client information
* Account information
* Transactions detail
* Loan Details
The users of the database system has the following facilities *
* Add new files to the system .
* Insert new records in the existing files ,

* Retrieving data form existing files,


* Deleting data from existing files,
* Removing existing files from the database system .
Q .6 What are the ob jectives of databases?
Ans .
[Ch # i ] Data Basics Computer Science Part-1 ]

* A database is a computerized record keeping system , the main objective of this


system is to make sure that the information is available in compact and efficient
manner.
Objectives of Database
There are three main objectives of the database.
* Data integration
o Data integration is the process of combining data residing at different sources and
providing the user with a unified view of these data .
o It means centralization of information. In manual file system data is stored in
many files at different locations . It is difficult to access data from isolated files in
database are information is logically centralized . It means data is stored on
different computer but it logically appears as a single file.
o Data integration is required because of frequency and the high data volume
increased usage.
* Data integrity
o Data integrity refers to the correctness and consistency of data in a database.
o Data integrity is related with quality of data. When a database contains any error
it losses its integrity.
o Data integrity is expressed in terms of integrity constraints, These arc the rules
designed to keep the data accurate and consistent.
o Data integrity is related to security and protection. Security means to protect the
data from unauthorized persons while integrity is related with quality of data.
o Ensuring that the data is " whole" or complete . Data is maintained as a single
copy to be more consistent.
Example :
A social security id belongs to a person. If a social security id is not related to a
person , the social security id is orphan data and data is not complete / whole.
* Data interdependence
o Database allows the organization of data to be changed without the need to make
the program again .
o User can easily change data appearance and data structures without modifying
application programs.
Q7 * What are different types of database models? Explain with the help of
diagrams *
Ans .
[Ch # i ] Data Basics Computer Science Part-1 ]
Types of Database Models
Jt is a data structure that a database system uses to store data . There are three
types of Logical Database Models

* Hierarchical Model
o In a hierarchical data model , data are organized into a tree-like structure .

ELECTRONICS

PORTABLE
TELEVISIONS
ELECTRONIC
^

TUBE LCD PLASMA MP3 PLAYERS CD PLAYERS 2 WAY RADIOS

FLASH

o This type of structure is also referred as an “ INVERTED TREE ” with the top
referred as “ ROOT” . It is a model in which data is organized like an
organizational chart . Each node in a chart represents an entity and its subordinate
entity describes the next level of hierarchical tree.

o The structure allows repeating information using parent/child relationships.

o Each parent can have many children but each child only has one parent.
o All attributes of a specific record are listed under an entity type. In a database, an
entity type is the equivalent of a table; each individual record is represented as a
row and an attribute as a column.
o Entity types are related to each other using 1: N mapping , also known as one- to-
many relationships.
o It cannot represent all the relationship between data . Its disadvantage is that it is
very difficult to modify.
[Ch # i ] Data Basics Computer Science Part-1 ]

* Network Model
o This model was developed to overcome the problems of hierarchical model .
o The network model is a database model conceived as a flexible wray of
representing objects and their relationships .
Supplier Part Color

ACME ENGINE RED

DELCO WING GREEN


Supplies has color

o Hierarchical model structures data as a tree of records, with each record having
one parent record and many children. The network model allows each record to
have multiple parent and child records, forming a lattice structure .
o Jn this model any item is directly related to another item. It is slow, complex and
more difficult to maintain.
o It required a complex diagram to present a database. The complexity makes
network database slow and difficult to maintain.

• Relational Model

o Network and hierarchical model were complex and inflexible , Tt is difficult to


expand or modify the database model . So to over come this problem Dr. E . F.
Codd introduced relational model .
o The relational model represents data in lhe form of two-dimension tables
( relations),

o Each table represents some real -world person, place, thing, or event about which
information is collected.
o The organization of data into relational tables is known as the logical view of the database.

o The way the database software physically stores the data on a computer disk
system is called the internal view.
[Ch # i ] Data Basics Computer Science Part-1]

E VTLTf-1 E v ury i -
E v TLIU -2 .
E v TLr y -5

E v MU -3 E vnr -6
^
[Ch # i ] Data Basics 14 Computer Science Part-1 ]

Q8 . Write down the advantages and disadvantages of a Database system.


Ans .
Advantages of Database Systems
* Data Independence
o Physical Implementation of data is separated from application programs ,

o DBMS lies between the application program and database . This properly allows
users lo make changes in database without changing application programs.
A D<]iat>as« Sysfem

Personnel depr ,
Dole base
\
f l i:
Soles aepT
Employee
Custom
Sdfcs
^

i m
Amounting <iepf
inventory
Accounts

• Support Complex Data Relationships


o Complex data structures and database design is sometimes required to store and
access data according to the requirement .
o This complexity enhances the ability to store and retrieve data as per requirement ,

* Provides Better Data Security V

o Access rights like ( read , write, update arid delete ) can be implemented on any data
item in the database
Example: A program or user can be restricted to change the data of a particular
field . A user or program can be granted to view, update and even delete a
particular data item in a database.
• Minimum Data Redundancy :
o Storing of same data at more than one place in a system is called data redundancy .
In a database system , data is integrated into a single, logical structure. Each fact is
stored in only one place. This minimizing of data redundancy increases data
processing speed. It also ensures correctness of data.
* Improved Data Sharing:
o Database is designed as a shared resource . Authorized users arc allowed to use to
database, Thus, many users can access and work on the same data at the same time.
[Ch # i ] Data Basics Computer Science Part-1 ]

* Improved Data Consistency :


o By reducing data redundancy , the data inconsistency is reduced . In a database
management system, each data item is stored , as far as possible, at one place only.
* Data Base Backup ! Recovery
In information technology , backup refers to making copies of data so that these
additional copies may be used to restore the original after a data loss event.
These additional copies are typically called " backups ." Backups are useful primarily
for two purposes:
o To restore a computer to an operational state following a disaster ,

o To restore tiles after they have been accidentally deleted or corrupted .


Recovery is the process of rebuilt the required data by using backup copy .
* Advanced Capabilities
o Advanced capabilities of DBMS include the online and ad -hoc reporting.
o It has the ability to create complex data structures for security purpose.
o It also provides backup/ recovery capabilities which are the primary requirements
of a DBMS .
Disadvantages of Database System

* System Overhead
o Hardware cost is an overhead of using a DBMS.
o A speedy system is required to run the DBMS .
o Even to perform a simple job like reading of data from database may require a
series of complex operations.
* Training of Staff
o DBMS are often complex systems so the training for users to use the DBMS is
required.
o Training is required at all levels, including programming, application
development, and database administration.
o The organization has to be paid a lot of amount for the training of staff to run the
DBMS .
o It is possible that in sufficient training lead a team to develop an in efficient
database.
[Ch # i ] Data Basics Computer Science Part-1 ]
Example: The use of proper and improper indexes for accessing and searching
the database,

* Wrong Selection of Database Environment Can Cause technical problems.

o A change in structure can he costly i f the database is not properly designed

o At this stage migration of data from one DBMS to another is very difficult

o In this way data service need to be suspended while migrating.

o Changes in network and hieraichal databases arc more costly as compare to


relational database systems.

* Data Must Be Considered as a Corporate Resource

o Data in an organization when matured can be used by other organization .

Example : The defaulters list of bank clients can be used by other banks to
approve or disapprove a loan application.

* Conversion Costs

o The existing or older system of data management is called the legacy system . It
usually consists of a traditional file processing system or an older database
technology. The cost of converting an old data management system to a modem
DBMS is usually large.

* Need for Backup and Recovery


o All operations of organization using a database system depend on accuracy and
continuous availability of data . Therefore, comprehensive procedures are needed
to backup for recovery of database .

* Need of Data Dictionary

G It is a database about data and database structures.

o It holds the name, type, range of values, source, and authorization for access for
each data element in the organization's files and databases .

o It also indicates which application programs use that data so that when a change
in a data structure is contemplated a list of affected programs can be generated .
,
[Ch # i ] Data Basics 17 Computer Science Part-1 ]
o This data dictionary is an overhead on the system because the system has to
update and maintain the data dictionary during all other system processes.
[Ch # i ] Data Basics Computer Science Part-1 ]

Q9 * What i $ a DBMS? Also discuss its objectives and features *


Ans *
Database Manai;enient System
G DBMS is a collection of programs that enables you to store, modify, and extract
information from a database.
O There are many different types of DBMS, ranging from small systems that run on
personal computers to huge systems that run on mainframes. The DBMS is used
for large and medium sized organizations having different types of files for
different purposes *

Procedjres
aic standnrte

! l
WUt«
and
finlDfCes
Database
administrator
¥
System
administrator
Da to base
Analysts da signal
m
n
if if T
L
I .'
1

i designs
i
i £ ii Hardware
End users Pro gammer s

use
Asplication
programs
J
J write
DBMS utilities
a

Objectives of DBMS
* Shareability
o Different programs and people must be able to use the same data at the same Lime ,

o Sharing means that information can be stored once and then retrieved by number
of times by authorized users of database. It reduces storage requirements ,
* Availability
Data and Database management system must be easily accessible to every user ,

* Evolvability or Data Growth


[Ch # i ] Data Basics Computer Science Part-1 ]
DBMS must be able to grow according to the user need . It must also be able to cope
with the advancement in business and technology.
• Data integration
o Data integration is the process of combining data residing at different sources and
providing the user with a unified view of these data .
o It means centralization of information . Tn manual file system data is stored in
many files at different locations it is difficult to access data from isolated files in
database information is logically centralized. It means data is stored on different
computer blit it logically appears as a single tile.
* Data integrity
o Ensuring that the data is " whole" or complete . Data is maintained as a single
copy to be more consistent ,

o Data integrity refers to the correctness and consistency of data in a database.


o Data integrity is related with quality of data. When a database contains any error
it losses its integrity.
o Data integrity is related to security and protection. Security means to protect the
data from unauthorized persons while integrity is related with quality of data.
o Data integrity is expressed in terms of integrity constraints. These are the rules
designed to keep the data accurate and consistent.
Features of DBMS
* Data Dictionary
o DBMS uses a file to store the data definition or description of the structure of
database is called data dictionary i .e . data about database.
o It holds the name type, range of values, source, and authorization for access for
,

each data element in the organization's files and databases.


o It also indicates which application programs use that data so that when a change
in a data structure is implemented , a list of affected programs can be generated .

o The data dictionary may be a stand-alone system or an integral part of the DBMS .
Data integrity and accuracy is better ensured in the later case . Using data
dictionary any information about data and database can be obtained.
* Database Engine :
o Database engine is the heart of DBMS It stores, retrieves, and updates the data .
,

Other components of database system rely on the database engine for their
functioning.
* Application Generator :
[Ch # i ] Data Basics Computer Science Part-1 ]
o Application generator is a part of DBMS. It consists of tools that are used to
create a complete database management application . A database application is a
collection of queries, forms and reports that are used to input and output data and
perform various data manipulation operations.
* Form Generator:
o Form generator is used to create data input screens . The form generator enables
developers to build forms by dragging and dropping form components such as
text boxes, radio buttons, check boxes, dropdown menus, etc *

* Query Language
o SQL is a language used to insert , update, retrieve and delete any data item from
the database.
o This language is also used to grant access rights on database.
o This is a standard language used with all relational databases.
o The instruction of this language is English like and easily understandable .
* Report Generator
o A program used to create a report in the form of hard soft copy.
o The report format can be specified by the user .
o This format is very much flexible.
o User can give headings and custom i / e messages on this report .
* Communication and Integration:
o Some database management systems provide special communication and
integration utilities. These are used to import and export data with different
databases running on different computers .
* Utilities
o DBMS utilities are the software programs used to maintain the database by
manipulating the data , records and files.
o Some programs are also used for backup and recovery procedures of the
databases,
* Access Security
o This facility is used to secure the data from unauthorized access ,

o This feature makes the data secure and private ,

o The data security is maintained by access right like password *

* Backup and Recovery


[Ch # i ] Data Basics Computer Science Part-1 ]
o When data is stored in a database there are chances of being lost or destruction by
natural disasters or by some human mistakes.
o The best option in this situation is to take a backup copy of the data.
o And in the case of corruption of data or failure of system database can be
reinstated with backup copy called recovery,
Q . 1 U What are the ob jects or components of database system?
Ans . A database is a computerized record keeping system . Its purpose is to maintain
data and make it available when required .
* Data
o Raw facts and figures are called data ,

o The data in a database is integrated and shared .


o Integrated means that several tiles arc stored as related flics and with minimum
repetition and duplication of data .
o Shared means that the data can be shared among several users , Thus * several users
can use the same data at the same time.
o Ability to maintain integrated and shared data is one of the major advantages of
database systems ,
* Hardware
The physical components of a system it includes
o I/O Devices
o Primary Storage
o Secondary Storage Devices
o I/O Channels
o Processor
* Software
It is a set of programs that are used to perform a specific task .
All kind of programs, which include
o User/System Software
Operating system
Database
DBMS
Application program
o Utilities
[Ch # i ] Data Basics Computer Science Part-1 ]
Backup and recovery
* Personnel
People who involves with the system
o Programmer / Analyst
Analyst determines the end user requirements about the database system.
He develops initial structure of the database.
Programmer then writes application programs with the help of languages .
DBMS and packaged software.
All operations on data are performed with the help of application program .
o End Users
It is the person who uses the database management system for his need .
He must have knowledge of information technology.
He doesn ’ t need to have the detail knowledge of the computer system.
He should be aw are of the usage details of the software he intends to use *

o Database Administrator
A database administrator ( DBA ) is a person who is responsible for the
environmental aspects of a database In general, these include :
*

Recoverability - Creating and testing Backups


Integrity - Verifying or helping to verify data integrity
Security - Defining and /or implementing access controls to the data
Availability - Ensuring maximum uptime
Performance - Ensuring maximum performance given budgetary constraints
Development and testing support - Helping programmers and engineers to
efficiently utilize the database.
\
BASIC CONCEPTS AND
TERMINOLOGY OF DATABASES
01. What is a field, record and file? Also explain that how data is handled ( stored
and accessed ) in file management system ( FMS)?
Ans,
* Field
o A field is a single unit of data stored as part of a database record ,

o Each record is made up of one or more fields which correspond to the columns in
,

a database table.
o Fields are often referred to as attributes .
* Record
o A database record consists of one set of fields for a given relational table ,

o In a relational database, records correspond to rows in each table.


* File
o A collection of related records treated as a single unit is called a tile or a data set .
Data Handling in File Management Systems
o In a file management system data can only be read or written sequentially ,

o A file consists of one or more records ,

o Each record contains one or more field instances ,

o Each field instance can contain a data value.


o Records can be specified iri two different ways iri file management system ,

o The fields have fixed length or they have variable lengths ,

o These stored records can be accessed sequentially or randomly by iheir address.


While storing and retrieving data in FMS following steps are followed ,

o Each file is given a unique name .


o This unique name is used to access the file, additions, deletions and modifications .
[Ch # 2] Basic Concepts and Terminology 36 Computer Science Part-1 ]
o Records in a file are placed next to each other. These records may be of fix length or
variable length .
o Each field is given a unique name ,

o The starting address of each field and its length is used to identify its storage location ,

o To access the contents of the field its name is used .


Fixed length fields
o In this technique length of fields are fixed and specified in application programs ,

o For example a name field is specified a length of 15 characters ,

o This field will occupy 15 bytes in memory even if the name is of less than 15
characters,
o When the fields in a record are of fix length then the record is also of fix length.
Variable length fields
o A variable length field takes as much space as the data required e .g. if a person name
is AM it will take 3 characters in memory ,

o In this method storage space is not wasted.


o In a variable length record the fields are separated using a special character such as
the tab character, the comma , or the pipe character ,
o Sometimes field values are enclosed in quotation marks, and any internal quotation
marks are doubled .
o The most common record delimiter is the newline.
Q 2. What is relational database system ? Also describe its different data elements.
Ans .
Relational Database System
o In relational databases a file structure is defined as a two dimensional array or table
having a unique name in a particular database ,
o All the columns of table are called its fields ,

o Each record is placed in table in the form of row.


o Row is also called tuple or occurrence of the table .
o Here are a few important definitions regarding database and file management
concepts.
Data Elements:
Field , Data Element Data Item, Attributeor Column:
The fields or data items in databases are termed as data items, items, attributes or
columns.
Record, Row or Tuple:
Records in file management structures are termed as rows or tuples in database
structures.
File, Tubie Relation or Data Object:
^
Files or datasets in databases are termed as tables, relations or data objects in
database structures.
[Ch # 2] Basic Concepts and Terminology 37 Computer Science Part-1 ]
Database ;
The collection of tables with some traditional tiles and some other necessary data
objects is termed as a database.
QX What is a relation (table)? Also describe its different properties.
Ans .
Relation / Table
o Table contains the descriptive information about an entity. Table is also called relation .
o Collection of rows and columns is called table . Each intersection of a row and column
is called a cell .
o Each record in a file system becomes a row of a relation in database.
o Each Tecord of file management system is called tuple or occurrence of the tabic in
database management system.
o Each entity is composed of attributes ( fields) and each attribute ( field of a table ) has
only one value,
o Each file in a tile management system corresponds to a table in database management
system .
o File management system corresponds to a database management system .
Entity ;
o Anything about which you want to keep the information in database is called an
entity ,

o Entity can be a person , object, concept or anything about which you can think of ,

o Name of an entity is w ritten in capital letters .


Entity can be defined in a database model like
STUDENT (ROLL NO, NAME, GENDER, ADDRESS, TEL)
Here STUDENT is the name of entity and the attributes of this entity are
ROLL NO, NAME , GENDER, ADDRESS and TEL. This entity is converted
into a table to store data in database.
Column
STUDENT i
ROLL NO NAME GENDER ADDRESS TEL

ROW ->
[Ch # 2] Basic Concepts and Terminology 3« Computer Science Part-1 ]

In above diagram all the attributes are called columns of the table and all the rows
are called records .
STUDENT

ROLL NO NAME GENDER ADDRESS TEL


ST 001 Adil Male Lahore 23435
ST 002 Nida Female Karachi 25482
ST 003 Qamar Male Gu j ranwal a 32654
ST004 Khalid Male Sialkot 78452
Properties of Relation
Relation or tabic is the basis of relational DBMS - A relation must have the
following characteristics .
* No Duplicate Rows
o In a relation no two rows can be the same,
o Actually there is no need to repeat a row -
o There must be one filed which uniquely identifies the row from others which is called
primary key.
* Order of Rows is not significant
o There is no order of rows in a table ,

o At the time of query order can be defined ,

o While inserting data order doesnT matter .


o It enables many uses to share same table without concern how data is organized *

* Order of Columns is not significant


o Order of column like row is not significant.
o New columns can be inserted at the end and columns can be accessed by their
names.
* Attributes have to be Atomic
o All the cells or intersection of a row and columns must have atomic value . An
atomic value cannot be further sub divided.
o Multiple values in a cell are not allowed e .g. name and address should be placed
,

in two different fields or cells ,


Q4- What arc views? Also discuss their uses.
Ans .
Views
[Ch # 2] Basic Concepts and Terminology Computer Science Part-1 ]

* Iii database theory , a view is a virtual or logical table composed of the result set of a
query i .e views are created using SQL statements .
, ,

* It is a dynamic „ virtual table computed from data in the database ,


* In a relational database , a view is not part of the physical schema .
* Changing the data in a table alters the data shown in the view.
Views can provide advantages over tables;
* They can subset the data contained in a table
* They can join and simplify multiple tables into a single virtual table
* View's can act as aggregated tables, where aggregated data ( sum , average etc . ) are
calculated and presented as pail of the data
* Views can hide the complexity of database, for example a view can represent Sales
data of different years after getting it from the different complex tables ,

* View's do not incur any extra storage overhead


* View's can provide extra security from unauthorized users and illegal access .
* Limit the exposure to which a table or tables are exposed to outer world
View' can be created by using SQL statement c .g.
CRREATE VIEW STUD ENT_VIEW AS
SELECT _
STUD NO, STUD NAME> STUD ADDR _
FROM STUDENT
WHERE STUD GENDER- T” ;
The above statement will create a view named STUDLNTV1EW. The view will
retrieve the record of only female students from STUDENT table .
Q 5, What is a key? Also different types of keys ?
Ans .

oA key is a field or set of fields of a database ( typically a relational database ) table


which together form a unique identifier for a database record ( a table entry ).
o The aggregate of these fields is usually referred to simply as Mthc key 11.
o A Key field also defines searches.
o Keys are used to establish relationship among tables .
o Keys are helpful to enforce data integrity .
Types of Keys
* Primary Key
o In a table the attribute or combination of columns that uniquely identify all
possible rows in a table.
[Ch # 2] Basic Concepts and Terminology 40 Computer Science Part-1 ]
o A table can have only one primary key ,

o Primary key cannot be null .


o Each value in primary key attribute must be unique,
o Primary key cannot be changed or removed during database operations ,

o A primary key is identified by underline the attribute name in the relation .


STUDENT (ROLLNO, NAME, GENDER , ADDRESS, TELL)
Example; A Social Security number ( associated with a specific person), ISBN
( associated with a specific book ) student roll number ( associated with only one student in
a class ) .
o In the following example TEACHE R C O D E is primary key field which uniquely
identifies each row in the table.
TEACHF.] 2
TEACHER CODE NAME PHONE ADDRESS
TE004 Prof Ijaz Ahmad 74581 Lahore
TE005 Dr. Aslam Elahi 54821 Karachi
TE 007 Dr. Zahid 32547 Islamabad
TE 009 Prof Arslan 74985 Lahore
* Secondary Key
o Secondary key may or may not be unique field . Some times records are required to
access by a field other than the primary key In these situations another key that is used
is called secondary key.
* Candidate Key /Alternate Key
o A table can have more than one attribute to be qualified as primary key One of
them is selected as primary key and remaining keys are called candidate keys.
o Sometimes a relation has more than one attribute that can be used as the primary
key . In these situations, it is difficult to select a primary key. There can be more
than one unique field or combinations of unique fields in a relation. These keys
are termed as candidate keys or alternate keys ,

* Composite/Concatenate Key
o Composite key consists of two or more than two fields.
o Composite key is also designated as a primary key.
o It is created in a situation when no single field fulfills the property of uniqueness .
To make unique more than one field are combined and used as primary key ,
[Ch # 2] Basic Concepts and Terminology 4i Computer Science Part-1 ]

* Sort/Control Key
o A field or a set of fields in a record that dictate the sequence of the file according
to our requirement .
Example; The sort keys STATE and NAME arrange the table data
alphabetically by name within state . STATE is the major sort key, and NAME
is the minor sort key.
* Foreign Key
o A foreign key is a referential constraint between two tables.
o Foreign key is an attribute of a relation that is used as a primary key another table.
o The tabic that contains a foreign key is called dependent table or child table.
o The table from where foreign key is referred is called parent table or independent
table.
o The foreign key identifies a column or a set of columns in parent table that refers
To a column or set of columns in child table.
o The columns in the parent table must form a primary key or unique key ,

o The values in one row of the child table columns must occur in a single row in the
parent table .
o A rowr in the child table cannot contain values that don 't exist in the parent table ,

o Foreign key and primary key are used to establish relationship between two tables.
o It is also helpful to maintain data integrity.
In the following example teacher table is parent table and student table is child table . In
parent table TEACHER CODE is primary key which is referenced in STUDENT table as
foreign key.
TEACHE 3
TEACHER CODE NAME
TE004 Prof. Ijaz Ahmad
TE 005 Dr. Aslam Elahi
TE 007 Dr. Zahid Mahmood
TE009 Prof. Arslan
STUDENT
ROLL NO NAME TEACHER CODE PHONE STATUS
ST 001 Adil TE 009 58555 Y
[Ch # 2] Basic Concepts and Terminology 42 Computer Science Part-1 ]

ST 007 Tahir TE 004 74542 Y


ST 0Q8 Imran TE 007 78541 N
ST 012 Adnan TE 004 74542 Y
ST034 Qasim TE 005 74646 N
ST038 Zahid TE 009 58555 Y
[Ch # 2] Basic Concepts and Terminology Computer Science Part-1 ]

Q 6. Define the term user? Alsu explain the role of data and database
administrator?
Ans *
The User
* It is the person who uses the database management system for his need .
* He must have knowledge of information technology.
* He doesn ’ t need to have the detail knowledge of the database system .
* He should be aware of the usage details of the installed software..
* He interact with the database through application program .
The Data Administrate) !
* The Data Administrator is the head of the Data Administration ( DA) department He
is responsible for the entire data of an organization.
* The DA department is responsible for the definition , organization , supervision, and
protection of data in order to provide good quality, shareable, and accessible data
throughout the enterprise .
* The DA establishes and implements policies and procedures.
* The Data Administrator manages a staff that is responsible for establishing and
implementing the Data Administration Program.
Responsibilities of Data Administrators mav include the following :
* Coordinate management and users to develop the information models, diagrams and
reports that contribute to the data architecture;
* Maintain the documentation of all components of the data architecture ( conceptual ,
logical and physical models ) through a central data repository;
* Develop policies on data -related activities such as data dictionary, data integrity, data
security, data inventory and data standards.
* Assist Database Administration with backup and recovery integrity checks, etc .
,

* DA serves as bridge between user and data processing staff and he is responsible for
user training.
The Database Administrator
A database administrator ( DBA ) is a person who is responsible for the
environmental aspects of a database . He is responsible for the design , implementation ,
operation , management and maintenance of the database. Ho must bo technically
competent.
Responsibilities of the DBA:
* Installation of software.
* Monitoring of database system .
* Solution of every problem .
[Ch # 2] Basic Concepts and Terminology 44 Computer Science Part-1]

* Recoverability - Creating and testing Backups


* Integrity - Verifying or helping to verify data integrity
* Security - Defining and/or implementing access controls to the data
* Availability - Ensuring maximum uptime
* Performance - Ensuring maximum performance given budgetary constraints
* Development and testing support - Helping programmers and engineers to efficiently
utilize the database.
The role of a database administrator has changed according to the technology of
database management systems ( DBMSs) as well as the needs of the owners of the
databases. For example, although logical and physical database designs are traditionally
the duties of a database analyst or database designer, a DBA may be asked to perform
those duties.
Q .7 What are indexes? What is their usage in FiMS & DBMS ?
Ans *
Indexes
* A database index is a data structure that improves the speed of operations in a table.
* Indexes can be created using one or more columns, providing the basis for both rapid
random lookups and efficient ordering of access to records .
* The disk space required to store the index is typically less than the storage of the table
-
(since indexes usually contains only the key fields according to which the tabic is to
be arranged , and excludes all the other details in the table ) .
In a relational database an index is part of a table created by the system developer/DBA *

* An index is used to locate a record in a file more quickly «

* It is also used to speed up the sotting and searching procedures


* Some indexes are created automatically when relationships are created in related
tables.
* The index may be created on primary key, secondary key and foreign key etc .
* The indexes are stored in index tile .
* DBMS uses these files to improve their performance.
Disadvantage:
[Ch # 2] Basic Concepts and Terminology Computer Science Part-1 ]

* Indexes can slow down the data entry and editing because index file is also updated
each time data is added or modified .
[Ch # a] Basic Concepts and Terminology 46 Computer Science Part-1 ]

Q.8 Discuss data manipulation in a database management system.


Ans.
Data Manipulation in a DBMS
Data manipulation in a database management system is different from data
manipulation in traditional file management system .
* Data is stored and manipulated in a data structure known as relation or table.
* A database may have one or more relations , In a relational database management
system , these relations are related through primary -foreign key pairs.
* DBMS uses indexes to quickly find data stored in relations .
* There are different types of users of a database. Each type of user has a distinct
role in a DBMS. End-users usually access and view' data . Data Administrator
organizes, supervises, and protects data. Database Administrator maintains the
database system .
* SQL is usually used for data manipulation operations . DBMS provides facilities
to insert update and delete the records in the database.
DATABASE DESIGN PROCESS
Ql . What are the different steps involved in analysis stage while designing a
database?
A ns.
The process of study the current system is called analysis, While designing a
database we must consider the following steps. These steps are used at analysis stage
while designing a database.

* Feasibility study
o A feasibility study is a preliminary study which determines and documents a
database’s practicality.
o Before developing a new system it is analyzed that either the new system
economically, technically and operationally feasible or not . The results of this
study includes;
The area of identification and selection of boundaries of the
database.
What is the cost of new system?
How much time is required to complete the system?
What the newr system will return ?
How much funds are allocated ?
Alternate solutions are considered .
The results of this study are used to make a decision whether to
proceed with the project or not.
During this process market analysis is also conducted .
o After the project is selected funds are allocated and planning is started .
[ Ch #3] Database Design Process 54 -
Computer Science Part 11

* Requirements analysis
o Systematic requirements analysis is also known as requirements engineering.
o It is sometimes referred by names such as requirements gathering, requirements
capturing, or requirements specification.
o Requirements must be measurable, testable, related to identified business needs or
opportunities, and defined to a level of detail sufficient for system design.
Conceptually , requirements analysis includes three types of activity:
Eliciting reguiremmtsi
The task of communicating with customers and users to determine what their
requirements arc?
Analyzing requirements:
Determining whether the stated requirements arc unclear, incomplete, ambiguous,
or contradictory, and then resolving these issues.
Recording, requirements :
Requirements may be documented in various forms, such as natural - language
documents, use cases, user stories, or process specifications.
* Project planning
o Project planning is part of project management
o Initially the project scope is defined and the appropriate methods for completing
the project arc determined .
o Following this step the durations for the various tasks necessary to complete the
,

work are listed and grouped into a work breakdown structure,

o The logical dependencies between tasks are defined using an activity network
diagram that enables identification of the critical path.
o Then the necessary resources can be estimated and costs for each activity can be
allocated to each resource, giving the total project cost . e.g. salaries of
development team , traveling expenses, cost of hardware equipments etc,
o At this stage, the project plan may be optimized to achieve the appropriate
balance between resource usage and project duration to comply with the project
objectives.
* Data analysis
While designing a database it is very important to analyze the data which is required
to be stored in the database There are three activities in this phase
,

DFD ( Data Flow Diagrams}:


o A data flow diagram ( DFD) is a graphical representation of the 11flow” of data
through an information system ,
o A data flow diagram can also be used for the visualization of data processing
(structured design ).
[ Ch #3] Database Design Process Computer Science Part 11-
Decision Tables:
o Decision tables are a precise yet compact way to model complicated logic ,

o Decision tables, like if-then-else and switch- case statements, associate conditions
with actions to perform.
Decision Trees :
A decision tree is a decision support tool that uses a graph or model of decisions
and their possible consequences ,

Q 2. What is data modeling? Also discuss its components / ingredients ?


An $ ,
Data ModeJin 8
o A representation of real world objects or events and their association is called
model and the identification of data objects and their relationships to other data
objects is called data modeling ,

o Data modeling is the first step in database design ,

o Data modeling helps us to understand the complexity of the system ,

o Designers first create a conceptual model of how data items relate to each other ,

o Data modeling involves a progression from conceptual model to logical model to


physical schema .
Ingredients of Data Model in!
1. Entity /Object
o Anything about which we w'ant to store data is called
entity ,
o It is participating in the system and it can be a person,
EMPLOYEE
place or an event ,
o Entity is represented as a rectangle ,

o Name of an entity is in capital letters,


o Each occurrence of an entity is also called an instance of entity. Each instance of
an entity is unique. It is identifiable by the primary key ,
2, Attributes
o Attributes are properties of an entity for example an EMPLOYEE has a name ,

address, telephone number etc .


Name Address Telephone

EMPLOYEE

o All these are called the attributes of the entity.


[ Ch #3] Database Design Process 5^ -
Computer Science Part 11
o Attributes are represented by an oval and name is written inside the shape .
3* Relationships
o A logical connection between two entities is called relationship.
o The relationship indicates how the entities are connected or related to each other *

o The name of relationship is displayed over the line that represents the type of
connection *

o Relationship is written within a diamond .


Orders
Displays

Stocks
BOOK BOOK STORE
Sells

Returns
Above figure shows different connections between BOOK and BOOK STORE ,

* A BOOK STORE orders BOOK(S)


* A BOOK STORE displays BOOK{ S )
• A BOOK STORE stocks BOOK{ S )
* A BOOK STORE sells ROOK{ S )
* A BOOK STORE returns BOOK ( S )

BOOK STORE ORDER BOOK

Some important points about relationships


o All relationships define the relevant connections between two entities*

o All relationships are bi-directional


o Only relevant relationships according to the requirement are considered ,

o The types of relationship are .


One to one.
One to many.
Many to many .
Recursive .
[ Ch #3] Database Design Process 7 -
Computer Science Part 11
None
Q3. What are relationships and what are their types?
Ans. Relationships
A logical connection between two entities is called relationship.
The relationship indicates how the entities are connected or related to each other .
The name of relationship is displayed over the line that represents the type of
connection.
All relationships define the relevant connections between two entities.
All relationships are bi - directional
Only relevant relationships according to the requirement are considered .
The relationship can be
One to One:
o One instance of first entity is related to exactly one instance of second
entity e . g . A country must have a capital and it must be only for one
,

country.

EMPLOYEE has VHICLE

One to Many :
o One instance of first entity is related to zero , one or may instances of
second entity c . g . A father can have many children but all children must
,

have only one father.

ROOM has < STUDENT

Many to Many :

o One or many instances of first entity are related to one or many instances
of second entity e .g . a student have many courses to study and similarly a
,

course can be studied by many students.


arm uiof
< iNaarus

llrWi aowspg jiajnmuo;} 8 ^ SS300JJ U #] S3(] SSBtjqTJQ [£# IQ ]


[ Ch #3] Database Design Process -
Computer Science Part 11

Q4. What is cardinality ? Explain briefly .


Ans . Cardinality

* The number of entity occurrences of first entity is related with one or more
occurrence of the second entity is known as cardinality ,

* It is expressed as one or many e. g. a country can have many cities but a country
can have only one capital .
* The cardinality of one is denoted by a shoit vertical line drawn across the
relationship line.
* The cardinality of many is denoted by the line end that splits into three parts. This
symbol is also called “ Crow’s Foot".

* Small circle represent the zero number of record ,

* The cardinality of relationship can be


o One to one
o One to many
o Many to many
o Recursive
o None

Each instance of A is related to a minimum of zero and a


A OF B maximum of one instance of B.

Each instance of B is related to a minimum of one and a


A B maximum of one instance of A.

Each instance of A is related to a minimum of one and a


A « B maximum of many instances of B.

Each instance of B is related to a minimum of zero and a


A B maximum of many instances of A .
DATA INTEGRITY AND
NORMALIZATION
Ql , What is data integrity? Also discuss its two types.
Ans.

o Data integrity refers to the correctness and consistency of data .


o Integrity means reliable and trustable It is another form of data protection .
,

o Security means the protection of data from unauthorized operations where as


integrity is concerned with the quality of data.
o Integrity is expressed in the terms of certain rules which are also called
consistency constraints . These rules act as a filter that purifies incoming data .
o DBMS uses these rules to maintain quality of data .
Types of Data Integrity
o There are two types of data Integrity ,

o Entity Integrity
o Referential Integrity
Entity integrity
o It is a primary key constraint i .e. no attribute of a primary key should contain null .
o Every relation must have a primary key, that primary key attribute cannot have a
null or duplicate values ,

o It is also called record integrity ,


Referential integrity
o It is a foreign key constraint .
o If a foreign key exists in a relation then either the foreign key value must match
the primary key value of the same tuple in its parent table or the foreign key value
must be completely NULL.
o Referential integrity can be achieved by specifying relationship between tw'o
tables and it is applied by using foreign key.
[Cfi#4] Data Integrity & Nomializatiort 78 -
Computer Science Part 11
o A referential integrity constraint requires that the foreign key has the same name
and data type as primary key in parent table,
o Referential integrity ensures that the relationship between the records of related
tables remains consistent .
Q2 , Explain the difference between data integrity and data security .
Ans.
Data Integrity Data Security
1. It refers to the validity of data. Tt ft is defined as protection of data with
relates to the logical protection respect to physical form of data against
( complete correct and consistent ) of accidental or intentional loss,
data . destruction or misuse.
2. Data integrity avoids from Data security avoids from
* Human errors when data is * Unauthorized access of data.
entered * Unauthorized edit , update and
* Errors that occur, when data is loss of data.
transmitted from one place to
another.
3. Data integrity can be implemented by Data security can be implemented
following rules through
* Primary key • User accounts ( password and
* Foreign key rights )
* Relationship Authentication schemes ( A
security plan which positively
identify a user attempting to
gain access to data )
Q3. Define the terms Synonyms, Homonyms, Redundant information and
mutually exclusive data .
Ans.
Svminvms
o A synonym is created when two different names are used for the same
information or attribute.
o The name of attribute must be same if it exists in two or more entities.
Example:
STUDENT STDSUBJECT
STDID STDNO ( error )
STDNAME SUBID
STD ADDRESS SUB NAME
In above example two entities are related and have common field STD ID . But
here it is used with different name . It is an error . It must be used with same name and
STD NO in STDSUBJECT table must be replaced with STDJD .
[Cfi#4] Data Integrity & Nomializatiort 79 -
Computer Science Part 11
Homonvms
o It is a problem of having same name for two different attributes.
Example:
STUDENT SUBJECT
STDJD STDJD ( error )
STDNAME SUB NAME
STD ADDRESS
Jn above example both relations have the same field he STD ID which is,

creating confusion . To avoid this we must replace the STDJD attribute in SUBJECT
relation with SUB ID.
Redundant information
o It is a problem of storing the same information in two different w ays or forms.
?

Example:
STUDENT
STDJD
STDDOB
STDDOBD
STD DOB M
STDDOBY
In above example the same information be date of birth of the student is stored in
,

two different ways at different places.


So the attributes STD DOB D, STD DOB M and STD DOB Y are redundant .
Mutually exclusive data
o Mutually exclusive mean having one out of a few options.
o In mutual exclusion only one option or set of specified options can be selected.
Example:
STUDENT
STD ID
STD_ MARRIED
STD SINGLE
In above example attributes STDMARRIED and S T D S INGLE arc mutually
exclusive fields. Only one field can give the required information therefore only one field
is required instead of two he . STD MARTIAL STATUS . _
[Cfi#4] Data Integrity & Nomializatiort So -
Computer Science Part 11
04 . What are database anomalies? Briefly discuss insertion deletion and
modification anomalies.
Database Anomalies :
* Database anomalies me tin errors and inconsistencies. It creates problems while
performing the operations like insertion, deletion and modification.
* It is necessary to remove anomalies for error free processing in relations.
* The anomalies can be eliminated by redefining a relation into two or more relations.
Insertion anomaly: *

It occurs when a user try to enter a new record in the relation but due to insertion
anomaly, the actual fact cannot be inserted until the user may provide many unnecessary
attributes of the same relation.
Deletion anomaly: V

It occurs when a user try to delete a record in the relation hut due to deletion anomaly,
the deletion of target record automatically deletes many facts about another relation .
Modification anomaly:
It occurs when a user try to update a record in the relation but due to modification
anomaly, the modification in the value of specific attribute require modification in all
attributes in which that value occurs.
Q5. Define Normalization and different steps involved in it*
Ans. Normalization:
Normalization is a process of efficiently organizing data in database.
Or
Normalization is a process of converting complex data structures into simple and
stable data structures.
o Normalization was first proposed by Dr . E . b . Codd.
o Normalization is a technique for reviewing the list of entities and their attributes
to ensure that attributes arc stored from where they belong.
o In other words wc can say that it is a process of analyzing the dependencies of
attributes within entities and it is performed as a series of tests on a relation .
o Attributes of each entity are checked against the rules called Normal form and
each normal form has some specific conditions.
Before normalization a few terms must be discussed .
[Cfi#4] Data Integrity & Nomializatiort -
Computer Science Part 11
Normalization steps:
Normalization is accomplished in steps, each of which represents a normal form . A
normal form is a state of relation that can be determined by applying simple rules to that
relation. The flow of normalization through different steps can be explained as follows.
Actions

Relation
l
Remove
repeating groups

r NF
Remove partial
dependencies

2ntl NF
Remove irati ^ itive
dependencies

11
3 NF

Remove remaining
ii iiom LI lies

Higher normal
forms
There are three types of normal forms.
( 1) First normal form.
( 2) Second normal form.
(3 ) Third normal form .
Q6. When a relation is in First Normal Form ? Explain with the help of an
example.
First normal form:
* A relation is in first normal form if and only if all underlying domain contain atomic
values only. Each cell should contain only one value and relation does not contain
any repeating groups.
* A repeating group is an attribute in which data items may repeat in each tuple at
variable number of times .
Example:
Suppose we have a relation DEPARTMENT .
DEPARTMENT
DEPT NO DEPT NAME EMP NO EMP NAME
D01 Management EO Kashi f Basher
[Cfi#4] Data Integrity & Nomializatiort -
Computer Science Part 11
E 02 Qasim
D02 Finance E 05 Huma Khalid
DO 3 Marketing E03 Hamid Ai
E 21 Imran Shakecl
o In above example the relation contains repeating groups,
_
o The EMP NO and EMP NAME are repeated for single occurrence of DEPT NO
and DEPTNAME *

o To bring it into 1 st NF eliminate the repeating groups from the table and fill in the
missing information .
DEPARTMENT
DEPT NO DEPT NAME EMP NO EMP NAME
D01 Management E 01 Kashi f Basher
D01 Management E02 Qasim
D02 Finance EOS Huma Khalid
D03 Marketing E 03 Hamid Ai
DO 3 Marketing E 21 Imran Shakeel
o For any tuple of an entity, each attribute must have one and only one value or “ an
attribute must have no repeating groups" ,

o The error exists in the above example because some attributes are being repeated
for a single occurrence of each record .
Following steps should be taken to overcome this problem
o Repeating attributes must be removed and placed where it belongs, under the
entity that defines it ,
o Analyze the relationship of where the repeating attribute come from and where
the attribute went to . Determine the relationship weather it is 1 : M or M : N .
case 1 : If the relationship between entities is l :M e. g. one department have more
than one employees and one employee can belong to only one department
at a time. There is no need to do any further change.
case 2 : If in a situation relationship is M :N i .e . one department have many
employees and one employee can work for more than one department then
we need another table to store intersection data. The newT tabic can be
EMP DEPT ,
[Cfi#4] Data Integrity & Nomializatiort -
Computer Science Part 11
Q7. When a relation is in Second Normal Form? Explain with the help of an example.
Second Normal Form:
o A relation is in 2 IKl NF if it is in V NF and every non- key attribute is fully
[

functionally dependent on the primary key. All non key attributes must depend on
all parts of primary key.
Following are few conditions for 2nd NF.
o The primary key consists of only one attribute
o Every non -key attribute is fully functionally dependant on the all the parts of
primary key.
Partial Functional Dependency:
A partial dependency occurs only in a relation with a composite key . It occurs
when a non-key attribute also depends on only part of the primary key .
For example consider the following relation with three attributes .
R(A, B, C )
Relation has a composite primary key consisting of attributes A and B . As the
primary key is unique, the following dependencies must be true :
A, B C
C depends on A and B together. That is, A and B together determine C,
A partial dependency exists when only some of the attributes in a composite key
can also determine a non -key attribute . That is a partial dependency occurs if one of the
following dependencies is true.
A C C depends on A alone. A alone determines C .
B^C C depends on B alone . B alone determines C .
Example:
In the following example STUDENT relation is in first normal form
STUDENT

STD1 D STDNAME CLASS FEE CRSNO CRSDATE


D01 Imran C 01 10000 CR 101 120898
D01 Imran C01 10000 CR 205 150998
DO 2 Saeed C01 10000 CR207 071098
D03 Baqir C02 15000 CR201 060499
D03 Baqir C02 15000 CR 205 150998
D04 Nazir CO 3 12000 CR305 120999
The above relation contains different redundancies, The relation can be expressed
using another notation .
[Cfi#4] Data Integrity & Nomializatiort «4 -
Computer Science Part 11
STUDENT ( STDIIX STDNAME, CLASS , FEE, CRSNO, CRSDATE)
o The above relation contains a composite primary key of STDID and CRSNO .
o The functional dependencies in this relation are as follows.
STDID STDNAVfET CLASS, FEE
STDID, CRSNO CRSDATE
o The non - key attributes NAME . CLASS and FEE are functionally dependent on
part of primary key Le. STDID *

o STDID is not a complete key.


-
o A type of dependency in which one or more non key attributes are functionally
dependent on a pan of primary key is called partial dependency .
o The paitial dependency creates redundancy.
o It also results certain database anomalies when database is updated .
Insertion anomaly :
o Suppose a new course is to be added in the relation .
o The new course cannot be inserted w ithout the insertion of a STDID because it is
part of primary key and cannot be NULL.
Deletion anomaly:
o Suppose the record of STDID is D04 is to be deleted ,

o The information about CRSNO will also be deleted.


Modification anomaly:
o Suppose the name of STDID DOl is to be updated ,

o It requires updating all records in which STDID DOl appears *

A relation with redundant data can be converted into 2nd NF by decomposing it into two
relations. The above relation can be split into two relations STUDENT and COURSE.
STUDENT
STDID STDNAME CLASS FEE
DOl Imran C01 10000
D02 Saeed C01 10000
D03 Baqir C02 15000
D04 Nazir C03 12000
COURSE
STDID CRSNO CRSDATE
DOl CR101 120898
DOl CR 205 150998
DO 2 CR 207 071098
[ Ch # /J Data Integrity Sc Normalization Computer Science Part-11
DO3 CR 20 I 060499
DO3 CR 205 150998
D04 CR 305 120999
o The primary key in STUDENT relation consists of only one attribute,
o It satisfies first condition.
o The attribute CRSDATE in COURSE relation fully functionally depends on
whole composite key.
o It satisfies the third condition .
o It means that both relation are in second normal form ,

Q8. W hen a relation is in Third Normal Form? Explain with the help of an
example.
Third normal form:
A relation is in 3ul NF if it is in 2 tkl NF and no transitive dependencies exist.
Transitive dependency:
-
o It is a functional dependency between two or more non key attributes ofa relation and
for 3 NF a non - key attribute must not depend on any other non -key attribute.
Example:
Consider a relation
SALES ( CUSNO, NAME, SALESMAN , REG TON )
Where CUSNO is a primary key
The following functional dependencies exist in the relation .

CUSNO NAME, SALESMAN

SALESMAN REGION
o SALES tabic is in 2 lld NF because the primary key consists of only one attribute.
o But REGION only depends on SALESPERSON therefore it is transitive
dependency which is violation of 3 cd NF.
o As a result there are update anomalies in relation SALES .
SALES
CUSNO NAME SALESMAN REGION
coot HEWAD Tahir East
C002 ALLIED Muneer South
C006 AWAN Azam East
[Cfi#4] Data Integrity & Nomializatiort S6 -
Computer Science Part 11

C003 HAJVAIRY Asghar West


COOS PUNJAB Muneer South
C004 HITECH Imran East
Insertion anomaly:
A new salesman assigned to the north region can not be entered until a customer
has been assigned to him.
Deletion anornalv:
If CUSNO C 004 wc loose the information that SALESMAN Imran is assigned to
the East region.
Modification anomaly:
If SALESMAN Munccr is reassigned to the East region , several rows must be
changed to reflect the fact .
These anomalies arise as a result of the transitive dependency. This problem can
be removed by decomposing the relation.
SALESMAN SALES
CUSNO NAME SALESMAN SALESMAN REGION
C001 HEWAD Tahir Tahir East
C002 ALLIED Muneer Muneer South
C006 AWAN Azam Azam East
C003 HAJVAIRY Asghar Asghar West
C008 PUNJAB Muneer Imran East
C004 HITECH Imran
Now both the relations are in 3 tLl NF because no transitive dependency exists .
Q.9 Define functional dependency.
Ans. Functional Dependency:
Case l:When primary' key consist of single column.
A functional dependency occurs when one attribute in a relation uniquely
determines another attribute. It show's a relationship between two attributes in a relation .
For example, an attribute B is functionally dependent upon an attribute A if each
value of attribute A determines only one value of attribute B .
The functional dependency of B on A is represented by ail arrow as:
A B
This expression is read as “ B depend on A'’. The attribute on the left-hand side of
the arrow' (A in this example) is called the determinant . This expression , therefore, is also
read as “ A determine B'\
[Cfi#4] Data Integrity & Nomializatiort »7 -
Computer Science Part 11
For examples consider the following relation :
STUDENT fStd - IR Std - Address, Std- Phone)
In this relation , Std-ID uniquely defines other attributes in the relation. It means
that in this relation , the name of a student can be found referring to that student ' s Std - ID.
This means that Std -ID defines a student ' s name .
The word “ defines", means that for every Std- ID, there will be one and only one
name , Thus, Std-Namc is functionally dependent on Std - ID. Similarly, Std- Addrcss and
Std - Phone are also functionally dependent upon Std - ID. This dependency is shown as :
Std -ID Std-Name, Std- Address, Std- Phone
Following are some common examples of functional dependencies.
ID Card Number — > Name, Address, Date of Birth
A person ' s name, address, and date of birth are functionally dependent upon the
person 's national identity card number .
ISBN — > Title, Author 's Name
The title and author 's name of a book arc functionally dependent upon the
International Standard Book Number ( ISBN ) of the book .
Full Functional Dependency:
Case 2: When primary key consist of more than one column.
Full functional dependency occurs when all non-key attributes in a relation
depend only upon the key attribute of the relation.
For example, consider the following relation:
RESULT ( Roll -No. Class. Marks )
The relation RESULT has a composite key consisting of two attributes Roll - No
and Class. Sample data for this relation is shown below:
RESULT
Roll-No Class Marks
45 C 75
45 VB.Net 55
53 Java 85
48 Oracle 66
48 C# 92
In this relation , the following dependency occurs:

Roll -No, Course > Marks
[Cfi#4] Data Integrity & Nomializafrort -
Computer Science Part 11
This is a full dependency. Both the attributes in the composite primary key are
needed to determine Marks *

The attribute Roll -No alone cannot determine Marks . Similarly, Marks also
cannot be determined with the Class attribute alone
*
INTRODUCTION OF
MICROSOFT ACCESS
Ql . What is MS-Access? What are the benefits of using it?
Ans .
Overview
o Microsoft Access is a very commonly used powerful DBMS ,

o It has a lot of features which help in creating , managing and viewing databases
,

o Microsoft Access is a RDBMS which can handle large amount of data,


o It is easy to use and even an inexperienced programmer can use it .
Microsoft Access has many advantages of using it but a few of them are as follows .
* Sample databases:
o Microsoft Access includes sample database applications for users,
o These applications help users to lcam about real word problems.
o The user can understand the interconnection of tables, queries, forms and reports .
* Wizards:
o As its name, these are really a magical component of Microsoft Access,
o Using wizard user can create database in a couple of minutes .
o User can even create and customize almost all objects of the Microsoft Access
e. g. tables, queries, forms and reports .
* Keys to understand the structure :
o Microsoft presents the structure of relations in a graphical form,

o In this way user can easily understand the entities and attributes
,

o It is also helpful in creating and viewing their relationships .


* Microsoft office integration :
o It can also be used with word , excel, and other office applications to create mail
merges, charts etc .
[Ch #;>J ) introduction cjAtkroso/l Access 9 ^ -
Computer Science Part 11

* Lasier programming:
o Simple code with macros is used to program different tasks of the Microsoft
Access.
o For a little bit complex applications code of VBA is also available,
* Common Standards:
o It has common standards with other applications.
o For example SQL used in Microsoft Access is standard and can be used in any
RDBMS .
* Redundancy:
o It allows storing, manipulating, analyzing and printing information contained in
the database.
o Microsoft Access stores data without redundancy ,

o It stores the data at one place without duplication.


Q 2. Explain the procedure for creating a new database in MS-Access.
Ans.
Creating New Databases:
From task bar on desktop
Press start button + Programs * Microsoft Access
[Ch #;>J ) introduction ojAlkroso/l Access 97 -
Computer Science Part 11

Microsoft Access will open with a dialog box . There are three options in the
dialog box .
* Blank Access database
* Access database wizards, pages, and projects
* Open an existing file
Create a blank Access Database without using wizard
* It is the first option in the dialog box .
* In this option you can create a blank new database.
* When you select this option another dialog will appear .
* Tn this “ new tile database" dialog give the name to your database and press create
button ,

* A database is created at the location with the name you specified .


[Ch#;>J ) introduction ajTvlicroso/1 Access gs -
Computer Science Part 11
File Mew Ddtdbd^c ?|x
sa^ in: |J Sample Database 3^ -0 OXCiilS- Tools *

M
history

i.
^
j y

IWy Doame ^ tt

m
Desktop

*
Favorites

Fit name : [dbi Obdte


Save ao type : Microsoft Access Databases Cancel

Create a database using the database wizard


* It is the second option in the dialog box ,

* In this option you cun create a database using wizard or from template.
* When you select this option another dialog will appear .
* From this dialog you can select a template ,

* On the basis of that template you cun create a new database ,


* It reduces a lot of effort and provides a guideline to create the required database.
lempUtM U
General [

Asset Tracling
0 0 g
Ccnfcact Evsnl
£ ]
E-qp-
eriSss
iBBlEl
^ review
Management Management

Iver>torv
Ccrtroi

Service Cdl
MancgcTrcnfc
Kcger

@ H
Time end
Dillrg
ffiEanr.ttj Fte»4pce a .

P
OK c*re*

Q3 . Explain the procedure to open and exit sin existing database.


[Ch#;>J ) introduction cjAtkroso/l Access 99 -
Computer Science Part 11
Ans.
Opening existing Databases
* It is the third option in the dialog.
* In this option you can open an existing database tile.
* When you select this option an open dialog will appear.
* From here you can explore you database file and press open button.
pen ?| xl

5 -
LMk in*: [ j Sample Database | 4r
^ T
1[
^ St
(
^ ^? |??| * 1ocb

HWOry

TOJ

Hy Gwuinents

A
Dcsdqp

*
Favor tos

My Hetwp'b
I -rfu Jj t*? Qp?n -
Pfa:« FiteeFfe | ML - oatrfl Vira Cancel

Exit Microsoft Access


* After completing your work with Microsoft Access properly exit the program to
avoid data loss.
* From file menu select close option to close the open database.
* Again from file menu select the exit option to close the application .
Q4 *Discuss the MS-Access Application Window * title bar* menu bar* toolbar*
scrollbars and status bar in detail *

Ans .
MS - Access Annlicatioi] Window
Microsoft Access application window is just like any other Microsoft application
program ’ s window,
* Title bar
It is the top most bar have name of application program with the opened file name. It also
has an icon on its left side to represent the application program. It also have three buttons
oil its right side .

xJ Close button used to close the application .


n] Maximize button to maximize application .
[Ch#;>J ) introduction ajTvlicroso/1 Access roo -
Computer Science Part 11

Minimize button to minimize application.

G Mitrosuft Access - Ini x |


* Menu bar
It is the second bar from top. It consists of many words. Each word on this bar
represents a menu . Every word on this bar also has a character underlined . This
underlined character represents the short cut key combination for that particular menu
e.g. In file menu f is underlined therefore this menu can be accessed using Ctrl + f short
cut key.
File Edit Vievti Insert fools Wir«do ^ Het 1

* Toolbars
Toolbar contain icon button to perform certain tasks Most commonly used
features are available on toolbars in the form of buttons.
-
G? H 4} i a ? A % R ^ '

- ft * BJH * boo tf
A few commonly used buttous are explained below .
New button is used to open a new database
Open button is used to open an existing database
u Save button is used to save the file.
Si Search button is used to search a particular text at particular space
m Print button is used to print any table, report or query result.
Gk Print preview button is to viewr before printing

Spelling and Grammar button is used to check the grammar and spelling of the
text
Cut button is used to cut an object or text selection
% Copy button is used to copy an object or text selection .
Paste button is used to paste the copied or cut data.
ID T Undo button is used to remove the last action.

*Scroll bar
Scroll bars are used to move around the window. There are two scroll bars,
horizontal and vertical scroll bar .
* Status bar
[Ch#;>J ) introduction ajTvlicroso/1 Access 103 Computer Science Part-11
Status bar is the bottom most bar. It shows the status of different operations e. g.
whether the num lock and caps lock are on or off
Ready NUM //.
Q 5. What is database window in the MS-Access? Also discuss different buttons
( objects ) available in this window.
An$,
Database Window
The database window displays all the objects of the database. From here all these
objects are managed . From this window all tables, forms, queries and reports are created ,
edited and maintained.

iCNorthwind : Dat ( Attest 200 D lilt For nidi ) - JOl K]

Dtsign

Objsc :s

[HD Tables
* „
Ciedtc table in Design vievrf !
Citdtfc! tablt! by usi ij wizard
Create table by entering date
1 Queries
[
^
j

EH Cflteqoiits
PI] rant
m Custamer ?
Reports EU EmnpkyeES

m«« HOI
HH1
Order Deiab
Order ?
3 Macros
EH Produts
Modules
HOI ihlpp
^i
EH Supplers

Gioups

Database Objects
Database consists of different components called the database objects . These
database objects are used to manage data. The four major database objects are as follows.
* Tables
o Table is a collection of rows and columns ,

o All the intersection points of rows and columns are called cells ,

o In these cells data can be stored ,

o Each column of table represents a field ,

o Each field is specified to store a particular type of data ,


o Table can be viewed in different ways but most commonly arc datasheet view and
design view .
[Ch#;>J ) introduction ajTvlicroso/1Access 102 Computer Science Part-11
H Categories ; Table UolJd
Category ID \ Category Name Descr ptiun Picture
* i]Beve rage s| Soft drinks , coffees , teas , jeers , and ales Bitmap linage
2 Condiments Sweet and savory saices , relisies , spreads , ; Bitmsp Image
3 Dnnfcchnni Desserts . candies. arrt sweat treads Bitmap Image
4 Dairy Products Cheeses Bitmap Image
5 GrainsfCereals Breads, crackers, pasta , and cereal Bitmap Image
6 Meat /Poultry Prepared meats Bitmap Image
7 Produce Dried fruit and bean curd Bitmap Image
0 Seafood Seaweed ard fish Bitmap Image
*Record(AutoNumber
:H I I|
)
1 I H h* l of 5

Data sheet view of a table


1Categories : Table -ini xj
Field Name Data Type Description
AutoNumber Number automatically assigned to a new category .
Category Name Text Name of food category .
Description Memo
Picture OLE Object £ pictue representing the food category.

Field sM3peities

General I lookup |
Field Size Long Integer
New Values Incrsment
Format
Caption Category ID field name car
[idexed Yes (No Duplicates} be up to 6*
characters longj
indudinq spaces.
Press FI for hefc
on field name
* .

Design view of a table


* Queries
o Query is used to get data from the database.
o The actual objective of data storage is that it can be retrieved when CVCT it is
required.
o Using query object data can also be deleted and updated .
o Jt is a powerful object to create reports according to the requirements.
[Ch#;>J ) introduction ajTvlicroso/1 Access 103 Computer Science Part-11

Enter Parameter Value

Employee ID

h
OK Cancel

ajp Queryl : Select Query -1 ! *1


Employee ID First Name Last Me me Hire Date | Address City
3 Margaret Peacock 03- May - 1993 4110 Old Redmond Rd, Redmond
* JAutoNiurber)
Reccrd : N 1 > | M [H»] of J
Query result against given information in the above dialog
* Forms
o The window that is used to enter data into the database is called form. Using form
data can be entered, edited and even viewed in Microsoft Access.
o Data entered in forms directly goes to the tables,
o Forms are always made after table creation ,

o The fields on form are linked to the table fields .


^ -
SU. 1- rvijpl n rr s _= I
-
Mnncy D nivnlin
'
.;
i pi[yny lif r | FaiOiij Inin|

Emfinyr. fi ID : 1 I

Finr Warrc: |EFSI5


L A 1* K OK; |Da^ cJri

tille: [SatesfieDressrtaUve

I Reports I : |l uler . AJLILMP


Wire Dote: |0lWt £92

lEifS ^ nsian: |54E7

Second Ijjjj L f I » W*\ tf 9

* Reports
o Reports are used to view data from database in a formatted way ,
o Not all but most of the RDBMS provide this facility to their users ,

o Reports can be generated on the basis of tables and queries ,

o We can app ] y formatting on the report to make them more presentable and understandable.
[Ch#;>J ) introduction cjAtkroso/l Access 104 -
Computer Science Part 11
^lsl *J
1 «. *isi¥imdryftF SrtJr* hy Y r

Summary of Sales by Year


-
OJ -A ug 2 ff &7

J 9 9 fi

tJuarte^: Ondtem Shipped: Stirias:

:i V63LUUS
G2 :i 12133 !

7 hitdsJ»r J 99 6: 143 $ 193317

1997

Qu&iiejr; ( Jntlm SA i/p/ptfdf; Sdd3:

92 5143/ 03
2 92 5145,(155
3 105 5143,320
109 5175,1 69

J 957: jyu seuau -i;


K606 I If IlM I H I
* Pages
o It is used to create and modify Data Access Pages . Data Access Page is a HTML
document ( Web page) . It is designed for viewing data on the Internet. A Data
Access Page is like a form , but it is specially designed to run in a Web browser to
access data from database stored on the Web server.
* Macros
o It is used to create and modify macros A macro is a set of one or more actions , ,

each action performs a particular operation , such as opening a form or printing a


report . Macros can help you to automate common tasks.
* Modules
o It is used to create and modify modules A module is a collection of Visual Basic ,

declarations and procedures that are stored together as a unit. Visual Basic code
can be written to perform different operations on database.
TABLE AND QUERY
Ql . What is table? Also discuss its different characteristics.
Ans .

o Table is the fundamental object of relational database.


o It is called relation in database terminology *

o Table is a collection of rows and columns .


0 Each intersection of row and column is called a cell.
0 Cell is the place where data is placed . Table has a lot of rows and columns .
o Each row contains a tuple and each column represents an attribute of an entity.
0 Table or relation itself represents an entity ,
E Employe ^s : Tabl5 ^Jnl
xj
employee Ip | Last Narre ] hirst Nsme Tile | Trt j 0 Bnth Date H119 Dale
+
H Davolio Nan:- y Saks Pffrpftpilstr. p ME QE -Dec - 19G3 01 - May - 1992
+ 7 Filer Andew Vies President , Sslas Dr 19 Feb-1952 14- Aug- 1992
3 Levering
A Peacgch
Janet
Warfare:
Sales RejJBseitatfce Ms
Saks Repre & f=- itatwe Mrs
3C -Aog- 1963 01 ApHBBa -
in- r :ep- 1 [£3 D3- M @ y - 1Q9=I
+ 5 Rnrhsnsn Ftgv n
^ Saks Manager Mr ni- Mar- ISK 17-0 nt.1993
+ 6 Suyama Michael Sales Represeitatoe Mr C 2 - Jul- 1 £C3 17-Qct 1993
7 Kng Fobsrl Sales Represeitatwe Mr - Mar - 1960 02- Jan- 199i
+
+ 3 Callahan Laura Inside sales Coordinate Ms. ^W - Jen- 1958 05-Mar- 19S1
+ 9 Uodeworti Ann ? Saks Repreaailatr.'e Ms . u - jji- iyw I &NOHSBI
JAuluNknibtr)
Record: H I i I [ l IF Hi I it * I aF 9 11

Characteristics of tables l Relation:


The tables of relational database have the following characteristics.
o Each cell of the table contains only on value.
o Each column has a distinct name , It is the name of the attribute or Held it
represents.
0 Each column is specified with a data type .
o The order of the columns is immaterial.
0 Each row represents a record .
[ Ch # GJ1 Table and Queiy 112 -
Computer Science Part 11
0 Each row is distinct. There arc no duplicate rows.
0 The order of rows is immaterial .
Every entity is convened into corresponding table.
0 In this way data about one entity is stored at only one place which avoids
redundancy.
Q2- Define the following terms. Degree of a relation, Cardinality of a relation,
Database, Object, Table, Field , Record , Design View and Datasheet view.
Ans.
Decree of a relation:
o The number of fields of a relation is called the degree of that relation ,

o A table' s degree is specified at the time of its creation.


e But as a rule it can be changed at any time. Change in degree of a table may cause
data loss.
Cardinality of a relation :

o The number of records in a relation is called the cardinality of that relation.


0 Cardinality of a table changes as new records are added or previous records are
deleted .
0 For example a table having 40 rows/records has cardinality 40 .
Basic Terminologies:
Here are a few words frequently used in MS-Access.
Database: Database is a collection of related records.
Object : Object is a component of database e g. table, form, query and report
, ,

Table: A table is a collection of related data arranged in the form of rows and
columns fables with common fields can be linked together to form
,

relationships .
Field: Field is a column in a table . A data type is defined for each field. Field
represents the attribute of the entity.
Record: Record is a row of table. It is a collection of attributes.
Design View ; This view is used to design the new table or edit existing table structure.
Datasheet View: this view allows user to view, edit and add data in the table.
Q3.
^
[ Ch # G Table and Que
^ ]]
3
What is MS-Acccss IDE? Also discuss different views of a table in MS-
Computer Science Part-11

Access,
Ans.
Access IDE
o IDE stands for Integrated Development Environment .
o It is a collection of facilities provided to the users .
o It is used by database designers and application programmers.
o It is used to create database and database applications ,

o IDE uses a graphical interface .


0 I he users do not create database applications manually.
0 The details of database creation are hidden from the user.
Starting Microsoft Access
From task bar on desktop
Press Start button > Programs > Microsoft Access
OR
From desktop double click the Microsoft Access icon if it is present over there.
Table Design View
o The view that is used to design the structure of a table is called design view .
0 It is used to specify name, data types and description of fields .
0 Primary key is also specifled in this view.
0 The structure of an existing table can also be modified in design view.
1Student ; Table
- Ini x|
Field Name Data Type Dear ption
RohunJ Number
_ Name Text
_
_ Address
Phone
Class
Text
Text
Text

zi
Field Properties
General | Lookup |
Field Size Long Integer
Format A field
name tan
Decimal Places AutO be up to
Input Mask 64
Caption character
Default Value 0 s long,
Validation Rule including
Validation Text spjcei ,
Required Mo
Press F 1
for help
Indexed Yes (No Duplicates)
OH held
names .
-
^
[ Ch # G Table and Query
Table Datasheet View
T14 Computer Science Part 11

Tabic view that is used to insert, delete or modify data in a table is called datasheet
view. The table in this view is displayed in rows and columns. The name of each field is
displayed at the lop of the column . Data can be manipulated in the follow ing forms.

Switching between views


To switch views from datasheet to design view just click the button at top left
corner of the window.
ip dbl : Database ( Access 2000 Tile format )
-n | x\

EjjlQFen Design ,- tJw >< aa ^ s2:


\ ;"T "

Objects Create table in Design view


Design|
ED Tables Create table by using wizard
'MliP
'
l£f ] Create table by entering data
3 Queries
a ggg
Ell Forms

9 Reports

^3 Pages

Macros

Modules

groups
Favorites

OR
Right click the table object and choose open for datasheet view and design view
to open in the design in the design view.
-
Q 4.
^
[ Ch # G Table and Query
How tables arc created in Design View ? Write stepwise procedure.
Computer Science Part 11

Ans,
o Microsoft Access like other databases allows users to create and manage tables
using its IDE.
0 A large amount of tables can be created using Microsoft Access ,
0 All the tables have unique name with in the database.
0 Each table can have multiple columns representing the attributes of an entity.
o Each column required to have unique name with in the table.
Each column need to be specified a data type which tells that what type of data ,

can be stored in that column .


Tabic Creation
Fable can be created in different ways in Microsoft access.
iSdbl : Database ( Access ZDOO file format ) -! *
Open Design
Ci

ft
— —- —-
-
Ci
Ci
& B
b

-D-

Objects 0] Create table h Design yfew


EO Tables 0J Create table by using wizard
0]
"

Create table by entering data


[pi Queries

El Forms

0 Reports

^
2
Pages

Macros

^ Modules
Groups

Favorites

1 lore are three methods to create a table *

* Create table in Design View ,

* Create table by Using Wizard


* Create table by Entering Data
Creatine [ able in Design Viewr
I. From objects pane on left side click on the tables object .
2 , There will be three options on the right pane .
-
3 ,
^
[ Ch # G Table and Queiy
Select the first option of “ create table in design view” and double click it
TlS Computer Science Part 11
,

4 , A blank table will open in design view.


5. Write field name, their data type.
6 , Under the description column enter the text that describes the Field It is optional. ,

7, The data type tells us that what kind of data we can store in that column or
attribute.
8, Primary key can be set by just selecting the field and pressing the primary key
button in toolbar.
El Hrrrunhh ftrrr ^ -i n x
Eh Edit 'i.Orf Insert Lo:b sondo w drip T ypjw = quastlex i ( ur iftJu
Ei - s s s a? * i a a| n - . |T|=^ != S 1
e^- 0.
m
'

JL> 1 ! [' jt - jb - jti " aouu tom HI & 1 at )

.lit jttyii ,;z if . . - x * * :- J


IL IL

uL je L _ > 4L Create tabk m Dedcri few


'
EH Tdriss il , Create t cble by using weard
4 L, create t abfc by entering data

SI r ^ rrn -5 HTnhlrl : Tnhftr Jn| x


9 Reici :: -pclh:|
Firi: Nar«c Uct.'i Type
PJjimfaer
DcmiptEn
E
hflnn Tenet
.
^ H

JT?
] P3 gn-;t

r^cf-TU >-
HdjrCrJ
DOB
^ Text
D-alsjliiue
ChS5
ffaUH
.irnri Rdd PrL
|
_
=
i 5 rl.i “ t

_±J Favorite;
| Lookup |
- leld izc lorg I rtesjer
Field
-OTvat M
nomc ccn
[
-
I'ecral lac s
r ji. Tdd..
= = ALtd he up ha
a*
-
C 4JLU
IifihA Js
vrtiiflbm Ri i *
variation I ext
II
- '
diaroctcrs
irpiridrpq
SCOWS ,
. cq _r:d m Press FI
few help on
[
"
cte /sd Yes Clio Cucltates) frdd
=
I1 111 fc .

^. h= - iwtch:g c: -: - He|p
Dcsgivc - NUPl
1
/A

Field name
0 This is the name of the field.
0 It must be self explanatory c g. name should represent name. +

0 The name cannot exceed 64 characters.


Data type
0 Before defining a field wc must think of data that the field will contain e. g. name
can contain characters, date of birth can contain date etc.
0 Data types available in MS-Access are in Text , Memo, Number, Date/Time,
Currency, Auto Number, Ycs/No, OLE Object and Hyper Link ,
[ Ch # G Table and Queiy -
Q5
^.
"7
What are the different data types available in MS-Access?
Computer Science Part 11

Ans .

0 Jt is the default data type.


o It can contain text or combinations of text and numbers, as well as numbers that
don 't require calculations, such as phone numbers .
o Its size is 255 characters or the length set by the FieldSize property, whichever is
less .
o Microsoft Access does not reserve space for unused portions of a text field.
* Memo
Q A text type field that can contain more than 64000 characters .
0 It is used for long descriptions .
* Number
o Numeric data used in mathematical calculations.
0 Size of this data type can be 1 , 2, 4, or 8 bytes ( 16 bytes if the FieldSize property
is set to Replication ID ).
* Data/lime
o A date, time or combination of both can be specified in this field.
o Its size is 8 bytes.
* Currency V

o This data type can hold currency values and numeric data used in mathematical
calculations.
o It can manage data accurately 15 digits on the left side of the decimal separator
and to 4 digits on the right side. Its size is 8 bytes .
* Auto Number
0 A unique sequential (incremented by l ) number or random number assigned by
Microsoft Access whenever a newr record is added to a table.
0 AutoNumber fields can ’ t be updated . Its size is 4 bytes.
* Yes/ No
o This field can store two values either Yes/ No, True/False, or On/Off
Its size is one bit.
[ Ch # GJ1 Table and Queiy PfS -
Computer Science Part 11

* OLE object
o An OLE ( Object Linking and Embedding) object is a sound, picture, or other
object such as a word document or excel spreadsheet that is created in another
program ,
o This data type is used to embed or link an OLE object in the database.
* Hyper Link
o This field contain text or combinations of text and numbers stored as text and
used as a hyperlink address ,

o A hyperlink address can have up to four parts:


text to display — the text that appears in a field or control,

address — the path to a file or page (URL) ,

subaddress — a location within the file or page ,

screentip — the text displayed as a tooltip.


General form of hyperlink is
Display text # address # subaddress# screentip
Example:
Google Home Page#http : //www . google .com #C : \ mv documcnts\database .mdb#
mytable
The easiest way to insert a hyperlink address in a field or control is to click
Hyperlink on the Insert menu .
Description ( optional )
The description is brief comments about the field .
Q 6. How different field properties of a table are defined in IVIS-Aceess ? Briefly
describe them.
Ans.
Defining field properties in design view
o Field properties can be defined in design view .
o Field properties are used to define how data will be entered, stored and displayed
in MS- Access .
o Field properties can be delined in design view.
o Design view window can be divided into two panes, a top pane and a bottom
pane,
o In top pane we enter the field name, its data type and description.
There is a long list of properties of fields but a few of them are briefly described.
[ Ch # G Table and Queiy -
*
^Field Size Tig Computer Science Part 11

o You can use the FieldSize property to set the maximum size for data stored in a
field set to the Text , Number, or AutoNumber data type.
o The default field size for the text type is 50 characters.
The field size can be limited to a certain number of characters if the value in the
field is small .
0 It saves disk space and prevents entry errors .
For number field following options are available.

Data Type Data Range Size in Bytes


4L'

Byte 0-255 1

Integer - 32768 to 32768 2


Long Integer -2, 147 ,483,648 to 2 , 147,483,648 4
Single -3.4 x 10 to 3.4 x 103* 4

Double -1.797x 103OS to 1.797x 10m 8

* Format
o The format property is used to specify the format of data as it is displayed.
o The first part of the property is used to apply to the field and the second applies to
empty fields .
Text and memo forma JPI
Following arc the symbols used to format text and memo data type.
Symbol
&
Description
@ Must have a text character in this position
& Optionally have a character in this position
< All characters will he lowercase

> All characters wall he uppercase

Space Display a space between characters


ABC ’ Display the characters inside the quotes
1

-
^
[ Ch # G Table and Que

@\!
^ 120

Adds character at the end


Computer Science Part 11

Table below shows the use of text format property and it result
Text Format
Format Datasheet Entry Access Displays Explanation
12345 12-345 @ indicates a required
character or space

1234 12-34 & indicates an optional


character or Space
< STUDENT student < converts characters to
lowercase
> Student STUDENT > converts characters to
uppercase
@\! Student Student! Adds characters to the end

@;” No Data** Student Student

@;” No Data** (Blank ) No Data


Number forma iJ
o Basic number format can be selected from the list box.

General Number 1234.874


Currency $ 123.45
Euro 1,23,87
Fixed 324.65
Standard 3.45 .65
Percent 234 00%
,

Scientific 4.56 E-03


o Decimal places to be displayed in a number can also be specified.
0 By default a number displays two decimal places.
[ Ch # G Table and Queiy -
o
^ 121 Computer Science Part 11
In addition to using the predefined format, custom formats can also be specified
using the symbols explained below.
Number Format

Format Datasheet Entry Access Displays Explanation


###,##0,00 123456, 78 123,456,78 0 is a placeholder that
displays a digit or 0 if there
is none.
$###,##0.00 0 $ 0 00, # is a placeholder that
displays a digit or nothing if
there is none.
###,. 00% 123 12,3% % multiplies the number by
100 and added a percent
sign
Currency formalH
o The currency format consists of four parts separated by semicolons.
o These are format for positive numbers, format for negative numbers, format for
zero values and format for NULL values .
Currency Format
Format Explanation
$##0.00; ($## 0 , 00 )[Red ] ;$0.00f none
11
Positive value will be normal
currency format , negative numbers
will b red in parentheses* zero is
entered for zero values, and tnone"
4

will be written for NULL values.


Yes/ No
c Fields are displayed as check boxes on the datasheet.
o To change the formatting of these fields first clicks the look up tab and change the
display control to the text box.
0 It has three parts, first docs not contain anything, second specifics formatting for
Yes and third for No values.
Yes/No Format
[ Ch # GJ1 Table and Que
^ 122 -
Computer Science Part 11

Format Explanation
;s'Yes'’[green];1JNo” [red] Prints “ Yes"' in green or “ No ' in red
1

Dale formal
The date format is as follows
Currency Format
Format Access Display Explanation
dddd’ VTrnnmm d’Y’yyyy Monday, January 5 , 1991 dddd . mmmm and yyyy
5

print the full day name,


month name and year.
add 11
mm in . d yy Mon, Jan . 1 01
? ddd. mtiiin . and yy print
the first three day letters,
first three month letters,
and last two year digits.
“ today is "dddd Today is Monday

h : n :s : AM/ PM 12: 00:00 AM “ n" is used for minutes to


avoid confusion with
months
Default Valu I
o
-
In some cases, the value of all records in a certain field is same *

o A default value can be set in this case.


o The user does not need to type the same value again and again .
o The property set the default value is used to set default value for a field.
Indexes
o The indexes arc created to query and sort records faster in MS- Access.
o The index property is used to set an indexed field .
o The Yes ( Duplicates Ok ) is selected if multiple entries of same data value are
allowed .
o The Yes ( No Duplicates ) option prevents duplicates
Field Validation Rules
0 The validation Rules specify the criteria for the data entered in the worksheet.
o A message can be displayed to the user if the data violates the rule.
o Expression builder button at the end of validation rule box is used to write the
rule.
Validation Text
[ Ch # GJ1 Table and Queiy 123 -
Computer Science Part 11
0 Validation Text is the message that is displayed when the validation rule for a
field is not followed.
Input Masks
An input mask controls the value of a record and set it in a specific format .
They are similar to the format property e.g. a telephone number field can be
formatted with an input mask to accept ten digits in the form ( 123 ) 456 7890: \
ll
'

0 The blank field would look like { . An input mask can be applied to
a field by following these steps .
In design view select the filed for input mask .
Click in the white space following input mask under the general tab.
Click the button to use the wizard or enter the mask such as ( @@@ )@@@
@@@@ into the field provided .
?

Following symbols can be used to create an input mask .


Input Mask Symbols
Symbol Explanation
A Letter or digit

0 A digit 0 through 9 without a + or - sign and with blanks displayed as zeros

9 Same as 0 with blanks displayed as spaces


# Same as 9 with +/- signs
> Letter

L Letter A through Z

C or & Character or Space

< Convert letter to lower case


> Convert letter to upper case

Q,7 What is an input mask ? In how many ways can it be created ?


A ns. Input Mask:
The input mask specifies the pattern for the data to be entered in a field. It
is similar to the format. However, it also displays the format in datasheet view
according to which data must be entered .
[ Ch # GJ1 Table and Queiy 124 -
Computer Science Part 11
There are two ways of creating an input mask for a field. These are using
the Input Mask Wizard and directly entering the input mask.
Creating Input Mask Using Wizard :
Input mask wizard works only with Text and Date fields. To add an input
mask to a field using the Input Mask Wizard .
o Open the table in the Design View.
0 Click on the field to which the input mask is to be added .
c Click in the Input Mask property in the bottom of the Design View w indow. The
ellipsis will appear next to the input mask text box.
0 Click on the ellipse and Input Mask Wizard will open .
0 Select an appropriate mask from the box and click next .
0 Modify the mask , if necessary, in the input mask text box.
0 Select the desired placeholder from the dropdown list .
0 Click Next button to move to the next step.
0 Select whether or not the symbols are to be displayed.
0 Click Finish button to complete the wizard task .
Components of Input Mask:
An input mask consists of three parts. These parts are separated by semicolons (;) ,

o The first part is the mask .


o The second part consists of input mask characters. These characters specify the
type of data that can be input in the field .
0 The third part specifies the placeholder. A placeholder is a character that is
displayed in the field where data is to be entered . Each placeholder specifies one
character of data. Placeholders are replaced when actual data is entered .
Input Mask Symbols
Symbol Explanation
A Letter or digit
0 A digit 0 through 9 without a + or - sign and with blanks displayed as zeros

9 Same as 0 with blanks displayed as spaces


# Same as 9 with +/- signs
9 Letter
[ Ch # G Table and Queiy -
L
^ Letter A through Z
125 Computer Science Part 11

C or & Character or Space


< Convert letter to lower case

> Convert letter to upper case


Examples of Input Masks :
Mask Field Data
( 999 )000- 0000 ( 042 ) 921 - 1995
( ) 756-7533
>LLL 9999 LXD 1112
>LL?9999 LH 269
AAa 123
12
Directly Entering Input Mask:
The Input Mask Wizard provides built - in masks for a few common fields. For
example, it can be used only for date and text fields. If some other type of mask is to be
entered, it has to be created by the user.
To create an input mask for a field without using the Wizard :
o Open the table in Design View ,

o Click in the field for which the input mask is to be created .


o Enter the input mask in the bottom half of the Design View. For example to enter
an input mask for entering telephone numbers as 042-756-7533, the input mask is
entered as : 0 Q0 \-Q00\-0 Q 00 ;0; _
Q 8. What is a primary key? How it is marked ?
Ans.
Primary Key

o Every record in a database table must be unique ,

o The uniqueness of a record is guaranteed by a field or a group of fields that


contain unique values in the table.
o This Held or the group of Helds is called the primary key of the table,
[ Ch # G Table and Queiy -
^ 125 Computer Science Part 11

o Designate the primary key Held by right clicking on the record and selecting
primary key.
o If none of the existing fields in a table produces unique values for every record, a
separate field must be added .
After doing above all when you will save the work it will ask you to give name to the
table. Give a meaningful name to the table and save it .
Q 9. How to create a table using Wizard and by entering data ?
Ans .
Creatine Table Using Wizard
Microsoft Access wizard provides an easy way to create tables. It provides
various table templates to create business and personal tables.
The following procedure is used to create a table using tabic wizard .
1 Open database window *

2. Click tables in objects pane.


3 , Double click the second option create table by using wizard . The table wizard
will start .
-
^
[ Ch # G Table and Que
Microsoft Access
^ 127 Computer Science Part 11
- JEliJ
File Edit View Insert Tools VVIldowi Help datatype ^

^ a y ma v
^ ^e «• S ^ I tf ^ 115-
1’ iS1 °S ® T
1? .
^ ^j
a d b l : Database ( Access 2000 file format
_ - PI XI

^
s
L- L
L Open Design -n 1 1 *- 1 tb-s6b“a
E w

Objects > . OwflbB table h design via w


I Tables li J Create table by using wizard
® ] Cr eate table by entering date
[jp Queries
Tabic Wizard
0 Forms
Which of the sample tables listed belou do you want to useta create your table?
0 Reports After selecting aitabllecategory , choose the sample table and sample fields you want to include
in your nsw tahle . Your table can include fields from more than one sample fable . If you ' re net
V| Pages sure about a Field go ahead and include it . It's easy to delete a Field later
3 Macros
i riiplt huAb ; Fields m Qy new tjble t
Modules ** Business
i n n HI HI HI ^
Personal M^ilingLstlD
roup; Prefix >
^ Sample Tables : Firstltenr =
# I Favorites
»
MiddleMame
Mailing List
Contacts
Customer;
Employees
9 LastMane
Suffix
Nitkfbane
<
hde
Products
Orders - Orgurii
^mnWariltf zl Bfraeme Field

Canoed < Back -


Mec t > Finish-

Table Wizard NUM

4. Choose the specific field for the table. Click on the business or personal option
button. Sample tabic will appear .
5. Select the sample table and then its required fields using the arrow buttons . ,

6. Enter a name for your table and also set primary key.
7. If you want to relate your table with existing one , Access can create the
relationship.
Creating [ able by Entering Data
o Microsoft Access provides the facility to create table by directly entering data .
o This option provides a blank datasheet .
0 The user can enter data in cells and click save button .
o It will prompt to add a primary key field .
O The fields are given names such as field 1 , field 2 etc . Names can be modified later
by the user,
[ Ch # GJ1 Table and Queiy 128 -
Computer Science Part 11
0 The data types of the fields are automatically specified according to the data
entered in the table.
Q 10. How to add , edit and delete records in a table?
Ans .
Addins Records
Data is entered into a table in datasheet view. To add data to a table
1 , Open the table in datasheet view
2. Type the data in first field of first record .
3, After typing press enter button, the cursor will move to the next field ,
4. Repeat the same for all fields.
5. When enter key is pressed in the last field of a record the cursor automatically
moves to the first field of next record.

* Editing Records
To edit records place the cursor in the record that is to be edited and make the
,

necessary changes. Use the arrow keys to move through the record grid.
* Deleting Records
The records can be deleted from a table in datasheet view ,
1 Open the table in datasheet view'.
2. Right click on the record selector of the record that is to be deleted . The record
will be selected and a pop up menu will appear.
3. Select delete record from the menu . A dialog box will appear to confirm deletion .
Click yes to delete the record .
Qll . How to Insert and delete a Field in a table?
Ans .
Inserting and Deleting Fields
E -
J

The best option for adding new fields is the use of design view.
1, Select the column before which the new column is to be added by clicking its
label at the top of the datasheet .
2. From insert menu select column
-
^
[ Ch # G Table and Que
^
To delete a field
129 Computer Science Part 11

1 Select the column to be deleted by placing the cursor in it.


2 , From edit menu select delete column.
Q 12. How to Resize, Freeze and Hide rows and columns. ?
Ans ,
Resizing Rows and Columns
The height of a row on a datasheet can be changed.
o The user can drag the grey sizing line between row labels up and own with the
mouse. The height of all rows is changed.
The column width can also be changed .
0 The user can drag the sizing line betw een columns.
0 If user double clicks on line, it will expand the column according to the longest
value in the column ,

* Freezing Columns
0 To prevent a column from scrolling when the datasheet is scrolled is called
freezing of the column .
0 When a column is frozen , it is always visible even when the datasheet is scrolled.
For example in a table that contains several columns, the leftmost column is not available
to view when the datasheet is scrolled to the right. If this column is to be kept visible, it is
frozen ,
1, Click in any rowr I the column that is to be frozen.
2 , Select freeze column from the format menu.
3 , The frozen column becomes the left most column and a black line appears in the
grid to the right of the last frozen column.
To unfreeze select unfreeze all columns from the format menu ,
• Hiding Columns
Remove the column from view is called hiding columns . It is a temporary process .
-
^
[ Ch # G Table and Que
^
Unhide Columns
130
U xl
Computer Science Part 11

Column: Close I
F Order Date
n Customer
F Order ID
F Employee
0 Recjuired Date
FI Shipped Date
0 Ship Via
0 Freight
0 Ship Name
F Ship Address
F ship City
F Ship Region
rz ^1 r d

1 Click in any row of the column that is to be hidden from view.


2. Select hide columns command from the format menu
To unhide column
1 Select unhide columns command from the format menu.
2 , The unhide columns dialog box will be displayed.
3 , The hidden columns are shown as unchecked in the dialog box .
4 , Click the checkbox of die column that is to be displayed again and click the close
button .
5. The column will be immediately displayed in the table.
Q 13. How to find and replace data in a table?
Ans .
Find and Replace Data in a Table
Find option is available in Microsoft Access to find a particular data item . This option
is available in edit menu . Using this option we can find required data item easily and
even replace it with the data of our own choice.
Find
1 Open the table in datasheet view
2. Place the cursor in any record in the field that you want to search and select Find
from the Edit menu .
[ Ch # G Table and Queiy -
3.
^ Enter the value criteria in the Find What box .
Computer Science Part 11

4. -
From the look in drop down menu select the field name.
5 , Now select the matching criteria from Match and click the More button for
additional search parameters .
6 , After setting all criteria click the find next button. To find further records on
same criteria keep clicking find next button .
Find aiiJ Replace U xl
Find Replace

Find What :

|Order ID
=
1 Find Nesd:

T anrel I
Look In: zi
Match : |Whole Field 3
Search ; [AI zi
Match Las* fv Swh ch Field* As For matted
1

1. To replace a data item select the replace tab .


2. Now again repeal the same procedure of find but in addition to that also write the
text in replace with text box .
3 , We have two additional options of replace and replace all.
4. Replace will perform the single replacement and replace all will perform the
change on all occurrences .
Q 14. What are the spelling and Auto correct and print options in MS-Aecess?
How these options are implemented ?
V ns .

Check Spelling and AutoCorrect


e This utility is used to locate the errors in spelling and grammar ,

o Autocorrect feature automatically correct common spelling errors.


This utility is available in tools menu.
o Short cut key is F 7 ,
[ Ch # G Table and Query -
^ '32 Computer Science Part 11

Spelling: English (U S ) ..
Not In Dictionary:
| Ignore lAddress' Field
Suggestions:
House Ignore Ignore All
Hue
Hogue Change- Change All
Hoe
Hour Add AutoCorreCt
Hope zl
Dictionary Language ; English (U,50 3
Options f p (Judo Last Cancel

Print a Datasheet
o Datasheets can be printed by clicking the print buttons on the toolbar or select
print from file menu to set more printing options.
Q15, How to create and edit table relationships in MS -Acccss ?
Ans .
Table Relationships
Q The relationship between two tables can be created by linking same fields of both tables.
0 The fields that are linked in both the tables usually have same name, data type and size.
etationships
- nj xj
St df n i l

HrMn RollNo
Nnmft dess
Address CredtHrs
DOB RecBoohs
show T ablc - ? x
g
Tables Queries: Sothi 1 Add

:
ShJCourse Close
i i

itJdenl

< 1 2U.

o Fields must contain the same kind of information.


0 It is not compulsory for fields to have the same name but same names are used to
avoid confusion.
[ Ch # G Table and Queiy -
0
^ ]
33 Computer Science Part 11
The table having primary key is called parent table and the table using the foreign
key is called child table.

To create a relationship

1. Click the relationship icon ng on the toolbar

2. The relationships window will appear

3 , Select the required tables but double click.

4 , Click close button after adding all tables.

5 * Click and drag the primary key field from parent tabic and drop to the same field
on child table.

Edit Relationships Jjxj


T able) Query : Related TableJQuery Create
[ student [stdCouse
w T

Cancel
ROIINQ •I Roll No

Join Type R R

Create NSW i

[ Enforce Referential Integrity

W Cascade Update Related Fields


F? Cascade Delete Related Record;
Relationship Type : --
One To Many

6. A dialog will appear select the enforce referential integrity constraints and press
create button

7. The relationship is created. A line joining the two related fields in the tables will
appear.
-
^
[ Ch # G Table and Que
^ ’34 Computer Science Part 11

Relationships - inJid
ffrira

SG9BHI Roll No
Name
Address Gass
|DQB Cre ditHrs
RjecBooks

ilj

The datasheet of a relational table will provide expand and collapse indicators to
view sub datasheets containing matching information.
§ Student ; Table
-|P| | X

Q . 16 What is a join ?
An $. The query that extracts data from two related tables in a database is called a join .
The join extracts data by looking into both the related tables ft first extracts the
,

required record from the first table and then it looks for its corresponding record
in the second table. Tt uses the relationship between the two tables to join the
records in both the tables .
Q 17 , What are relationship and join? Also discuss referential integrity *

Ans .
Relationships and Join
It provides a great advantage while handling data in related tables .
0 Before relational database there was only option of flat files .
[ Ch # GJ1 Table and Query 35
] -
Computer Science Part 11
o Hat file is a big block of data like an excel sheet.
[ Ch # GJ1 Table and Que
^ 135 -
Computer Science Part 11

o You can t analyze the data from all aspects in a flat -file .
0 With relational database design you can view data as many form as you want .
v Joins are what makes relationships work . In most cases, you want to bring
together or perform an action on data from more than one table or query
For example: You might want to view a customer's information with the orders the customer
placed. To see this information, you need data from the Customers and Orders table > L +

Referential Integrity
_ c ~y

* Referential integrity is a system of rules that ensure that relationships between records in
related tables are valid and that you don ' t accidentally delete or change related data.
* To enforce referential integrity both tables must have at least one common field ,
which have same data type and size.
You can set referential integrity when all of the following conditions are met:
* The matching field from the primary table is a primary key or has a unique index .
* The related fields have the same data type and fieldsize .
The following rules apply when you use referential integrity:
* You can ' t add a value in the foreign key field of the related table that doesn’t exist in
the primary key of the primary table . However, you can enter a Null value in the
foreign key, specifying that the records are unrelated .
* You can’ t delete a record from a primary table if matching records exist in a related
table.
For example : You can 't delete an employee record from the Employees table if there
are orders assigned to the employee in the Orders table.
* You can 't change a primary key value in the primary table, if that record lias related
records.
For example: You can 't change an employee ' s ID in the Employees tabic if there are
orders assigned to that employee in the Orders table.
Cascade Update Related Fields and Cascade Delete Related Fields
If the cascade update related fields and cascade delete related records check boxes
are checked in the edit relationship dialog box , whenever you update or delete a record in
primary table the effect will appear in the related table automatically.
Q 18. What is sorting and filtering? Also discuss different options available in them.
Ans .
Sorting and Filterin s
J

Sorting and filtering allows viewing records of a table in different than ordinary way.
[ Ch # G Table and Queiy
^ T37 Computer Science Part-11

Sorting il li
Arranging data in alphabetical order is called sorting , It can be either ascending or
descending.
1. To sort records in a table open it in datasheet view.
2, Click on the tieId which you want to sort .
3. Choose Sort command from Records menu and then select sort ascending or
sort descending . Or
4. From the tool bar select zl ascending button or
To remove a sort
descending button .
^
1. Open the tabic in datasheet view'
2, Select remove filter/sort option from the records menu .
3, The data in the table will be displayed in the default order.
Filterin 8
A niter is used to extract the records that match a set of criteria. Fillers are
basically queries but they only appear to open tables or forms.
v>
Filter by Selection
This feature is used to filter records that contain same data values in given field
e.g. it can filter all records that have a value “ Sales Representative" in title field.
1, Place the cursor in the field according to which the niter is to be applied
2. Click Filter bv Selection button on toolbar or select Records Filter — Filter
bv Selection from the menu bar.
Id8

£3 Microsoft Access -|q | *


File Edit Tfiaui Tr^ert Format Records lools Window Help how sorting works

fee - y a
« § a^ * %s « % it li v u® n *w ® -M - .
9 Employees : Table Oj x ]
^
| Last Name | First Name Trie Title Of C Birth Date Hire Date | Addi
* Devoid Nancy S-ales Repre sedative Miss QB- Dec- 1963 C 1 - May- 1932 507 - 20th A
+ Levelling Janel Sales_ R & 3 reserilative Miss - -
30- Aug- 19G3 01 Apr 1992 722 MOBS B:
* Peacock Margaret S-ales Representative Mrs . 19- Sep- 1958 C3- May- 1933 4110 Old Re
* Suyama Michael Sales Re p re se illative Mr . 02-JuI- 1963 17- Oct- 199G Coverttry Hoi
* King Robert S-ales Representative Mr, 29-May- 1960 Q2-Jan- 1994 Edgeham Hr
Dodisworth Anne Sales Repress Native Miss Q2- Jul- 1969 15- Nov- 1994 7 Houndstoo
*
RlWOrdl H * 3 F | n | nn | of O (Filtered} ij

Employee's title , FLTR NJM /A


[ Ch # G Table and Queiy -
^ '38 Computer Science Part 11

Filter by Form
^
This feature is useful if the table is large and it is difficult for the user to find the
record that contains the value according to which the filler is to be applied . This table
creates a blank version of the table with drop down menus.
1. Click on the field lo enter the filter criteria under default look lor tab of filter by
form window.
2 , Click Or tab at the bottom of window to specify another criteria .

3 , Click apply filter V button on toolbar after selecting all criteria to filter .

The following methods can be used where the drop down menu appears instead of
selecting an absolute value.
Filter by form
Format Explanation
Like “ * Lahore ” Selects all records that end wdth “ Lahore ”

<= ” F” Selects all records that begin with the letters A through F
>4/5/99 Selects all dates sine 4/ 5 /99
o50 Selects all records not equal to 50
Saving a Filtc J

L Select file — save as query from the menu bar


2. Enter a name for the query
3. Click ok . The query is now saved with in the database.
[ Ch # G Table and Queiy -
^ 139 Computer Science Part 11

Removing a Filter
1. Click the depressed Remove Filter toggle button on the toolbar
E Microsoft Access
File: Edfc View Insert ^orrriat Records Tools Window help

- a a sat? * a
^ « a u y'sfv] M *
Remove Filter
w © ’ 5) ,

Q 19 * What is a Query? Alsu discuss its uses and advantages


Ans .
Introduction to Queries
o A query is a question that requires some data from the database.
o A query is created by specifying fields to display from a table or another query.
o It can also specify condition for extracting data .
0 Queries select records from one or more tables in a database.
0 These extracted records can be used for analysis.
o The resulting collection of records called a dynaset (short for dynamic subset) .
0 The query is updated whenever the tables are updated .
Uses of Query
1. Extract records according to the specified criteria
2. Choose the Helds to display in the resull
3 , Sort the records in a specific order
4. Calculate fields and summarize data .
A query can be given a name and it can be saved, Tt can also be used repeatedly . It can be
used as a source of records for forms and reports .
[ Ch # GJ1 Table and Queiy 140 -
Computer Science Part 11
Advantages of Query
Joining
Query can be executed against multiple tables . In the case of related tables query
join them and extract the data as a single dataset.
Flexibility
Query is a flexible way of manipulating data in a database. It provides facilities to
add , remove, modify and search data.
Easy to Use
Queries are easy to use. Any one can execute query just by double clicking it .
Q 20. What are the different types of queries available in MS-Access?
Ans.
Types of queries|
There are five types of queries described as follows.
Select Queries
A select query is the most common type of query.
It retrieves data from one or more tables and displays the results in a datasheet
where you can update the records (with some restrictions ) .
You can also use a select query to group records and calculate sums, counts,
averages, and other types of totals.
Action Queries
0 An action query is a query that makes changes to or moves many records in just
one operation.
There arc four types of action queries :
1. Delete Queries:
0 A delete query deletes a group of records from one or more tables.
0 With delete queries, you always delete entire records, not just selected fields
within records.
For example : You could use a delete query to remove products that are
discontinued or for which there are no orders .
2. Update Queries :
0 An update query makes global changes to a group of records in one or more
tables.
0 With an update query, you can change data in existing tables .
[ Ch # GJ1 Table and Queiy H" -
Computer Science Part 11
For example: You can raise prices by 10 percent for all dairy products, or you
can raise salaries by 5 percent for the people within a certain job category.
3. Append Queries :
o An append query adds a group of records from one or more tables to the end of
one or more tables .
o To avoid typing all this information into your own database, yourd like to append
it to your Customers table.
For example : Suppose that you acquire some new customers and a database
containing a table of information on those customers,
4. Make-Table Queries :
0 A makc-tablc query creates a new table from all or part of the data in one or more
tables.
Make-table queries are helpful for creating a table to export to other Microsoft
Access databases or a history table that contains old records.
Crosstab Queries
Crosstab queries are used to calculate and restructure data for easier analysis of
data.
o These queries calculate a sum , average, count , or other type of total for data that is
grouped by two types of information one down the left side of the datasheet
and another across the top.
Parameter Queries
o A parameter query is a query that when run displays its own dialog box prompting
you for information such as criteria .
,

For retrieving records or a value you want to insert in a field.


You can design the query to prompt you for more than one piece of information;
For example : You can design it to prompt you for two dates . Access can then
retrieve all records that fall between those two dates .
Q 21 * How to create a Query using Design view?
Ans .
Create a Query in design View
Following are the steps to create a query in design view .
1. From the database window select queries object.
2 , Now select create query in design view option from right side pane .
3. A show table dialog box will appear with the name of tables.
4. Select the required tables by pressing Add button or just by double click .
[ Ch # GJ1 Table iinci Query 142 -
Computer Science Part 11
5 * Add fields from the tables to the query grid by double clicking.
6 , Enter the criteria for the query in the criteria field .
7, Wildcards and expression builder can also be used to specify the criteria ,

Query ] : Select Query - inlxl


E
-
fli dprs DO
OrderlI >
*
ProductlD
QrderiD
UnitPrice
CusiomsrIC* Quantity
Enfiptoye*I[>
Discount T

OnderDabe

i l
Field: Oi derlD Cu stonier 1C UnitPrice Quantity
Table: Orders Orders Order Details Order Details J
Sort:
Show:
Criteria: "B9BEV"
a 0
or:
[ Ch # G Table and Queiy -
^ 43 Computer Science Part 11

8. After you have selected all the fields and specified the criteria click the * run
button on the toolbar.
gg8 Query 1 : Select. Query -|D| *1
Order ID Customer Unit Price Quantity
B 's Beverages J8.00 BO
10289 B 's
10471 B 's
Beverages
Beverages
128.60
124.00
Ell
BO
10471 B 's Beverages
10484 B 's Beverages
*30.40
$8.00
20
14 —
10484 B 's Beverages 14.70
10484 B 's Beverages
*42
*t15 CC40 "
10538 B 's Beverages . 7
10533 B 's
10539 B's
Beverages
Beverages
*34.80
J6.00 8
10539 B's Beverages
10539 B 's Beverages
* $2.50
10.00 15
15
10539 B'S Beverages
10578 B 's Beverages
*118.00
20.00 6
201
Record : M I ^ If 1 I M U*| cf 22

9. You will see the result of query in a grid like table.


10 , Save the query by clicking the save button.
Specifying Criteria

* Criteria are limits you place otl a query to identify the specific records you want to
work with .
For example: Instead of viewing all the suppliers that your company uses, you can
view just suppliers from Japan . To do this you specify criteria that limits the results
,

to records whose Country field is "Japan".


To specify criteria for a field in the design grid, enter an expression in the Criteria
cell for that field . The expression in the preceding example would be "Japan ". You can
use more complicated expressions, however, such as "Between 1000 And 5000".
Wild Cards
Wildcard characters arc used as placeholders for other characters when you arc
specifying a value you want to find and you :
* Know only part of the value .
[ Ch # G Table and Queiy -
*
^Want to find values that start with a sped lie letter or match a certain pattern
144 Computer Science Part 11
.
Wildcard characters are meant to be used with fields that have the Text data type.
You can sometimes use them successfully with other data types, such as dates.
A list of wildcard characters is given below.
Query Wildcards and Expression Operators

Wildcard/Operator Explanation

Matches any single alphabetic character e g B? U finds ball, bell


+ >

and bill

* Matches any number of characters . ft can be used as the first or


last character in the character string e .g. wh * finds what, white,
and why

<1 Value less than 1

>=0 Value grater than or equal to 0


n ,
< > X” Not equal to ( all classes besides X )

Between l and 100 Numbers between 1 and 100

Is Null Find records with no value

Is Not Null Find all records that have a value

Like “ a* ” All words beginning with “ a”

> 0 and <=10 All numbers greater than 0 and less than 10

"AM ” or "Salman ” Values are All or Salman

Q 22* How to create a Query using Query wizard?


Ans ,
Query Wizard
[ Ch # GJ1 Table iinci Query H5 Computer Science Part-11
MS- Access query wizard will easily assist you to begin creating a select query.
1 Click die create query by using wizard icon in database window.
2 , Select the fields you want to be included .

S imple Query Wirard

Which fields do you wart in your query?

Vflucan Ch& ose From more Ehen one Cable or query


ii
Tables / Queries

|Query : alphabetical List qf Prodi -|


Available Fields ; Selected Fields:
Prgductio ProductName
SupplierlD OuantityPerLhft
CategorylD » UhtsInSock
UmtPrice
UnitsOnOrder
<
ReorderLevel
Discontinued «

Cancel < Bach Next > Finish

3. Click next button .

Simple Query Wizard

Would you like a detail or summary query ?


1 -Milan 111 111 i i i m r i i i i i n 111111 uriwi IIIIIB m i l 11 IIIITII m i m i i i m n iiiiiiiiiiimMiiriwiiiii 11 m i n i i i i i i m i i i i n ill
1
(
* Detail fshows every field of every record) i
P Summary

Summary Options ,

Cancel < Back Next > Finish


[ Ch # G Table and Queiy Computer Science Part-11

4.
^ 146
From this screen select the detail view or summary view . Detail view will show
every field of very record and summary view will give the summarized data.
5. Press next button .
Simple Query Wizard

What title do you want For your query?


habetical List of Products Query

That's- all the information the wi2ard needs to create your


query .

Do you want to open the query or modify the query's design?

OjDfcn the query to view information .


C Modify the query design ,

Display help on working with the query?

Cancel < Back rde- xt > Finish

6, On the next window enter the name of the query and click finish .
Find Duplicates Query
This query will filter out the records in a single table that contain duplicate values .
1. Click on newp button on the queries database window .
2+ Select Find Duplicates Query Wizard
New Query

Design View
* n
1 KKK XXK || Simple Query Wizard
2 _KKK_ KXW
3 XXX IKH I 2 KXX HXK Crosstab Query Wizard
2 ox :::: x I 2 HXX X.KH
Find Duplicates Query Wizard
Find Unmatched Query Wizard
This wizard creates a query that
finds records with duplicate field
values in a single table or query

Cancel
[ Ch # GJ1 Table and Query > 47 Computer Science Part-11

3. Select the table or query that you want to use in this query.
hind Duplicates Query Wiz ard

Which table or query do you want to search for duplicate field values?
1 mm |
2 HI if HIE iTH
3 KKK HHK K | For example, to Frid cities with more than one customer you would
2 m KHK H 'fVH choose a Customer table below.
~
4 KH KHK KHK [
2
[ Table ; Categories
« itItit
XJW H K
Table ; Customers
2 xxx xxx m
Table : Employees
Table : Order Details
Table ; Orders
Table : Products
Table ; Shippers
Table ; Suppliers

View
f* Tables C Queries P Both

Cancel < Back Next > Finish

4. Select the fields that may contain duplicate values using arrow buttons.
Find Duplicates Query Wizard

Which fields might cort-sin duplicate information?


1 KXK KSB! !-IK " For example, It you V9 looking For cities with mors- than one oitfgmerj y&u
2 H:: K would choose City end Region Fields here
3 KXX HI: : I::: H
;
2 -!!-!! HSf Ml IK Avail. abls fields ; Duplicate- value fields
4 KXI m Kix
CustcmerlD LompanyfJame
CointaciName Address
Conte ctTitle >> c* y
Postal Code Region
Country
Phone <
Fax

C ancd < Etack [ Most > Finish


[ Ch # GJ1 Table iinci Queiy 148 Computer Science Part-11
5. Press the next button.
Find Duplicates Query Wizard

Do you want the query to show fields in addition to those with duplicate values?

1 nil HK
2 m OK : MM For e, if you chose to look for diplicate City valuesj -you co Jd choose
3 KHii OK KK ~ Customer Marne and Address here.
2 »1 0»
i Ml UK tm
fM
Available Felds : Additional query Fields :
jCChtad Title I |CustWBf ]p
Postal Code Conta ctName
Count ry »
Phone
Fax
<
c<

Cancel ^ Eadk I rje -t >


'
| Finish

6 , Now select the field which you want to display along with the selected fields.
Find Duplicates Query Wizard

What do yew want to name yocr query?

Do you want to view the query results, or modify the query design?

<* Wew the results .


P modify the design.

Chsplay Help on wgrlno with the queryi

Cartel < Back Next > Finish

7. Name the new query and click Finish.


[ Ch # G Table and Queiy -
^ '49 Computer Science Part 11

Delete a table from the query


Click the table s title bar and press delete key on the keyboard

Sorting Query Field


By default data extracted by queries are not sorted. However wc can sort any field
explicitly in ascending or descending order .
1. Click on the sort row in the field column you wanl to sort ,
2, Click on the down arrow , a menu will appear
3. Click on ascending or descending to sort accordingly.
Performing Calculations in a Quer
A query can be used to perform a calculation on a group of records. The user can
perform calculation in a query by using predefined calculation in MS-Access . The user
can also create a custom calculation according to the requirement ,

MS- Access provides following calculation types.


Group by: identified the group lo calculate.
Sum; Add the values.
Avg : Average of the values,
Min : Finds the minimum value.
Max: Finds the maximum value.
Count: Counts the number of values.
StDev: Calculates the Standard Deviation.
Var: Calculate the Variance.
First : Finds the first field value.
Last: Finds the last field value.
Expression : Creates a calculate field through an expression .
Where: Indicates criteria for a field not included in the query.
MICROSOFT ACCESS FORMS
AND REPORTS
Qi - What is a form? Also discuss its uses and advantages.
Ans .
Form :
o A form is a type of a database object that is primarily used to enter or display data
in a database.
o A form is constructed from a collection of individual design elements,
o These elements are called controls.
o The common elements are text boxes, labels, check boxes etc . these elements are
used for different purposes .
Uses of Form
o Form is used to add data in the database
o It is used to delete data from the database
,

o Using form data can be modified in the database ,

o Data can be viewed using forms ,

o Data can also be searched with the help of forms .


o You can also use a form as a switchboard that opens other forms and reports in
the database.
o Forms are also used as a custom dialog box that accepts user input and carries out
an action based on the input.
Advantages of Forms
Easy to Use : Forms are easier to use . It contains simple graphical components that
simplify the process of data manipulation .
User Friendly: Layout of forms is graphical and user friendly. Anyone can work on them
easily ,
[Ch #7] Microsoft Acoess forms & Reports 158 -
Computer Science Part 11
No Technical Expertise Required : An ordinary user can use the forms for data entry. No
technical knowledge or training is required for simple forms.

Time Saving: Forms require less time to enter data. Access provides master detail forms
to enter data more conveniently.

Flexibility:Forms are very flexible in its layouts. Many layouts are available in MS-
Access for the case of use.

Q 2. Write down the procedure of creating form using w izard .


Ans .

Create Form bv Using Wizard

1 , In database window select form from the object pane.

2 Select the create form by using wizard option.


,

3 , A dialog box will appear .

Hum Wizard

Which fields do you want on your form?

J You e-an choose from more than one table or query ,

Tablet jQuer 1 es
[Query: Alphabetical List of Prodi ~ |
Av ailable Fields : Selected Fields :
PraductTD ProdurtName
SupplierlD Category ID
Qu^ntityPerUnit UnitsQriQrder
UnftPrice
UntalnScck
:Reorder Level
<
Discontinued
CategoryName

Cancel efiatk | Milt > | Finish


[Ch#7] Microsoft Acoess forms & Reports 59
] -
Computer Science Part 11
4 . From here select the table/qucries and then also select a field or set of fields from
available fields . This selection can be done by using arrow button . After this press
next button .
Fnrm Wizard

Csn l > Finish


^

5. At this screen we can select the lavout


- of the form . Press next button
u
[Ch#7] Microsoft Acoess forms & Reports i Go Computer Science Part-11
Form Wiza rd

6 , Now select the visual style for the form and press next button .

Form Wizard

What title do you wart For you' form?

0 phabetical l_Kt of Products

That’s all the information the vizard needs to create your


Form ,
Dc yo J want to open the form or modify the Fornn'e. design?

** Open the form to view or enter information,

r Modify the form's design .

Di-splay Help on working with the Form?

Cancel < BacK Next > Finish


[Ch #7] Microsoft Acoess forms & Reports 161 Computer Science Part-11

7. This is the final screen for form creation. Here enter the name for form and press
finish button *

Q3- Discuss different layouts of a form in MS-Access.


Ans .

Form Layouts
There are four layouts for forms in MS- Access ,

* Columnar Form
o Columnar form is used to display one record at a time,
o It displays text boxes and labels for each field .
o Columnar form provides a record navigation bar to traverse through records *

* Justified Form
o This form is used to display one record at a time ,

o The fields are justified according to the window ,

o The labels are displayed on the top of each field .


[Ch#7] Microsoft Acoess forms & Reports 162 Computer Science Part-11

g@ Alphabetical List of Pmdurts


—! I xl
Ptoducl ID Product Name Supplier
[] Chef Anton's Cajun Si easuning New Orleans Cajun Delights
3
Category Qu^rtty Per Unit Unjl Price Units In Stock
Condiments TT43 6 os jars $22 00
, 53
Units Cm Order FIeorcter Level Discontinued Category Hams
1 1 Condiments
Rewrd ; < I < If 4 | H |» *| IJF e?

* Tabular Form
o In tabular forms multiple records are displayed with fields in columns and records
in rows .
o Each row represents a record *

o It is best for the situation when you want to display a few records and of narrow
fields and you want to see several records at the same time .
31 Emplnyee-sl - *
Last Mams First N < Title Address Postal Country home Phone ^

iDavofo Nancy |Sales Represent - 1507 20th Ave E . |9sn 22 |USA |f 2oej 555-99*
Andrew |VIM Resident S [ 90BW Capitol V/ oy
, . |9B40 i |USA [pejss&M
[Janet |Sales Represent. [ 722 Mos aj
|Leveling
|Margai [ Sales Represent. -110 Did Redmond Rd.
^^ lvd
193033 |USA [|206J 555- 341
[99052 [USA [1206) 555-91 £
| -'eecock
14
Buchanan |5 tever |Sdes Manager 114 Geirert Mill [W l f [UK |[71] 35&4Bti
Suy ma
^ |Micha* | Sdes Represent' | Coventry Hou |EC2 7. V J K |(71 ] 55^777:
[King Robert |$ el«s Represent. | Edgeham Hobw |RG19 |JK ||71 ] 55S559E
|l auia [inside Sales CM [ 47260 lib Ave. N E 199105 |USA [1206] 5551 If
"

Callahan
Dod;worth [ Anne [Sales Represent. 7 Haundstooth Rd. |WG 2; [UK [|71 ] 555444*
*
Recrrd ; M I i II 6 IHI of 9 u I —

o It saves time of scrolling records to analyze them ,


* Datasheet Form
o A datasheet form displays data in datasheet view ,

o Each row displays one record at a time .


[Ch #7] Microsoft Acoess forms & Reports 163 Computer Science Part-11
o Datasheet form provides record navigation bar to navigate through different
records <

o This type of form is often used for the basis of sub form.

£3 Alphabetical List of Products!


Product ID Product Name Supplier Catec|on ^
fl Chai Exotic Liquids Beverages
2 Chamg Exotic Liquids Beverages
3 Aniseed Syrup Exotic Liquids Condiments
4 Chef Anton 's Cajun Seasoning New Orleans Cajun Del Condiments
6 Grandma 's Boysenberry Spread Grandma Kelly 's Heme Condiments
7 Uncle Bob's Organic Dried Pears Grandma Kelly 's home Produce
8 Northwoods Cranberry Sauce Grandma Kelly 's Home Condiments
10 llkura Tokyo Traders Seafood
11 Gueso Cabrales Cooperativa de Quesos Dairy Products
12 Gu§ so Marichego La Pastors Cooperative de Quesos Dairy Products
ih -
1 11 E I IPV4 C1 —- —
1 -J
1 s

"
Record: N 1 I H |i l
* of 69 ll I i
[Ch#7] Microsoft Acoess forms & Reports rS4 Computer Science Part-11

Q4- Write down the procedure of creating form using design view .
Ans *
Create Form in Desisn View
To create form in design view follow the following steps
1 Select form from the object pane
* ,

2 . Select the create form by using wizard option .


EU Forml : Form
= jn| *1
I - -1 - I p a

^ E
- p

- B
4 I - 8
4 i
- 5 ’ aJs|
f Detail
'

!
"5
r 9
P P
P 11
^ r
r
9 9 i
Bui r
p
r
a i i p p a
9
! p
^• i m
a i p p r a s
9
- p p
p
a a i p p
r
a i
I n
9
r 9
. a aa - a a . a a aa .. a u . a
i a a
L
fa a a
i
fa
-
i
i L fa a a .
i L
i fa a
L
fa a a
i i
i
i
fa
J i L i i
i fa a fa a k a a
I fa
fa fa a a
J I
i
-
i fa a fa a i
i
fa fa a
J
.1 a fa a a .
I
i .
i fa a a

i n
' : ; i wOEiiCMFry '
Muffle :: jCompanylName p r P 9
! P
P P 9 9
!
I
!
" P B P
! !
i
"
r P 9
,B
P 9 " P H 9
LI
L L a ILL J L a J LILB a L LI

Aft ab| P 9 P 9 P P 9 9 p P 9 P P P P s
M Customers
r r r r
P r B i I B i l l i
. B 9 B 9
.
I B 9 9 i e B i
. r. B 9 9 r B
fa a a a

m i B a a i i i fa a i B a a la B a a a
j i i la fa

M _::
I
r a a i i i P r p 9 r 9 9 1 r P9
fa fa a a
9 L 1 1 1
fa a a
- ddress k fa
- a a .a a
i
CustomerJD
w
i a

ff I P 9 “I
1
P 9 P P 9
9
P P! B 9 P 9 P B P B 9 P 9 CcmpariyUame
L aJ L BJ a a B a a L mLaa LI a a a L fl L a L a

am CcrtactName
fl fa fa

r P p 9 p B r m 9 9 P 9
I

r i d!
ra
B
i i
a a
a
B
a
i h
r
.
i
B 9
a u
i I
1 i

h a
r
a
r
fa
m i
r
B
B r
B B B
a i d
B 9
.
i Baa a
IBBrill
19 B 9

i il
a
r
.
i a
a
r
. .
i
B

faifaii
r
i H
B 9 i
a i
r
I B B
B9
Contact Tills
-I El i B a
Adcress
r -v P 91 P 9 9
9 9
9 ' P
P
P
n 9 9 p p 9 B '1
9 P
P
9
9
P 9 P
p i n
9 9
9 9
r p9
I P 9
City
a a fa a . a . s aa a
I B i H .
i fa a
PIS fa B
-
I it fa fa
Regon
2 a
PostalCotJe
CuLntry
m \ Phofte
Fax

< 1
3 A form in design view will appear .
,

4 Add controls from the toolbar to the form and set their control source property.
,

5 After placing all the required fields and their labels on the form right click the button
,

at left upper comer.


6 Select the form view and see the form you have just designed in data entry mode .
,

Points to consider while Editing Forms


* Grid lines
o By default horizontal and vertical dotted lines appears on the form in design view,
c These are called gridlines ,

o These lines arc very helpful while placing controls on the form arid make them
aligned to each other and to the form.
* Snap to Grid
On the Format menu, click Snap To Grid ,

If Snap To Grid is turned on, when you create a control by clicking the form , repoit
or data access page, Microsoft Access aligns the upper-left comer of the control to the
[Ch #7] Microsoft Acoess forms & Reports 165 -
Computer Science Part 11
grid . If you create a control by dragging, Access aligns all comers of the control to
the grid. If you move or resize an existing control , Access lets you move the control
or its boundary from grid point to grid point only.
When Snap To Crid is turned off, Access ignores the grid and lets you place, move,
or resize controls anywhere on the form , report, or data access page .

* Resizing Object
o Select the control or controls that you want to resize .

o To select more than one control hold down the SHIFT key and click each control ,
,

or drag a rectangle over the controls.

o Drag the sizing handles until the control is in the size you want.

* Change Form Object Type


The object of the form can be changed easily without creating a new form. The form
object type can be changed as follows ,

1. Right click on the object with the mouse

2. Select change to option

3 Select and available object type from the list


*

* LabcJ /Objcct Alignment

Each form object and its label are bounded Both move together when any of them is
*

moved . The user can change the position of the object and label in relation to each
other.

* Tab Order

This option is used to alter the tab of objects on form . The user can change the order
as follows .

1 Select tab order from view menu


,

2. Click the gray box before the row whose tab order is to he changed ,

3 , Drag it to a new location and release the mouse button .


[Ch #7] Mion>soft Acoess forms & Reports 166 -
Computer Science Part 11

Tab Order l ] *i
Section Custom Order:
Form Header Customer!D
'
Comp any Name
Detail Con tact Name
Form Footer Con tact Title
Address
Click to select a rc or
dick and drag to select ^ City
Region
multiple rows. Drag Posta iCode
selected row(s) to move Country
them to desired tab
order ,
Phone

OK Cancel Auto Order

* Form Appearance
The form appearance can also be changed as follows
1. Right click on the form and select color from Fill back color option.
S 1. LIJ I

pO / \ Font-/rFore Color
Nl an -
l "1 B
— [

2 Change the color of individual form object by highlighting the object and
,

selecting a color from font fore color from formatting toolbar.


3. the font , font size, font effect , font alignment , and border can also be modified
using formatting toolbar .
* Page Header and Footer
Header and footer added to the form will only appear when printed.
1 Select page header /footer from view menu
,

2 Select page numbers form insert menu


,

3 Select date and time from insert menu


,

Q.5 What is a toolbox briefly describe the controls available on the toolbox?
Ans . Toolbox :
The toolbox contains a set of tools or controls that arc used to design a form is
Design View ,
[Ch #7] Microsoft Acoess forms & Reports 167 Computer Science Part-11
The toolbox is displayed or hidden using the Toolbox Icon on the toolbar. The
Toolbox Icon is a toggle button . Clicking on this icon displays the Toolbox if it is hidden .
Similarly, clicking the icon hides the toolbox if it is being displayed.
Toolbox Controls :
Toolbox contains controls that are used to create a form , These controls include
buttons, check boxes , text boxes, etc . Toolbox contains most of the tools that are usually
needed for creating a form. However, new tools can also be added to the toolbox.
Following is a brief description of the controls available on the Toolbox :
Control Description
Select Objects It is not a control . It is used to manipulate the controls on the
forms. For example, it is used to select , move, resize, align ,
etc. controls on the form.
Text Box It is used to display data from or input data into tables .
Label It is used to display data. The data displayed is this control
cannot be edited directly by the user.
Option Button It is also called the radio button. Radio buttons are used as a
group in which only one radio button can be checked at a
time.
Check Box It is used to get an input from the user . It can have two states :
checked and unchecked.
Combo Box It is used to provide a short list of items.
Command Button It represents a click -able button on the form . It is used to start
an action when it is clicked .
List Box It is used to provide a list of items .
Image It is used for displaying images. This control has fewer
capabilities than the Picture Box Control .
Line It is used to draw' lines .
Control Wizard It is used to create the List Box , Combo Box, option Group
and command button controls w ith the help of a wizard .
Option Group It is used to provide the user a group of options from which
only one can be selected . All elements in a group of options
are mutually exclusive.
Toggle Button It is used to either select or not select an option . Both text and
pictures can be placed on this button .
[Ch #7] Microsoft Acoess forms & Reports 168 -
Computer Science Part 11

Unbound Object Frame It is used to display an OLE object or picture on the form (or
report). The object will remain constant and not change as you
move from record to record .
Bound Object Frame rt is used to display (or to edit /add ) the OLE object or picture
attach to the record . It is used as bound control.
Page Break It is used as Page Break in Form or report .
Tab Control It is used to create tabbed with many pages .
SubForm / SubReport It is used to add a subform ( or subreport ) into the form .
The form that contains the sub forms is called the main
form ( or Report ) .
Rectangle It is used to draw rectangles on the form.
More Controls It is used to display more controls that are available in MS
Access toolbox .
Q .6 What is a control? Explain its different types.
An $ + Control :
A control is a graphical object. It is used to:
o Obtain and display data from database tables .
o Input data into database .
o Perform an action.
Types of Controls:
There are three types of controls. These are:
o Bound controls.
o Unbound controls .
o Calculated controls .
Bound Controls:
The control that is connected to a field of a table is called the bound control. It
gets data from a field of the table and displays it on the form. The control source property
is used to assign a field of a table to the control . The text box is the most commonly used
bound control .
Unbound Controls:
The control that is not directly connected to a table is called the unbound control .
These controls arc used to display information such as labels and draw lines, rectangles, etc.
[Ch #7] Microsoft Acoess forms & Reports iSg -
Computer Science Part 11
Calculated Controls:
The control that contains an expression and displays the calculated data is called
the calculated control The expression usually returns the data from database tables.
Q 7. How to add list and combo boxes on a form?
Ans .
List and Combo Boxes
o List box and combo box are used to display a list, which appears on the screen ,
from which the user can choose items .
o These objects are used if the possible values are small and limited ,

o The user can enter value quickly and easily by using these objects ,

o List box and combo box differ in the number of values they display.
o In list box more than one values can be visible at a time but in combo box only
one value is visible at a time.
o In combo box all values can be viewed by using its drop down button .
Cornb o Box - List Box
Reed Hall a
Ben Hill Griffin III Halil
Reed Hall
Whitaker Hall

Adding list Box and Combo Box to Form


1. Open the form in design view.
2. Select toolbox from view menu .
\
3, Make sure that control wizards button is pressed .
4. Click the list or combo box tool button and draw the outline on form .
5. The combo box wizard dialog box will appear .
[Ch #7] Microsoft Acoess forms & Reports 170 Computer Science Part 11 -
Luiiihju BAH Wizard

This witzard creates a ccnmbo box, which displays a list of values you
tan choose From ,. How do you want your combo bo to get its
valued *
KKMKK
*
nmumxm IliCII ilu
-
P 1 want fcht combo box to look up the v alues In a table or query . |
I
-
IIB BIB
^ l i r^ i i
..
iB lIUJIUi 1

BBB
..

n
IIMII ...........

u n i i i f l e -
! IIUUIM ill

-
. . . ill all

!9 I IV 9 III 9 I IIBIIIBI III SIB


. lAEUEJI 1 ... ...... ........
1 ill

IB
MBIUill UI1U

! IIBIIBBI IIP
^

^ I will type in the values that I want

Cancel c Back We*t > Finish

L Select source type for the list or combo box values and click next
2. The next option is about selection of values for list box or combo box .
Combo BOH Wizard
Which table or query should provide the values for your combo
box ?
-j£ 9 mit|1ll - B B B B I B I IB 19 111 m i 1191 i n i U B I H B f l f I T B I I P9 I 1 111 111 I 1191 9 B 9 I 9 19 B 9 19 B I i r i l I PI I 119 I B 19 I B
— B f I P I P B 9 I PI 9 1H 9 119 B 1*1 I MB fl

: Table ; Categories
Table : Customers
Table : Employees
Tahle: Order Detail?
Table : Orders
Table ; Products
Table : Shippers
Table ; Suppliers
rView
(? Table ? f Queries C Both

C^ntel < Back f Next > Finish

3. Select the table OT query from which the value will come to combo or list box ,
4. Click next and choose the fields .
[Ch #7] Microsoft Acoess forms & Reports Computer Science Part-11
' 71
Combo BOH Wizard

Which fields contain the values you want included in your combo
box ? The Reids yo> j select: become columns in your combo box .
m SHE m m
HM XKK
XKX KKE K O XXX

XXXXXX
J
Available Fields: Selected Fields :

CateacfvNaitfie | - I
CtfWOfVH?
LSJ
|I ra ra i |
S

»
<
«

Cancel | < £ack |


^ext >
f | Fjni h
^

5 H Set the width of combo box using mouse and press next.
Combo BOH Wizard

How Hide would you like the columns in your combo box?

To adjust the width of a column , drag its right edge to the width you wantj or double-click the
right edge of the column heading to get the best fit .

Cate-gory ID |
1
2|
3
4
5
6
7

Cance < Back I Next > J Finish

6. The next dialog box tells access what to do with the value that is selected . Choose
remember the value for later use.
7 Click next
,
[Ch #7] Microsoft Acoess forms & Reports 172 Computer Science Part-11

Combo BOH Wizard


Whet label would you like For your combo box ?

Those are all the answers the wizard needs to create your combo
box ,

Oi & play Help on customizing the combo box

Cancel < Eack Me Finish

8 Type the name for the control, which will appear as the label on form
+ ,

9. Click finish .
Q8. How to add check boxes and radio buttons on a form ?
Ans .
Check Boxes and Radio Buttons
o Check boxes are used when one or more than one option may be selected from a
list of given options .
o An option is selected by clicking on the check box .
o When an option is selected , a tick mark appears in the box ,

o An empty and blank box indicates that the option has not been selected ,

o Radio buttons are also called option buttons ,

o These are used when only one option from many is to be selected ,

o These options are mutually exclusive.


o Radio button is selected using mouse by pressing the circular region.
Adding Check Boxes and Radio Buttons to Form
1. Open the form in design view .
2 Select toolbox from view menu .
,

3
4
,

,
Make sure that control wizard button

is pressed .
Click the option group and draw the outline on form .
[Ch#7] Microsoft Acoess forms & Reports Computer Science Part-11
'73
5 , The option group wizard dialog box will appear.
Option Group Wizard

An option group contains; a set of option buttons, check


EKKHIH ,
boxes or toggle buttons YOJ can dwwe only one option
r

P Kttt

JiWi \ \
I
'
<* What latiel do you want For each option?
Label Names

Cancel < Eiack Next > Finish


[Ch#7] Microsoft Acoess forms & Reports Computer Science Part-11
'74
6. Enter the label names and press next

Option Group Wizard

Do you wart one option to be the default choice?


K93HCK
S U H K IjJjHJ

r BtKHa
VeSj the default choice is
_
|M-?I b
-
] IJI JI 1 L.l J
-
IJI 1U I II 9 UI „ll l 1 S -- . - - —
L li ll IL IU1 LlUai LIl ll .i I 11 1 I

r MUH
P hlOj 1 donlt vvant a default .

Cancel < Beck Next > Finish

7 , Select the default choice value and press next button.


[Ch#7] Microsoft Acoess forms & Reports n5 -
Computer Science Part 11

8 , Confirm the value for choices and press next button


Option Group Wizard
What type of controls do you want in the option
group ?
__ .
i B. S b U &U iBU .
aft I J B U B U U K I .
BIU M MM H U B BJ . .
U U BL
-S U J U M U LB

Option buttons
- Sample — HI ia r i n i N i i i n i HBI M i l H I I B! I I I I 111 HBIIII

F Ch eck boxes
f * Male
f~ Fends
j Toggle buttons

What st le would you like to use?


^ C Shadowed
' * Etched
C Flat C Sunken
C Raised

Cancel < Back IN ext > Finish

9 . Choose the type and style of option group and press next .
Option Group Wizard

What caption do you want tar the option group?

That's all the information the wizard needs to create your


option group.

"

f Display Help on customizing the option group .

Cancel < Back Ne )d: > Finish

10. Type the caption for the option group and click finish .
Q9. How to add command button on a form?
Ans .
Command Buttons
o Command button is used To perform a task associated to it .
o It works like an action button and do the thing for which it is being programmed .
[Ch#7] Microsoft Acoess forms & Reports 176 -
Computer Science Part 11
Addins Command Buttons to Form
1 Open the form in design view ,
+

2. Select toolbox from view menu .


3, Make sure that control wizard button is pressed ,
4, Click the command button and draw the outline on form.
5 , The command button wizard will appear .
Command Button Wizard

Sample : What action do you want to happen when the button is


pressed?

ft Different actions ere available for each category .


11 B

Categories: Actions ;

i Record Navigation Find Next


Record Operations Find Record
Form Operations Go To First Record
Report Operations Go To Last Record
Application Go To Next Record
Miscellaneous Go To Previous Record

Cancel < Back I Next > Finish

6 . Here action categories are appeared .


7. Select an action and press next button.
8. Follow the wizard instructions and proceed .
9. Choose appearance ,

10. Enter the name of the button .


[Ch #7] Microsoft Acoess forms & Reports ]
77 Computer Science Part-11
Command Button Wizard

What do you want to name the button?


Sample

A meaningful name VM help you to refer to the button later .


;ommand 22

That's all the information the wizard needs to create your


command button.

-
I Display Help on cust omiz in g the but t on

Cancel < Back Next > Finish

Q.1U How to create the form using wizard:


1 . Double click the create form using wizard m database window .
Form Wizard

Which fields do you want on your form?

You can choose from more than one table or query .


Fables/ Queries
|TABLE ; ^ttKocrse
Available Fields : Selected Fields :
RQW RcPMo
° HD Name
» ci^s?
CreditHrs
RecBooks
<
<C

Cancel < Back Next > Finish

2. Select the table or query and its fields for main form .
3 . Now select the table or query and its fields for sub form .
4. Select form with sub form and press next button .
[Ch#7] Microsoft Acoess forms & Reports I78 Computer Science Part-11

Form Wizard

How do you want to view your


data?
uiibiu aiiiyu 1 1111a 1

I by Student RollFJo , Name


by StdCourse

Class, CreditHrSj RecBoota

(* Form with subform(s) C Linked forms

Cancel < Back Next > Finish

5 , Now select the layout for subfonn and press next button.
Form Wizard
What layout would you like for your subform ?

r IsbJar
* Datasheet
"
(
am 1min
"
IBIIII

p PivotTable
p PivolCfuit

Cancel < Back Next > Finish

6. Select the style for the form and press next button .
[Ch#7] Microsoft Acoess forms & Reports Computer Science Part-11
' 79
[Ch#7] Microsoft Acoess forms & Reports i So -
Computer Science Part 11

7. Give the name to form and subform and press finish button

8. Form will appear as shown in the above diagram,


* Creating Subform using Subform wizard
If main form or both forms already exists, subform wizard can be used .
1. Open main form in design view.
2. Make sure that control wizard button on the toolbox is pressed .
3, Click subform icon on toolbox .
4 , Draw it on the form, a wizard will appear.
5 * Select use existing tables and queries if the sub form has not been created yet.
Subtorm Wizar J
You can use an existing form to create your subform or subnepart or
cre -ate your own using tables and/ or queries . ^
KKIK j
KK

What data tvculd you like to usa far yiour subform or subreport?

mi i n 111 um 111a 11 i 11 III I I I H I l l l l! I I I I B I I I I I IIBBI I I IIBI


*
*+ Use existing Tables and Quarles
Use an existhg
-
form

-- - mu r is in

— —- —
* it ti 5 IITS f iirni

SfaCourse 5ubForm
Student

Cancel
^ Ba:k Ne xt > I Finish
[Ch #7] Microsoft Acoess forms & Reports » Sr -
Computer Science Part 11
6 The next window will display table relationships assumed by MS -Access .
,

SubForm Wizard
Would you like to define which fields lint your main form to this
subform yourselfj « choose from the lis below ?
a
:
x ftSB *
lf f * Choose from a list C Define my own.

Show StdCoursa for each record in Student using ROIIMD


More

Cancel < Eack Next > Finish

7. Enter the name of subform and click finish.


* Creating Subform using drag-and -drop method
This method is used when both the forms already exists .
L Open parent form in design view
[Ch#7] Microsoft Acoess forms & Reports l&2 Computer Science Part-11
ap db i :Dababa^p (Ac - I D I »1 S ^KjdpnH :Form Jnj
*
.
3^ ^- i
I

^ ^ MevM - Sl.
p -I i a
I P ! I I 1 ! 2 P a ! I ! 3
5pei>
J i !
Desion
^
Q
D >- a

4 Form Header
Ob cct i
'
E] Create form in Design ric
(01] T ables 1*1 ] Create Forri by usng v Isi . _
HWM;
Ia I .. i.
FidlNa
j
P I"

[§] (
Jueaies
El 5 tdCourre Sub form 1 "

El Student B I I il h I I I a
OF ame
I rs
li il B I

Forms FBI [Addrsss


fa I

Student ' i n

feepCrhs
fa
-. - B a rf fa
II ai i rf
I rf B
J

i
Doe a
— JDO
-
§ -. — - s
a *

^2 Pages i n
rf
i

faI I rf
n

rf
B

H rf
B

fa
P

fa a i i rf fa .
i
-.
fa i
a
- m P P M

fa a fa i a


H I p i 11 I I I I P! M i l II s I1I III
Macros aa s
r i

a i J i. i a i a j a a a i. a a
i

I II n i ci a ii aa i n im i i n n ni m i ia

Module? J LI
rf fa I I
rf . fa
fa la
rf H
I I rf fa
J L fa
I B li I
rf fa

.

a a

rf 1 rf fa .
i i a fa B
S! r " B
E

Groups
£
. . -
11 Favoritas
B I I I 1 a LI IJ
B i i 'i r i i 'i

a E
I L iJ L I

I N L II I I
B
a IL L L LI I I
r r i B B i i

E a
-
JE
i r

aE
II

11
L II
r

L
i i B
LII IIB
r I U B B

I I I I J i l l I I III I L
B
L E I II
r -
i i i B

a
19
a a

a
B 1

i
J

LI B LI

a B d m aa B III a
i m i r p 1p ar i a i la

9
= 9

-
9 P I i sr B r I 9 B I I p r i
^9 B 9
9 9

I1 9 B B B I 1 rf B H I rf B

*3=
zJ
i

2. Select windows tile vertically *

© bi : Database ( Access ln | xl gg Student 1 : Form | n| x

k& Peagn ^ >


n -6
- !=— E=— r u .

^
b
1 - . - 2 - 3
l Qpen [ j Ne] “
O Ci D
i ! » * i i

4 Form Header
objects Create form in Design vie

[Oil Tables £![] Create form by using wia * Detail


1B P I

.
9 9

: : jFtdiNo
fa

RtfBfl
I rf I I rf rf rf rf fa i a rf fa i i
i I 9 r i i 9 B i i
- -
) Querios m 5 tdCcurse Subform
9 9 r B 9 9 P p rs 9 p p i 9

Ef Name :
J 1.
: | Name
rf rf
a

Studenf .I r f
- .-
fa I B 1« .
I
B I I il 9

Form?
m 5 tudsntl Adaw iii! [Addiess rf rf

^
j a

B fa fa B rf fa fa B fa

Rsports rf fa B I rf fa I B
f

DOB [DOE
i

^
2
Pages

Macias
p i 9 B

r i n B
p 1 1B P
e r
r

9
9
9 9

9 P I
B 9 B I
B

I 9
B

^
9 9
B 9 P

:i .
^ tiCcuree ubifotn
^ .
Module ? fa LB fa fa 1 S rf B U N I rf rf fa 1

*:
I I

j i
i 1 i 2 i a i

Groups rf B

# Form Header
jjfJ Favorite
* p
0 Data! f

9 P 1 I B P 9 B I 1 9 9 1 I B B P I 9 B P

ass ! [Gflss
iri
" '

iW I I B II I 1
H U M r
I I B B I
p I I
.T.
I B B I I U I1
i n r 9 i ri
A

1
4
3
i if

3 Drag from icon beside the name of subform on detail section of main form design
* «
[Ch #7] Microsoft Acoess forms & Reports Computer Science Part 11 -
Q l l. How to implement muitipie page form using tabs, conditional formatting,
password text fields, change control type and composite primary key?

An $ +

Multiple Page Forms Using Tabs

Using tab controls multi-page forms can be created.

1 , Click the tab control from toolbox and draw on the form .

2 , Add new controls to each tab

3 , Right click in the tab area and choose inset page or delete page to add new tables or
delete tabs.

4 . Right click on the tab control and select page order to reorder the tabs .

5 , Double click on a tab and change name property under other tab to rename tabs

H=| Forml : Form nix


r
i r
1 - B » l i
2 1
l 1 B
^ 3 l 4 - , l

0 Detail
a a B J B 1 a 1 ana a . .
i 1 1 a a H 1
1 p p e a r 1 r 1 P I ! 1 P a 1 P I P " 111 r 1 a 1 a a a P 1 p 1 I 1 P B P P 1 I B a P 1 1T 1 1 1 P 1 P r a p a r p p a 1

r
p sl pop2|
1 1 1 r
^
_. & L J .
ft ft A

I
a
Name Khurr -am S P
p

r a
* “5 P

1 r "H

1 H J J

1
Address ; -
L shore a

a
a r

ii
p

.
1
a

a
p

L
P a

m
P 4a

- . .-

-
k k 1 k 1 a

a
a p a s s 1 PI a 1 I a 1-a r a sea 1 r 1 a a ra r s
.a
P a a a p 1 p
. a p
. aa a r P a
a a
a
a
k a k a

P a s e a p a
..
a a 1
p a
-- mI
1 1
- --ft

a a
k
p
a a
a
1
a w a P a a
i

1
a
a ! r a r a
a.a a a
s a a r a
1
a 8 a
P
ft
a- r
k ft 1
p
a a
a
.
p *B
k
p
-
p
- p a p
a
a!
k a

4 j ft S;

Conditional Formatting
Special formatting that depends on the control ' s value is called conditional
formatting. To add conditional formatting to a control element follow these steps.
1 . Select the control on which the formatting is to be applied .
[Ch #7] Microsoft Acoess forms & Reports 184 Computer Science Part 11 -
2 Select conditional formatting from format menu.
,

Conditional Formatting TI X|

Default Formatting
This format wdl he used if no
conditions -are met:

Condition 1
AaBbCcYyZz B / U
^ • A *

[ Field Val ue Is * [ less than 3 Be


Preview of Format to use when
condition is true ; AaHbCcYyZz B / u a - A t ts

rCondition 2
| Field Vd ue Is T
| greater than 3 P°
Preview of Format to use when
condition is true ; AaBbCcYyZz B / U
^ - A - 11.1

J\ dd » I Delete 1 H OK Cancel

3. Select the field value option from condtion l *

4. Also select the formatting against the selected value.


5. Apply the conditions as per requirement and press ok button .
Password Text Fields
A text box can be used as password field For password each character should appear as an
asterisk as the user types the password in the text box . For this follow the following steps.
1. Select the text field in design view.
2. Right click and select properties.
3. Select data tab
4. Click on input mask field and click [ , , , ] button
5. Choose password from the list of input masks
6. Click finish .
Change Control Type
They type of a control can be changed without deleting it . Only limited controls can be
converted to other type of controls.
1 . Select the control in design view.
2. Choose change to from format menu.
3. Select one of the control types that is not grayed out .
Composite Primary Key
1 , Move the mouse over the gray column next to the field names and note that it
becomes an arrow.
[Ch #7] Microsoft Acoess forms & Reports -
Computer Science Part 11
2 Click the mouse, hold it down and drag it over all fields that should be primary keys
,

and release the button.


3, Click the primary key button ,
Q 12, What is a report? Also discuss its different types and their uses ,
Ans *

o Reports arc the output of a database.


o The user can generate different types of reports by manipulating the database ,

o The information on the reports is arranged in different styles,


o The user cannot edit data displayed on the report ,

o The user also cannot input data in a report ,

o The reports are generated for priming purposes.


Uses of reports
o Reports give output data in a required format ,

o It is flexible to represent data in different ways ,

o Report also support for graphics and chart information ,

o Report can display the result of a query.


Columnar Reports
o In this type of report values are displayed in the form of columns ,

o The label indicates the name of the field,


The columnar report spreads the information for a single record over many rows ,

o The layout of a columnar report is as follows.


[Ch #7] Microsoft Acoess forms & Reports 186 -
Computer Science Part 11
Rvpurt WiijrJ

t abular Report A
o The tabular report provide a column for each Held under column header .
o Additional pages are printed in sequence if the columns do not fit on one page .
Report- Wizard
Ho v wuld you like to lay out your report ?
*
Layaut Crtwwwor
( Qpkmnar rf £ortr.*i:
(!" iTflbular "
XXXX KHttt XttXH JOO! X XXXtt Landscape

xraxx
Mliico: KMKSf
MOCKX xxxxa IOCXKK
-
1 KKHK
raxxx
C justified

--
HH IHW WW KXXW 3« M5WK W W X A
XJ XXX
XWXK * -
XSCMXX XXX XX JOO KX I XXXX
XXXHX JQM1 X WKKK
HWHK Slow HMHXX ]OgCK «
-- - --
XS XHX
XS XXX
XXWO : XXXXX JO&KH
WK : XXXXX JOOWK 5 XXXX
>KHXX:
-
--
HS KXX HMflK KHHHX JfflXXH MKHK
XS XXX HM£H XXXXX H 2£»! X S=XXXX!
X>XXX )0TO XXXXX M3CXKX WXXX:

Adjust the field width so call Fields Fit on


a p age .

Cancel < Bac - :. Next > Finish

Q 13. How to create a report using Wizard ?


Ans .
Report Creation Lisin ? Wizard
1 , Double click the create report by using wizard
[Ch #7] Microsoft Acoess forms & Reports 187 -
Computer Science Part 11
Report Wizard

Which fields do you want or your report?

You can choose from more than one table or query ,

TableslQueries
[Table: Student
Available Fields: Selected Fields :

>
Name
Adctess >>
DOB
<
«

Cancel < Hack | tjext > Bnish

2 Select the information source for the report, select table/queries and their fields using
,

arrow buttons.

3 Choose the grouping levels and press next button.


,
[Ch #7] Microsoft Acoess forms & Reports iSS Computer Science Part-11

Report Wizard

What sort order do you want for your records?

Von can sort records by up to Four fields in either ,


ascending or descending order ,
KKXKMXKXXH

XXV SfWXKXX
1 Name
d Ascending
12 3 4

1 xf - x
X T HE XK
-
y XT x
XXX X
d Ascending
u ... vv X XXX XXI X x>:x x
xxx x

f d
XX

V" V i1f ¥
3 Ascending
A KXJ X
^ LK X

i
XXI
9CK :
KKKXHXKMK 4 d Ascending

A sail xx w ^x -c x p F X T J f -
: : •••

K
rxxx xxxx
E xa XK :: x xxx xxx x : x

Cancel
^ Back Nlext > Finish

4 Now select the sort order and press next button


,

5. At this screen select the Layout and page orientation for the report and again click
next button .
Report Wizard
How would you like to lay out your report ?

Layout Orientation

r Columnar ~
G Portrait

um# K « ®t xnm
XMHX HKWH HKHKX KHKKH MKKH
JCKHH KWH
r
Xabujar
111!
!
i
' -
L andcc pe
^

0
XMSfrH KWHXK AhMH MMKH
justified
JKMKK -
KKK iH HHHKH KHKKH MHKH
HHMK KKHHtf tfHKHH MKHH
SKMKK XKWH KKKHK KMKHH MHKX
IKMKK MKH-IH KMKKM KHHHX MHHX
HHSttH KKHHX HH H « «
KWKK HKMH KWXXK KHKHK JHHMH
HKWX KKXKtf KKHW WHXX
KMXK KKMH KKXHX KHXHH MX KM
3KWKX HKMH KWXKK KHKKH MX KM

F Adjust the fi eld width so all fields fit an


a page .

Oancel < Back Next > Finish

6. Select a color and graphic style


7 Type a name for the report and press finish button
, ,

Q 1I 4. How to create a report using Design View ? Also discuss how to print a report ?
[Ch #7] Microsoft Acoess forms & Reports i »9 -
Computer Science Part 11
Ans .
Report Creation In Design View
To crate report in design view select design view from database window'.
1 . Click the new' button highlight the design view and click ok button .
New Report ? l x|

ipesian Vtew

m Report Wizard
AutoReport : Columnar
Autoreport : Tabular
Chart Wizard
Create anew report without Label Wizard
using a wizard,

Choose the table or query where


the objects data comes from d
OK Cane el

2. A blank grid and form element toolbar will appear *

I
1 Student : Repnrt
'

Jnl xl
.| - i 1 2 3 ' 1 1
4 1

Report Header
IJ 1
-
fi fc B
. L I L S L I J E J
B k a J i i
n
u i
i
r
L
i
a
i
J a J k i a .
i a a

Stu dent .
B i k a a a i i k k a a a a B I k a a a

IUUU i

I JL
s"

J L=L
r r a r B i
#

9 9 9
L X
B P B P 9 9 9 9
i j
P P P
n
9 9 9 9
I
til s 9 9

Page Header Am ab
# Detal
RoBMo
D
RoJLXo ® p
m
IT

- ’ P I P * s t - p a r B 9 a 9
P I P
9 9 9 S
i

Nmfi : i ;; i i i p B r B
LIE I
k a s a . .
iMerrie i i
I II IB I
.
r

.
r m9 Ba B
L J I 1 fl
a aa 5E i

a
B a i
p P a k a k k a k a a a > . a

!: Mpiiieas; ; ;;
a a a a a u a aa a a
i fa k a k a m m k a k

- k i i

Mdrm
P B' P 9 P
- 9 9 9 9 9 9 9 9
f ra 9

i a P B P 9 P B 9 H 9 P I P 9 9 9 9 9 9

i r i r -
p 9 i
I I I
B a 9 i a i i
T
i
J:::!!!:B B I 9
H I n i l B i l l i> 1 1
-
i
I Ii i
r i r n i B 'i
I
¥

J # Page Footer
. . .. _ m V

^
-
J k i
r P 9 p B I 9 P P P I P 9 r F P 9 P H 9 B 9 9 9 9 9 9 9
5 " 9 S' p r r a

# Footer
I j

3. Design the report using controls .


4 , Click print preview button at the top left corner of the screen to preview the report .
[Ch #7] Microsoft Acoess forms & Reports 190 Computer Science Part-11
Printing Reports
o Select page set up from file menu to modify page margins their size, orientation ,
and column setup.
o After all these changes print the report using print button on toolbar or from file menu.
Q 15. Differentiate between form and report *

Ans .
Difference between Forms and Reports
Forms and reports are opposite to each other. Both are very important objects of
database systems . The main difference between forms and reports are as follows ,
Form Report
Forms arc made for data input Reports are made for data output
The data in a form can be deleted The data in a report cannot be deleted
The data in form cannot be formatted Reports represent data in formatted form
Forms arc used on computer screens only Reports can be printed to form hard copy
The data in form can be modified The data in report cannot be modified
Q 16. What is the Linking process in MS -Access?
Ans .
Linkin LI
The process of linking in MS -Access creates a link to an object in another
database. The table is not copied to the current database.
Follow the steps to create a link
1. Open the destination database ,
,

2 Select file Get External Data — Link Tables from the menu bar
3, Choose the database that the table is located in and dick the Link button .
4 . A window with tables will appear.
5. Select the tables that should be linked and press ok .
6 A link with the Tables will appear in database window .
,

Q 17. What is a sw itchboard? Also w rite dow n the steps of creating a switch board *

Ans .
Switch Board
o Switch board is a form in access used to navigate database e. g. to open a form or
report,
o II contains buttons.
o Actions of these buttons are set in a way that on click an object is opened.
Creating a Switch Board in Access
L From tools menu select database utilities and then switchboard manger ,

2. If no switch board exists access will ask to create a new one.


3. Click yes to display the switchboard.
4 . Click Edit to edit options.
[Ch #7] Microsoft Acoess forms & Reports T9 ] -
Computer Science Part 11
5. Change the default name of switchboard .
6. Click New to display Edit Switchboard Item dialog box .
7. Select the appropriate option from drop down list in command field .
8. Choose the form and click ok
9. Repeat this process until all items arc added to switchboard form
10. If you want to give users a second option for closing the Switchboard ( besides the
Close box), create a new Switchboard item named Exit and associate it with the
command Exit Application . This option will close the Switchboard and the database *

11 . Running Switchboard .
• Right-click on the database window and choose startup from the menu.
* Click the dropdown arrow for the Display Form / Page option , choose
Switchboard, and click OK.
» The next time you open this database, Access will run the Switchboard form.
Keyboard Shortcuts
Database Actions Editing
Open existing Database CTRL + O Select All CTRL + A
Open a new databse CTRL + N Replace CTRL + H
Save CTRL + S Spell checker F7
Save Record SHIFT+ENTER Toggle between edit mode F 2
and navigation mode
Print CTRL + P Open window for editing SHIFT + F 2
large content fields
Display database Fll Switch from current field ESC
window to current record
Find and Replace CTRL + F Navigating Through a datasheet
Copy CTRL + C Next field TAB
Cut CTRL + X Previous field SHIFT +TAB
Paste CTRL + V f irst field of record HOME
Undo CTRL + Z Last field of record END
Redo CTRL + Y Next record DOWN
ARROW'
Help FI Previous record UP ARROW
Toggle between Form F5 First field of first record CTRL+HOME
and Design View
Last field of last record CTRL + END
Others
Insert fine break in a CTRL+ENTER Copy data from previous CTRL + 4

memo field record


Insert current date CTRL + ; Add a record CTRL ++
Inset current time CTRL + : Delete a record CTRL +-
GETTING STARTED WITH C
Ql . What is a programming language? Also discuss its different types .
Prosrammine Language:
* It is the way of communication between User and Computer .
* It is used to write computer programs .
* A computer program is a series of instructions that directs a computer to perform
tasks.
* A computer programmer sometimes called a developer, creates or modifies computer
programs ,

* A programming language is a set of words abbreviations and symbols that enables a


programmer to communicate instructions to a computer.
* Just as human speak a variety of languages a programmer use a variety of languages
and tools to create programs.
* Several programming languages exist today. Each language has its own rules for
writing the instructions. A language provides the rules to write an instruction is called
its syntax .
* Language is designed for specific purposes c.g. scientific applications, business
solutions or Web Page Development .
Types of Programming Languages ;
There are two types of computer languages.
1 . Low Level Language
2. High Level Language
Low Level Language ( LLL
* The language, which is closed to machine, is called low-level language ,

* A low level programming language is machine dependent A machine dependent


,

language runs on only one type of computer.


* These programs are not portable to other types of computer.
[ Ch # 8] Getting Started v^ ith C 196 Computer Science Part-11

* A Computer can easily understand low-level language.


* The low level language requires a deep understanding of the machine architecture.
* There are two types o flow-level language.
( i ) Machine language
(ii) Assembly language
Machine Language :
* It is the native language of computer. It is known as first generation programming
language.
* The computer does not need any translator to understand it.
* Every machine language instruction consists of 0 's and 1 s,
'

* It is difficult for human beings to understand and learn it .


* It is difficult to locate and remove errors in the program.
* It is directly executed by the computer .
* The machine language programs are machine dependent .
Assembly language:

* Machine language instructions


^^
and Us ) are replaced with English like words
known as mnemonics ( Ne-monics ). fi is second generation programming language.
* It is also called symbolic language.
* Symbolic instruction codes are meaningful abbreviations A programmer writes C for
,

compare L tor load M for multiply.


* An assembler is required to translate the assembly language programs into machine
language.
High Level Language ( HLL ):
* It is closed to human language .
* It is user friendly language. User can learn and understand high level language easily.
* The instructions of HLL are written in English statements .
* The programs of HLL are not directly executed on the computer ,

* The programs written in HLL arc machine independent.


* A language translator is required to translate the HLL into low level language . Each
language has its own translator. These translators arc compilers and interpreters
* HLL programs are easy to modify, debug and more reliable .
* The HLL does not require a deep understanding of the machine architecture.
[ Ch # 8] Getting Started v^ ith C
'97 -
Computer Science Part 11

* HLL describes a well defined way of writing programs .


* These languages arc mostly used for writing application programs
* Every high level language provides a large number of built in functions.
* The programs in high level language are shorter than the programs in low level
language.
Examples :
* C and C++ (used for writing System Software )
* Java {Java is equipped with strong Network features )
* COBOL ( common business oriented language and used for business applications)
* PASCAL
* FORTRAN (Formula Translation and used for mathematical problems)
* BASIC ( Beginners all purposes symbolic instruction code)
TECHNIQUES OF PROGRAMMING IN HIGH LEVEL LANGUAGE:
Structured Programming Language:
* A programming language in which the logic of the program is divided into a number
of smaller sections or modules.
* Each section of the program performs a specific function.
* These programs arc easy to write, debug and modify .
Un-Stinctured Programming Language :
* A programming language in which the logic of the program is written in a single
module.
* It is very difficult to delect any error in the program .
* Its readability is difficult .
Q 2. What is a language processor? Also discuss its different types.
Ans .
Language Processor/Translator:
* It is software that is used to translate the high level language programs (source code )
into machine language (object code ) .
* Each language has its own translator and only one type of translator is used in any
language .
There are three types of language processor.
L Compiler
2 Interpreter
,

3 Assembler
,
[ Ch # 8] Getting Started v^ ith C 198 Computer Science Part-11
Compiler:

* The language translator translates the source code into object code and the whole
program is translated at the same time ,

* If a program contains errors then compiler cannot convert the source code into
machine code until all the errors are removed from the source program ,

* C uses compiler to convert the source code into object code.


Interpreter:
* The language translator translates the source code into object code statement by
statement.
* The working of interpreter is slower than the compiler.
* If there is any error in the program statement it will stop its execution .
* After removing the error it will start reading the next statement .
Assembler :
* The language translator translates the assembly language into machine code.
Q3. What is C language? Also write down about its history. List out some
advantages of C language.
Ans.
C Language:
* In computing , C is a general- purpose procedural computer programming language. It
was originally made lo use with UNIX operating system .
* Although C was designed for developing system software, but it is also widely used
for developing application software.
* It is used on many different software platforms and computer architectures.
* C has greatly influenced many other popular programming languages, most notably
C ++ , which originally wras as an extension to C .
History of C Language:
* Dennis Ritchie developed this language in 1972 in AT & T Bell Laboratories.
* It was derived from B programming Language which was developed by Ken
Thompson in 1969-70. B was the basis for C Language .
* It was native Language of UNIX ,

* System programs under UNIX were designed in C .


* The earlier version of C was known as K & R (Kemighan and Ritchie).
* ANSI ( American national standard institute ) developed a standard version of C called
ANSI C
[ Ch # 8] Getting Started v^ ith C Computer Science Part-11
' 99
Advantages of C Language:

* System Programming : C provides a powerful approach tor system programming. It


was mainly designed to develop system software programs . Programmers can write
complex software programs more easily than any other low level language.
* Platform Independence: C is a machine independent language . It means that
programs written in C language can be executed on any type of computer hardware
with a little modification . For example, a C program written for Intel micro- processor
can be executed on a machine that uses AMD micro-processor,
* Small Language: C is a very small language. It requires limited space ( only some
KB ’s ) on computer 's hard disk ft has only few reserve words. Tn spile of that, it is
,

very powerful for developing different types of programs.

* Fast Code Execution : The code written in C language executes very quickly.
Minimum code execution time is the major cause of using C language for big system
level software projects. Its compiler converts the source code into the object code in a
very short period of time.
* Flexible Codes: The programs written in C language are very flexible. A
programmer can easily change codes . Procedures and functions help the programmers
to utilize them for multiple purposes.

* Structured Programming: C provides structured programming approach. In


structured programming a program is divided into small units called modules. Each
module consists of different instructions to perform a particular task .
* Easy to Learn and Use : C is a very simple language ft is easy to learn and use.
,

Instructions of C have very simple syntax. So, a programmer needs not necessary to
have a detailed knowledge of computer architecture .
Q4 * How to create , edit, save , compile and execute a C language program in
Turbo C++*
Ans .
There are six major steps to prepare a C program for execution . These steps are:
* Writing the source program.
* Saving the source code
* Compiling the source code
* Linking the object file
* Loading the object file
* Executing
[ Ch # 8] Getting Started C 200 -
Computer Science Part 11
h ollowing diagram helps us to understand the inter-connection of these steps:
Tilt user write dAwn Hit pni r^ni
^
and save its us a s« unce File

st

Soiirte ]in\ isoil


File Source Fil*

\ f

The Compiler at tempts to translate L ser corrects syntax errors


'

the source program

yt [ as! of Li nns

\ iv
*
Oh]eel File

st
Tht Linker l inks the object Hit with Other
conr spur ding object files Object File

\ r

Eutaubk
Pile

yt
The Loader places Hie executable
file Inlo the memory

S r
Executable Flit
In Mcnirhry

Create a fil I
*
User can open a menu using mouse or press ALT+F key to open a file menu .
Select New to open a new file .
Edit a file
To edit a file first we need to open that file .
To open a file from file menu select open.
Locate the file in open box .
Press ok to open the located file
Save a fil \
To save a file select save from file menu or press F2 short cut key.
A dialog box will appear .
Write down the name, extension and location of the file to create e ,g. Z:\ First C ,

Compile a fil Iz
• From compile menu select compile option OR press ALT + F9
[ Ch # 8] Getting Started v^ ith C 20 ] -
Computer Science Part 11

* If there is no error in the program , it will be translated to object code.


Execute a file
* To execute a tile select run from run menu OR press Ctrl + F 9
* The out put of the program is shown on the screen .
* To see the out put press ALT + F5.
Q 5, Define Source program , Object Program , Linker and Loader *
Ans *
Source Program ;
* The program written in High Level Language is called source program ,

* The computer does not understand the source code ,

* The source code is converted into machine code and then it is directly executed on the
computer .
Object Program:
* The machine language version that result from compiling the source is called object
code. Compiler stores the object code on storage media for exhibition.
» The computer understands the object code directly.
Linker:
* The linker is a program that combines the object program with additional library files
and produces an executable file with . exe extension.
* In linking process the object file is linked to many other library files *

* The executable file (.exe ) runs directly on the computer after linking process .
* Each source program consists of built-in functions. Built in functions are contained in
library files.
* Linker links all relevant library files with our object code and produces an executable file.
* Linker creates executable file when the source code is error free .
Loader:
* It is a system software f or execution , the loader loads the executable files in The
,

memory.
* Ctrl+ F9 key is used to load and run the programs.
* The executable file (.exe ) runs directly on the computer after Unking process .
* When a program is run , the output screen will disappear in a moment to see the
output press Alt+F5 ,
Q 6, What is the basic structure of a C Program *
Ans *
Basic Structure of a C Program:
Structure of a C program means the logic to write a program. C is structured
programming language. It provides a better way of writing programs. The linker of C
program links many files before execution . There are two parts of a C program structure ,

o Preprocessor Directives .
[ Ch # 8] Getting Started v^ ith C 202 -
Computer Science Part 11
o Main function with C statements

Preprocessor Directives :

* The instructions given to the compiler before the beginning of the actual program are
called preprocessor directives or compiler directives,

* It ahvays begins with # symbol e g #include, #define These are the instructions that
, , ,

tells the compiler to perform an action before compiling the source program .
*include directive:
* The include directive gives a program access to the library.
* The include directive causes the preprocessor to insert definitions from a standard
header file into a program before compilation i. e. The include directive tells the
compiler where to find the meaning of identifiers used in the program ,

* It is used to include header Hies in the program. There are two methods to include
header files.
# include <header file name>
Or
# inelude “ header file name" {User defined HF )
Examples :
# include<stdio h > ,

#include “ conio.h"
tfdefine directive:
* This preprocessor directive is used to define a constant macro.
* Constant Macro: It is a name that is replaced by a particular constant value before
compilation.
* It is use to assign a constant value to an identifier .
* Macro name cannot be changed during program execution .

Syntax :
#define Macro name expression /constant
Example:
#define PI 3.142857
Preprocessor:

* Preprocessor is a part of compiler that modifies or handles a C program before its


compilation.
[ Ch # 8] Getting Started C 203 -
Computer Science Part 11

* It is a program that processed the preprocessor directives * It performs some


processing before compilation .
Header Files:
* These files contain the definition of standard library function $ Each header file
1

contains definition of one type of functions only e.g. math . h contains the definition of
all mathematical functions.
* The extension of header file is .h
* The include directive is used to add header files in the source program.
* All the header tiles arc located in INCLUDE subfolder *

* These are the prototypes for the statements used in the program . To use a library
function in a program its relevant header file must be mention at the top of program.
* There are two methods to include header files .
# include <header tile name>
Or
#include "header file name” ( User defined HF )
Examples:
#include<stdio h> *

# inelude “ eonio.h”
Main Function :
* It indicates the beginning of a C program .
* Every C program has a main function and if it is not included in the program , then the
compiler generates an error message.
* The remaining lines in the program are enclosed in pair of curly braces and are called
body of main function i . e. all the program statements are written in body of main
function.
* The user- delhied functions are created outside the main function.
* The program execution always begins from main function *

Syntax:
void main (void)
r
Statements of the program Body of main function
}
* The definition of main starts with void represents the data type returned by main ,
which means function returns nothing, however, it can also return a value.
[ Ch # 8] Getting Started v^ ith C 204 -
Computer Science Part 11

* The second void enclosed in parentheses represents that the main function does not accept
any argument or any parameter; however, arguments can be passed to the main function.
* Main function may accept one or more value and may output one value. The data type of
main is specified before keyword main.
Delimiters :
* The braces in the main function represents start and end of the program , these braces
are called delimiters.
• \ Represents start of the code.
* } Represents end of the function code.
* The lines between curly braces are statements of the program.
Statement Terminator:
* Each statement of a C program ends with a semicolon (; ) called statement terminator .
* If statement terminator (semicolon) is missing in any statement then the compiler will
generate the following error message ;
Statement missing;
Q7 * What are programming errors? Also discuss its different types.
Ans .
FOGRAMMING ERRORS:
* The errors in a program arc called BUGS .

* The process of finding and removing these errors is called debugging.


There arc three types of errors.
11 Syntax Errors
2. Run Time Errors
3 . Logical Errors .
Syntax Errors :
* A syntax error occurs when the program violates one or more grammar rules of
language ( HLL ).
* A compiler detects these errors at the time of compilation .
* If a program has syntax error then it can not be translated and executed .
* The errors must be removed for the successful compilation.
* These errors are easy to locate and remove because the compiler specifies the location
and type of error.
[ Ch # 8] Getting Started C 205 -
Computer Science Part 11

* In C language examples arc :


Missing statement terminator
Function call missing
A misspelled keyword
Run Time Errors:
* A run time error occurs when the program directs the computer to perform an illegal
operation .
* Run lime errors are detected and displayed by the computer during the execution of a
program.
* When a run time error occurs, the computer stops the execution and displays a
diagnostic message.
Example:
Dividing number by zero .
Logical Errors:
* A logical error occurs when a program follows a faulty algorithm .
* The compiler cannot detect logical errors; therefore no error message is reported from
the compiler .
* Programs cannot be crashed due to logical errors.
* It is difficult to detect logical error. Program with logical errors produces wrong output.
* AH the statements should be verified one by one to detect and remove the logical errors .
Examples:
Use of incorrect mathematical formula.
Data input is incorrect.
Incorrect sequence of operations in a program.
Q 8. Explain the debugging feature of Turbo C++.
Ans *
Debugging Feature of Turbo C++:
Turbo C is an IDE (integrated development environment ) tool. It provides us
the facility to create, edit , delete run . compile, and debugging the programs .
,

Turbo C ++ provides many useful debugging features. Through these features, wc


can easily locate logical and syntax errors. Debugging options are provided as a
[ Ch # 8] Getting Started v^ ith C 20G -
Computer Science Part 11
separate menu named Debug in the Menu bar. Here is a brief description of these
features ,
Compiling Single Line:
TC Compiler provides an excellent option to compile the program line by line *

This enables the programmer to easily locate errors. For compiling a single line at

a time, select Run > Trace Into OR press F7 shortcut key.
Watches:
Watches or watch expressions are used to check the value of a variable during the
program execution. It shows that how and when the value of some particular
variable is changed. It is normally used in combination with compiling single line.
Following procedure is used to apply watch or watch expressions.
o Compile the program line by line through F 7 OK select Run — > Trace Into .
o During Lhe execution , when control comes to the line that contains required
variable, place the cursor on that variable whose value is to be checked .
o Select Debug — > Watches from Menu bar A sub menu will appear.
*

o Select Add Watch from the submenu OR simply use Ctrl + F7 shortcut key. A
dialog box will appear with selected variable shown in Watch Expression
field.
o Click OK or press Enter. TC sub-window shows an error message
automatically that shows the current value of the selected variable .
Breakpoints:
It is the most successful and an effective technique of debugging A breakpoint is
,

a point in the program where the compiler temporarily stops the program
execution , so that the programmer can analyze necessary values TC provides awn
*

easy way to use this mechanism for applying breakpoints . A breakpoint can be
applied through two simple steps :
Place the cursor on the line where you want to apply the breakpoint.
Select Debug — > Toggle Breakpoint OR use Ctrl + F 8 shortcut key. Turbo C ++
automatically stops the program execution when control reached at that particular
line.
Evaluate/ Modify Window:
The evaluate/ modify window is used to change the value of variable during
program execution . It can be useful if the user is single stepping the program and
wants to change the value of a certain variable . The following procedure is used
to use evaluate/modify window:
[ Ch # 8] Getting Started v^ ith C 207 -
Computer Science Part 11
o Select Debug > Evaluatc/ Modify : A new window will appear with three
fields.
o Enter the name of the variable whose value is to be modified in expression
field.
0 Enter the new value for the variable in Now Value field . The value of the third
field Result will also change automatically.
Q .9 Write a short note on Turbo C++ compiler .
Ans .
* Turbo C++ is a compiler used for C and C ++ languages. Since, C ++ is based on C
language. Turbo C ++ provides an environment in which programmer can write,
compile, and debug programs for both languages. It is a software product of
Borland International .
* It provides a complete IDE ( Integrated Development Environment) also called TC
Editor it is used to create, edit and save C programs. TC provides a powerful
,

debugger that helps the programmers in detecting and removing errors. Here is a
basic layout of Turbo C IDE.
* Turbo C editor provides an easy way to write programs. The user can open TC
Editor through one of the following ways:
o Simply type hLTC in Command prompt ( at C ; \)
"

o —
Double click on the TC shortcut at C — > TC — > Bin > TC shortcut.
o Type C:\ TC\ binVTC in Start Run text box and OK button to run Turbo C
Editor.
* The Menu bar contains of Turbo C Editor contains menus to create, edit, compile,
execute, and debug C programs. A menu can be accessed through mouse or
keyboard shortcut , for keyboard shortcut, combination of Alt key with the first
highlighted character of each menu is used . For example, Alt + F is used to open
File menu.
Q . 10 Clarify the difference between ‘fiC” and “ .CPF'1 extension.
Ans ,
Turbo C++ is a compiler used for both C and C ++ languages. The default extension
for each program in TC environment is “ .CPF (stands for C Plus Plus) which is used
1

to include many additional features for C++ programs. Many of these additional
features are not supported by ANSI C. So, “ .CPP extension must be changed into
11

+C because the standard extension of C programs is only AC \ In Short:


'

o .CPP extension is used for C ++ programs .


[ Ch # 8] Getting Started v^ ith C 208 -
Computer Science Part 11
o .C extension is used for C programs.
ELEMENTS OF C
Q. l Explain the importance of elements of C language?
Ans .
A language is a source of communication between two individuals. We can
express our feel digs and thoughts with the help of a language , Similarly, the
language through which we can communicate with a computer is called a
computer language.
The process of learning a computer language is similar to learn a human language.
In English language, some alphabets are combined to make a word . Then, some
words are combined to form a sentence. Finally, some sentences are collected to
narrate a complete story .
In the similar fashion , there is a set of characters ( like English alphabets ) in C
language called Basic Character Set These characters are used to form words and
,

words are combined to generate instructions. Finally, instructions are written in a


specific way to write a C program.

Character sot

Alphabets — > Words > Sentence — > Story
Tokens — > Commands Program
Q.2 What is a character set? Explain the character set of C language?
Ans .
Each programming language has its ow n set of characters which are used to w rite
statements of the program .
The C language allows a limited set of alphabets, digits and special characters ,
These alphabets, digits and special characters are collectively called character set
of C language, A list of C character set is as follows;
Category Description
Lowercase Letters a , b, c, d, e, . . . . .
a 4 * * z.m m a J

Uppercase Letters A, B, C, D, Z.
Digits 0, 1 , 2, 3 , 4, 5 , 6 , 7 , 8 , 9
Special Characters + - * / = etc.
Blank Spaces Blank space, new line , tab
[ Ch # gJ Elements ofC 224 Computer Science Part-11
Q3. What is an Identifier? Also write down its two different types.
Ans .
Identifiers :
* Identifiers arc the names used to represent variables, constants, data types, functions,
and labels in the program.
* Identifiers consist of characters (alphabets, numbers, underscore). Identifiers can
contain any number of characters but only the first 31 characters are significant to C
compiler.
* C is a case sensitive language, therefore, in C language Uppercase and lower case
letters arc different .
* There are two types of identifiers in C .
1 . Standard Identifiers .
2 User-defined Identifiers .
,

Standard identifiers:
* These identifiers have special meaning (defined operations) in C like reserve words.
* These can be redefined for other purposes but it is not recommended .
* If a standard identifier is redefined in a program then wc arc unable to use it for
original purpose .
* Examples:
* printf name of output function defined in stdio. h
* seanf name of input function defined in stdio.h
User-defined identifiers ;
* These identifiers are defined by the programmer ( user).
* A user uses these identifiers for variables, constants, data types, functions, and labels
in the program.
* These words are used to store or access data from various memory locations.
Q4. What are the Keywords / Reserve words in e language?
Ans .
Keywords/ Reserve words:
* These are the words, which have predefined meaning in C language ,

* There are 32 keywords in C language.


* These words cannot be used or redefined for any other purpose in the C program .
* All keywords are written in lowercase.
* List of C keywords :
[ Ch # tf Elements ofC 225 Computer Science Part-11

1. auto 2 , double 3 , void 4. unsigned


5. long 6 , switch 7 , signed 8 * for
9. ml 10. struct 11. extern 12 . typedef
13 . do 14. if 15. goto 16. default
17 . break 18 . else 19 . case 20 . continue

21 . static 22 . while 23. union 24 . return


25 . volatile 26 . sizeof 27 . short 28 . lloat
29 . char 30 . const 31 . enum 32 . register

Q 5. What is a variable? Also write down the rules for naming a variable?
Ans .
Variables :
* A variable is a name of memory locat ion.
* Variables are used to store values that can be changed during program execution .
* The value of variables may be numeric or alphabets .
* Variable name remains same but the value stored in variable may change during the
program execution ,

* When a variable is created in a computer program , some bytes in the computer


memory are allocated to it. These bytes are used to store the value assigned to the
variable.
* The relationship between name, conlenl and address of a variable is shown in the
following figure:
0001
0002
0003
0004
0005
0006 500 Salary

Variable name is salary.


Address is 0006
Variable content is 500
[ Ch # gJ Elements ofC 22 6 -
Computer Science Part 11

* Variable name is the identifier that is assigned to a specific location in the computer
memory.
* Variable content refer to value stored in the memory location associated with ihe
variable, and
* Variable address refers to the address of memory assigned to the variable.
Rules for Naming Variables:
* A variable name can consists of letters, digits, and the underscore character.
* The first character of a variable name must be an alphabet .
* The underscore is also a legal first character but it is not recommended .
* The first character of a variable name cannot be a digit.
* Blank spaces are not allowed in variable names.
* Special characters e.g. &, , $ etc. cannot be used in variables ,
A

* A variable name can only be declared for only one data type in a program.
* C is ease sensitive language, therefore, the names count and COUNT arc two
different variables
* C keywords cannot be used as variable names.
* In C\ variable name can be up to 31 characters long. If a variable consists of more
than 31 characters, then the compiler ignores the characters after 31 st characters .
* Variable names should be in readable form e .g. pay, loan
* Programmers commonly use kwer case letters for variables names and upper case for
constants.
Q 6. What is meant by variable declaration and initialization ? Explain with the
help of examples?
Ans .
Variable Declaration:
* Variable declaration tells the compiler the name and type of value stored in variable .
* C is a strongly typed language, it means before using a variable in a program , it must
be declared.
* When a variable is declared , a certain number of bytes (depending upon the data type )
are allocated to the variable in memory.
* It means declaration not only declares but also defines a variable .
* TC gives an error message if undeclared variable is used in the program.
Variable declaration Syntax :
Data type variable name ;
int a;
[ Ch # tf Elements ofC 227 Computer Science Part-11
char ch ;
Declaration of Multiple Variables:
Datatype list of variables separated by comma;
float c, d;
int x , ys z;
Variable Initiali /ation
* Assigning a value to a variable at the time of declaration is called initialization of the
variable ,
* The general syntax is :
Type variable Value;
Example:
int k ; //declaration of k
k = 20; //initialization of k
Variables can be declared and initialized in a single statement
int a = 15;
float b = 5.23, c = 12, 8;
char ch = 1VT ;
L

Garbage Value:
* When a variable is declared , the compiler reserves the space for it . If wc do not
initialize it then it may contain a meaningless data is called garbage value, and with
the involvement of such variable may cause unexpected results .
* To avoid this situation , all variables must be declared and initialized according to
program requirement.
Assignment operator: Equal to (=) symbol is used to initialize a variable in the
program .
Program:
# inelude<stdio .h>
# include<conio h> ,

void main( )
f

intx;
printsValue of x= % d ” x );
x=200;
printfTVahie of x= %d’\ x);
getch ( );
}
Output:
[ Ch # gJ Elements ofC 228 -
Computer Science Part 11

Value of X=-27896 As we have displayed the value of x wiLhoul lniualizalion so output is undefined
Value of x = 200
'

Q7 * What is a constant? Also discuss its different types .


Ans .
Constants:
* A quantity whose value cannot be changed during program execution .
* Example:
#define pi 3.142857
pi whose value remains same during program execution.
There are two types of constants:
1 . Numeric constants.
2 Character constants.
,

Numeric Constant:
* These constants consist of numbers.
* There are two types of numeric constants .
i . Integers
ii . Float
Integer constants represent values that are counted and without decimal or
fractional pari . e. g. + 56, -678 etc
Floating constants represents values that are measured e .g. 4.786, 0.45 etc.,

Character Constant:
* It is a single alphabet, a single digit or a single symbol enclosed within apostrophes.
* The maximum length of a character constant is 1 .
* Examples are: 5 s + \ ET etc.
L ? 4 4

* String Constant is a group of characters enclosed in double quotes. For example "1
Love Pakistan ” .
Q 8. What is a data type? Also write about character data types.
Ans .
Data TVDCS:
* Data type defines maximum or minimum set of values and set of operations on those
values.
[ Ch # gJ Elements ofC 229 -
Computer Science Part 11
Standard data type is one which is predefined in C language.
In C language the basic standard data types are inf float , char and double and long double.
User-define data type allows us to define our own data types.
Data Types for Characters.
* A keyword char is used for character data type. It is used to represent a letter,
number, or a symbol.
* A character variable occupies 1 byte in memory.
* %c is used as format specifier .
* A character is enclosed in apostrophes e. g. * xy 5 \
, etc.
* Signed and unsigned keywords can be used with char .
* Signed characters represent numbers ranging from -128 to 127 .
* Unsigned characters represent numbers ranging from 0 to 255.
* Alphabets, numbers and punctuation marks arc always represent with positive
numbers.
Characters can also be compared , added and subtracted .
Characters are stored in memory in the form of ASCII codes . Therefore arithmetic
operations are performed on ASCII values.
Example:
Write a program to show arithmetic operation on char type variables.
# include<stdio . h>
void main ( void )
1
char chi , eh 2, sum ;
chi = 42s; //chi contains ASCII code of 2 =50
ch2 = ‘6’ s //chi contains ASCII code of 6 =54
sum = chi +ch2;
printfC\n Sum = %d” ,sum); //output Sum = 104
}
Program :
Write a program that assigns a character to char type variable and displays its
ASCII value.
#include<stdio.h>
#include<canio.h>
void main ( )
!
char x;
x= LA\
printf(“ Character value of x= %c\n” fx);
printff ‘ASCII value of x = %d'\ x);
getchf );
[ Ch # tf Elements ofC 230 Computer Science Part-11

I
Output :
Character Value of x = A
ASCII value of x-65
Q9. Discuss different Numeric data types used in C language*
Ans .
Data Types for Integers:
* Integers are the numbers without decimal fraction. It may be positive, negative or
zero c g 112, -234, 0 etc
* * * *

* An integer variable may be signed or unsigned . If not mentioned then all integers are
considered as signed ,
* Data Types for Integers are:
mL
* short int ,

* long int *

int:
* It takes 2 bytes in memory *

* The keyword int is used for integers *

* There are two further sub- types of int variables *

* Signed int
* Unsigned int
Signed int or short int:
* Range of int , signed int or shoit int variables are -215 to 215 - 1 or -32768 to 32767 .
* int, signed int and short int can handle both positive and negative numbers.
* %d or % i arc used as format specifiers,
Unsigned int or unsigned short int:
* unsigned int can not handle negative numbers *

* it can handle numbers ranging from 0 to 216 - 1 or 0 to 65535


* %u is the format specifier for unsigned int *

Ions int :
* It is used to represent larger integers .
* It occupies 4 bytes in memory ,

-
* It can hold numbers ranging from -231 to 231- l (fe, 2147483648 to 2147483647 )
Unsigned long int:
* It can hold numbers ranging from 0 to 232 - 1 (i e 0 to 4294967295).
« *
[ Ch # tf Elements ofC 231 Computer Science Part-11

Data Type Bytes Range of values


Int 3 signed int, short 2 - 32768 to 32767
mt
unsigned int , unsigned 2 Oto 65535
short int
Long 4 -2147483648 to 2147483647
unsigned long 4 0 to 4294967295
[ Ch # gJ Elements ofC 232 -
Computer Science Part 11

Q 10. Discuss different floating point or real data types used in C language.
A ns.
Data Tvpes for Floating Point Numbers *
These are the numbers with fractional pail. e. g. 2 J 3 ? 0.54 etc.
ANSI C specifies three floating point data types .
float
double
long double
All are different in memory requirement and range .
float:
It may be signed or unsigned numbers.
It is represented in decimal or exponential form .
It occupies 4 bytes in memory.
It can store real values up to 3 4x 10 38' to 3 4x 10+38.
"

, ,

Its accuracy is up to 6 decimal places .


Scientific nr Exponential form of float point number :
* The storage area occupied by the number is divided into two sections.
* Mantissa: It is the value of the number ,

* Exponent: it is the power to which mantissa is raised .


* In C, scientific forms of a number are
+mep
-mop
+ mEp
-m Ep
* m represents the mantissa pail
* E or e is used instead of base JO.
* p represents the exponent part.
* If the number is smaller than 1 then its exponent is negative. ( i e. 0 00524 is equal to
, ,

5.24xE-3 )
Example: 2.45 x 105 is represented as 2.45 e5 or 2.45 E5 .
The following table gives a real number and its equivalent scientific and exponential
forms.
Floating Point Number Scientific form Exponential form
0.00006 6.0x 10 i 6.0e-5
60000000.0 6.0x 107 6.0E 7
-1.62x 10-
6
-0.00000162 -1.620 E-6
660.0 6.6x 102 6.6E2
[ Ch # tf Elements ofC -
Computer Science Part 11

double:
* It is used to store larger floating point numbers.
* It takes 8 bytes in memory .
-308 i 308
* It can handle real numbers from 1.7 x 10 to 1.7 x 10
* Its accuracy is up to 15 decimal places.
Ions double
* A long double variable takes 10 bytes in memory.
* It can handle real numbers from 3.4 x 10^932 to 3 4x 10 14932
,

* Its accuracy is up to 19 decimal places.


Data Type Bytes Decimal Range of values
Places
6 10 to 1 O 38
3S '

Float 4 '

Double 8 15 10-308 to 10+308


long double 10 19 10-4932 to 10+4932

Data ty pe Bites
u.
Format Specifier Range
Signed char 1 %c -128 to 127
Unsigned char 1 %c 0 to 255
Short signed int 2 % d, % i - 32768 to 32767
Short unsigned int 2 %u 0 to 65535
Long signed int 4 % Id -2147483648 to 2147483647
Long unsigned int 4 % lu 0 to 4294967295
Float 4 %f -3.4 e 38 to 3.4 e 38
308 308
Double 8 % lf - 1.7 c to 1.7 e
4932
Long double 10 % Lf - 1.7 c to 1.7 e4932
Qll. Define the Cancellation Error, Arithmetic Underflow, Arithmetic Overflow ,
Integer Underflowr and Integer Overflow *
Ans .
Cancellation Error
* While working w ith floating point numbers, some unexpected results cause problems.
* For example manipulation of very large and very small float numbers produced
unexpected results e.g. the result of addition of 1970.0 and 0.0000001243 may
produce 1970.000000 on some computers .
[ Ch # gJ Elements ofC 234 Computer Science Part-11

* This type of errors is called cancellation errors he. in cancellation errors a very small
value disappears when it is added to or subtracted from a very large value.
Arithmetic Underflow:
* When two very small numbers arc manipulated , the result may be too small to be
represented accurately, so it will be represented as zero .
* This is called arithmetic underflow i e when the value assigned is less than the
, +

minimum allowable limit an underflow occurs.


Arithmetic Overflows
* When two very large numbers are manipulated, the result may be too large to be
represented .
* This is called arithmetic overflow i .e. When the value assigned is greater than the
maximum allowable limit, an overflow occurs.
Integer Underflow : 7

* When the value assigned to a variable is less than the minimum allowable limit of an
integer i . e . -32768, an underflow occurs .
'

* In case of an integer underflow different compiler takes different actions.


* fn most cases compiler runs the programs and it produces incorrect results.
Integer Overflow :

* When the value assigned to a variable is greater than the maximum allowable limit of
an integer i .e. +32767, an integer overflow occurs.
* In case of an integer overflew different compiler takes different actions.
* In most cases compiler runs the programs and it produces incorrect results.
* In case of overflow and underflow in integer variables, the assigned value “ wraps
around “ the maximum/minimum limits. The wrap around means that the value that
comes after the maximum is the minimum value.
32767

- 32768
* For example, the maximum value that an int type variable can have is 32767. When 1
is added to a variable to already contains a value of 32767, the result is -32768. That
is, the value wraps around and starts from the minimum value, i e. -32768.
+
[ Ch # gJ Elements ofC 235 -
Computer Science Part 11

* Similarly, the value below the minimum limit is the maximum value The minimum
*

value that an int type variable can have is — 32768 When t is subtracted from the
*

variable that already contains a value of -32768, the result is 32767 . That is the value
wraps around and starts from the maximum value i .e . 32767 .
,

Q 12. What are comments? Also discuss its different types.


Ans.
Comments:
* Comments play no role in the execution of the program These are 11011-executable
*

statements .
* The compiler docs not translate these statements.
* It increases the readability of the program
,

* It is used to add informative notes about the statements in a program that helps in
debugging and modifying programs .
* It also explains the logic of the program.
* There are two types of comments in C\
1 Single line comments
*

2 Multi line Comments


,

Single line comments :

* Single line comments arc inserted by typing two forward slashes before the beginning
of a line *

Example: // this program Calculates temperature


Multi line Comments:
* Multi-line comments are used to provide such informative notes w'hich extend to
multi lines .
* Multi line comments are inserted by typing slash asterisk ( / *) in the beginning and
asterisk slash ( */) at the end of paragraph. Then the compiler ignores all lines within
this block.
* By omitting ending letters */ will cause the whole program code beneath the opening
letters / * for comments to be commented.
Example: /* this program calculates factorial of a number
Number is positive integer. And result is long integer. * /
Q 13. What is an expression ? Also describe operator and operand ?
Ans .
Expressions:
[ Ch # gJ Elements ofC 235 Computer Science Part-11

* An expression is a combination of Operands (constants and variables ) and operators.


We can write an expression as follows ;
Operand 1 ( operator ) Operand 2
Or
Operator (operand)
Operator:

* It is a symbol or a sign used to perforin a certain tasks on data.


* Unary operators required single data item ( operand) and binary operators required two
data items (Operands).
* Following types of operators arc available in C .
o Arithmetic Operators
o Relational Operators,
o Logical Operators ,

o Increment and decrement Operators ,


o Assignment Operator
Operand :

* The value on which we want to perform operation is called the operand.


There are three types of Expressions
.
1 Arithmetic Expressions
2. Relational Expressions
3. Logical Expressions
Q 14, Describe arithmetic expression ? Also discuss its different modes.
Ans .
Arithmetic Expressions and Arithmetic Operators:
* Arithmetic operators are used with constants and variables forms arithmetic
expressions.
* These operators ( + , * /, % ) are used to perform arithmetic operations .
Operator Function
+ Addition of two numbers (Binary a+b)
Subtraction of two Numbers (Binary a-b)
Multiplication of two Numbers ( Binary a*b)
/ Divide two numbers ( Binary a / b )
[ Ch # tf Elements ofC 237 -
Computer Science Part 11

% To get remainder after dividing numbers ( Binary a%b )


+ unary + (+ a )
unary - (-a )
* All arithmetic operators are used for all types of numeric data except remainder
operator.
* Remainder operator or Modulus Operator {%) is used only with integers .
* All the arithmetic expressions are evaluated from left to right ,

* The computer performs only one operation at a time ,

* Unary operators have higher precedence over the binary operator ,

* The priority of multiplication and division is higher than addition and subtraction ,
however, the priority of * and / is equal and the priority of + and - is equal .
There arc three modes of arithmetic expressions ,
i. Integer Arithmetic
iit Real Arithmetic
iii , Mixed arithmetic
Integer arithmetic Mode :
* When an arithmetic operation is performed on integer values it always yields an
integer result
* It does not produce real results.
Example:
A+R A-R A *R A/B
A=22, B=4 26 18 88 5
Real arithmetic Mode:

* When an arithmetic operation is performed on floating point numbers, it always


yields a floating point result .
Example:
A +R A -B A *B A/B
A=22.0, B=4.0 26 000000
, 18.000000 88.000000 5 500000
,

Mixed arithmetic Made :


[ Ch # tf Elements ofC 238 Computer Science Part-11

• When an arithmetic operation is performed on integers and floating point numbers


( anyone is real number ), it always yields a floating point result.

Example:
A-B A-B A* B A/ B
A=22, B=4.0 26.000000 18.000000 88.000000 5.500000
Program :
Write a program in C language to show different arithmetic operations on data ,

#incl ude<stdio.h>
# i n e I ude<conto.h>
void main( )
{
int x,y,add,siib,muhdiv,mod;
x=20 ;
y=4 ;
add=x +y;
sub=x-y;
mul-x * y;
div=x/yj
mod^x % y;
printf{ Addition is %d ir \ add ) ;
44

printflf **Subtraction is %d\nv,sub);

^
printfl Multip1ication is %d \ n > u1 );
printf( Division is %d\n” ,div);
46

printf("Modulus is %d .rT , iriod );


gctch ( );
}
Output :
[ Ch # tf Elements ofC 239 -
Computer Science Part 11
Addition is 24
Subtraction is J 6
Multiplication is SO
Division is 5
Modulus is 0.
Q 15. What are relational expressions?
Am .
Relational Expression and Relational Operators
* Relational operators with constants and variables form relational expressions.
* There arc six binary relational operators ( <f > , <= , >=, =, !=) used to compare two
values.
* These always evaluates to true or false.
* A true state is represented by a non zero value ( 1 ) and a false state is represented by a
zero value (0),
* All the relational expressions are evaluated from left to right.
* Relational operators are at the same level of hierarchy be no relational operator has
*

the preference over the other .

Operator Meaning Expression

< Less than a<b


<= Less than or equal to a <= b
> Greater then a>b
greater than or equal to a>=b
equal to a=b
)
= not equal to a != b
Example:
A<B A<=B A>B A>= B A== B A!= B
A= 1 (X B=20 l l 0 0 0 1
A=10, B= 10 0 1 0 1 1 0
A=20, B= 10 0 0 1 1 0 1
[ Ch # tf Elements ofC 240 -
Computer Science Part 11
Q 16. What are Logical Expressions ? Also discuss its different operators.
Ans.
Logical Expressions and Logical Operators:
* These operators are used to combine more than one relational expression i .e .
relational expressions with logical operators form logical expressions.
* And ( && ), or ( ||) and not ( ! ) are three logical operators.
* Logical operators also produce true or false results ,
* Not ( ! ) is a unary operator but && and || are binary operators.
* If more than one logical operator is used in an expression then the expression will be
evaluated from left to right in the following sequence.
Not (! )
And (&&)
Or (||)
And Operator ( && )
• It is used to combine two or more relational expressions.
• It produces true if all the relational expressions (conditions ) are true and it produces
false result if any one of the conditions or all the conditions are false.

A(Exp-l ) B( Exp-2 ) A && B


1 1 1
1 0 0
0 1 0
0 0 0
Example: X= 10, Y =20, Z-30
A=X>Y B =X> Z A&& B
0 0 0
A =X <Y B = X >Z A&& B
I 0 0
A=X> Y —
B X<Z A&& B
0 I 0
A=X< Y B = X <Z A && B
1 1 I
[Cltffg] Elements ofC 241 -
Computer Science Part 11

• It is also used to combine two or more relational expressions.


• It produces false if all the conditions ( relational expressions) are false and it produces
true result if any one of the conditions or all the conditions are true.
A ( Exp-l ) B( Exp-2 )
1 1 1
1 0 1
0 1 1
0 0 0
Example: X=10, Y=20, Z=30
A=X>Y B=X>Z AIIB
0 0 0
A = X<Y B=X>Z A|| B
1 0 1
A = X>Y B=X<Z A B
0 1 1
A =X<Y B=X<Z A||B
1 1 1
Not or Negation Operator ( ! ) :
* It negates the value of an expression .
* If an expression evaluates to true ( non - zero value) then it converts true into false
(zero value) and if an expression yields false then its negation yields true .
A ! (A )
1 0
0 l
Example: X = 10, Y=20
A =X>Y !(A)
0 l
A =X<Y 1(A)
1 0
Q 17. What is Increment and decrement operator? Explain with the help of
examples.
Ans.
Increment Operator (++):
* ++ is used as increment operator.
[ Ch # gJ Elements ofC 242 Computer Science Part-11

* It is used to increase the value of the variable by one.


* It can be used before or after the variable name e .g. x++ or ++x
,

* It can not be used with constants and expressions. Only the variables can be
incremented.
* It is unary operator.
* There are two types of increment operator
1 . Postfix increment operator
2 Prefix increment operator .
,

Postfix increment operator ;


* When ++ is follows its operand ( variable ), it is called postfix increment operator
* In postfix increment, increases the value of variable after the execution of the
statement he. it first uses Ihe current value of the variable in the statement and after
the completion of the statement it increases the value by one.
Example:
A = 100 ;
B - A ++; // A= 101 , B= 100
B = A ++; // is equivalent to B = A; and A = A + 1 ;
Prefix increment operator:
* When is precedes its operand ( variable ), it is called prefix increment operator .
* In prefix increment , ++ increases the value of the variable before the execution of the
statement be. it first increases the current value of the variable by one and then new
value is used in the statement .
Example:
A = 100 ;
B - ++A; // A= I 01 , B=101
B = ++A; // is equivalent to A = A + 1: AND B = A ;
Decrement Operator (-- ):
* —is used as decrement operator.
* It is used to decrease the value of the variable by one.
+


* It can be used before or after the variable name c g. x or -x ,
* It can not be used with constants and expressions. Only the variables can be
decremented.
* It is unary operator.
* There are two types of decrement operator
L Postfix decrement operator
2 Prefix decrement operator.
,
[ Ch # tf Elements ofC 243 -
Computer Science Part 11
Postfix decrement operator :

* When is follows its operand ( variable ), it is called postfix decrement operator.
* Tn postfix decrement, decreases the value of variable after the execution of the
statement he. it First uses the current value of the variable in the statement and after
the completion of the statement U decreases the value by one .
Example:
A = 100;
B=A :
B = A--:
— //
//
A =99, B= 100
is equivalent to B = A; and A = A - 1 ;
Prefix decrement operator:
* When —
is precedes its operand (variable), it is called prefix decrement operator ,

* In prefix decrement , —
decreases the value of the variable before the execution of the
statement i .e. it first decreases the current value of the variable by one and then new
value is used in the statement.
Example:
A = 100 ;
B = -A; // A=99, B=99
B = -A; // is equivalent to A = A - 1; AND B = A ;
Program :
Write a program in C language to show the difference of prefix increment and
postfix increment .
# includc<stdio .h>
# include<conio.h>
void main( )
t
mt x , y;
y=50;
x=++y;
clrscr( );
printff 'Prefix IncrmentVF*);
printf("Value of x = %d\ n” fx);
v
printf{"Value of y = %d \ n ' , y );
y=50;
x=y++ ;
print f("Post fix Incremental") ;
printf{“ Value of x = %d \ n \ x );
[ Ch # tf Elements ofC 244 Computer Science Part-11
pnntf (“ Value of y = %d\n’\y);
gctch ( );
}
Output :
Prefix Increment
Value of x = 51
Value of y = 51
Postfix Increment
Value of x = 50
Value of y = 51
Q 18. What is assignment statement and assignment operator?
Ans*
Assignment Statement and Assignment Operator (=):
* Assignment statement is used to assign a value or a computational result to a variable.
* The symbol equal (=) represents assignment operator ,
* There are two types of assignment statement .
T Simple Assignment Statement
2 Compound Assignment Statement
,

Simple Assignment statement:

* The value is written on the right side of the operator and the variable is left side of the
operator in the assignment statement.
* Writing variable to right and value to left causes a syntax error ,

* General form of assignment statement


* Variable - expression
Expression can be a variable, constant , arithmetic, relational or logical expression e.g.
A= 10;
D= B * B -4 * A * C ;
Compound Assignment statement:
* It is used to assign one value to more than one variables.
* General form of compound Statement
_
* Var - l =var -2=var - 3 = = - n value
var
Example:
ml x, y, z;
x — y — z — 10 ; //The value 10 is stored in variables x , y and z
Compound Assignment Expression And Compound Assignment Operators :
[ Ch # tf Elements ofC 245 -
Computer Science Part 11

* It is used to add, subtract multiply or divide the value to or from a variable.


,

* There arc four compound assignment operators ( +=, -=, *=, / =) that can increment or
decrement the value of the variables by other than one ,
* tGeneral form of writing compound assignment expressions is
Variable operator - value
Example:
int J = 10, 1=20;
li value ofj is increase by 5 and J =15 or J =J +5
I *= 5 ; // value of i is multiplied by 5 and stored in I (1= 100 ) //or equivalent to
1 = 1*5
Program :
Write a program in C Language to show the working of compound assignment statement,
#inc1ude<stdio.h>
# include<conio h> ,

void main( )
{
int a. s m df r;
} ?

a = s = m = d = r = 200;
a +=5;
-
s =5;
m*=5;
d/=5;
r%= 5;
drscr( );
printf(“ %a\rf \a);
J
printf(“ %d\n” );
printf("%d \ n’ \ m );
printf(tVod ,,
\n Jd);
printf(“ %d \n” ,r);

Output :
205
95
1000
40
0
Q 19 , What is operator precedence? List the operators used in C language
according to their precedence level *

An $ t
[ Ch # gJ Elements ofC 246 -
Computer Science Part 11
Operator Precedence :
The order in which different types of operators are evaluated is called as operator
precedence . It is also known as hierarchy of operators .
All operators in C language have their own precedence level .
In any expression , the operators with higher precedence level are evaluated before
the operators with lower precedence level .
When an expression is a combination of arithmetic, relational and logical
expression then the expression is evaluated in the following sequence.
o Arithmetic
o Relational
o Logical
o The expression in parenthesis is evaluated first. In case of nested parenthesis, the
part of expression in the inner most parenthesis is evaluated first .
o Next , multiplication and division (* /) operators arc evaluated.
o Then , plus and minus ( + -) operators are evaluated .
o Relational operators, Logical AND, OR and finally assignment operator are
respectively evaluated.
Operator Precedence
! Logical not Highest
( ) parenthesis
/, %

>, >=, <, <=


— — t—
f *

&& (and )
11 («r) Lowest

The table shows the level of precedence for different operators. Logical not (!)
and parenthesis has the highest precedence.
For example, consider the expression ; 25 * (6 + (50 - 48) / 2 ) + 15
* First of all, the expression in the inner most parenthesis ( 50 48) is
evaluated .
* Then the result of this expression is divided by 2 . It gives value 1.
,

* In third step, 1 is added to 6. The entire expression in parenthesis gives value 7.


* Now , 7 is multiplied to 25 Finally, 175 is added with 15 and 190 becomes
,

the answer.
Q . 2 U What is an operator’ s associatively? Explain with example .
Alls.
[ Ch # gJ Elements ofC 247 -
Computer Science Part 11
The order in which the operators of same precedence are evaluated is called
operator associative! It tells the compiler that if some operators of same
^
precedence level are there then how the expression is evaluated (from left - to —
right or right - to - left ).
Operator Associativclv
+ + (postfix) (postfix) Left - to - right
+ (unary ) ( unary ) -1— ( prefix) ( prefix ) Left - to - right
/ % Left - to - right
+ Left - to - right
+= * Right - to - left
* For example, consider the expression : 5 + 6 - 9 - 2 + 7. In this expression , plus
and minus operators have the same precedence level Here, operators
associatively rule ( described in row no. 4 of the above table ) is used to evaluate
this expression. It is evaluated as follows :
o 5 +_6 - 9 - 2 + 7
o 11 - 9- 2 + 7
o 2-2+7
o 0+7
o 7
Q . 21 What is meant by type casting? Explain in detail .
An $ Type Casting ;
+

* The conversion of the data type of a value into another data type during the
program execution is called type casting. Type casting can be performed in two
standard ways:
* Implicit Casting
* Explicit Casting
* Implicit Casting:
O Implicit casting is automatically performed by the C compiler. The operands in
arithmetic operation must be of similar data types I11 case, the data types of operands
,

are different , the values with lower data type are converted into higher data type.
0 It is important to describe here that data types in C language are categorized
from lower to higher order. This categorization is based on the number of
bytes that a data type takes in memory . Different data types are arranged into
the following sequence .
o If nested parenthesis are used , then the part of expression in the inner most
parenthesis is evaluated first.
[ Ch # tf Elements ofC 248 -
Computer Science Part 11
1 figlier Data Types

^ ^Long Don Me

Double
>
Final

Lung
>n
( Jut

c Char
J
Lower Data Types

o For example, suppose a is an integer type variable and b is a long type


variable and we want to evaluate the expression a + b. In this expression, data
type of variable a is low'er than b. Therefore, the value of variable a will be
converted into long. The data type of a is not changed he., it remains int . Only
the value is converted into another data types in order to evaluate the
expression .
Explicit Casting :
o Explicit casting is performed by the programmer. In explicit casting, the type
cast operator is used i .e. , convert one numeric data type into another numeric
data type. The syntax for this conversion is as shown below :
( type) expression;
o Type: It specifies the data type to which the value of the expression is to be
converted.
o Expression : It includes a constant, variable , or expression whose data type is
to be converted.

o For example, consider the expression a % b ; . Suppose, both variables arc of


float data type. The expression will generate a runtime error because the
modules operator cannot work with float variables. It can only work with
integers. So, the value of both variables will be converted into int data type.
( int ) a % ( int ) b ;
[ Ch # tf Elements ofC 249 -
Computer Science Part 11
o The above statement will convert the value of variable a and value of
variable b into int data type. Then , it can be successfully evaluated . Here, it
is important to explain that the values of both variables are temporarily
converted while the actual data type remains float.
ICJiafiM 10\

INPUT/OUTPUT
Q1. What is an output statement? Explain the printf() function of C language.
Ans ,
Output Statements:
* Output statements ( functions ) arc used to get data from the program ,
* Output produced by monitor is called standard output .
Example:
rintf ( ) Function :
* It is used to display messages.
* Jt can be pronounced as print-eff function .
* It can be accessed by including standard input / output header file stdio . h in the
program +

* It takes formatted string and list of variables as an argument.


* The values of variables are displayed according the specified format in the string ,
* Wc can use printf ( ) function in two ways,
L To print a constant message
Syntax : printf ( “ Message ” );
Example:
printf( ''Hello World “ ); // output Is Hello World
.
2 To print values of Variables:
Syntax : printf( “ Format specifiers Control string^ , var- 1 , var-2
f );
Control string consists of text, format specifiers and escape sequence and is
enclosed in double quotation marks.
Example:
A =2 ;
p r i n t f A ); // output is 2
%d is format specifier for integer variable A
printf(“ %fy A ); // output is 2.000000
%f is format specifier for float value ,

% is format symbol .
[ Ch # io] Inpwt/Outpid 270 -
Computer Science Part 11
Q 2. What are format specifier? Also write dawn the associated data types.
A ns.
Format Specifiers:
* A format specifier represents data type field width and format of a value of a variable
displayed on the screen ,
* A format specifier always begins with the symbol % .
* Format specifiers are used for both input and output statements.
* The general syntax of format specifies is .
_
% Flag Field Width Precision Conversion Charactcr
• % It specifies the beginning of the format specifier.
* Flag
o - or + symbol can be used as flag. Its use is optional ,

o + is used to display a + sign with positive numbers .


o - is used to display output left justified . BY default the output is right justified .
* Field width A number is used as field width . It specifies the minimum number
of columns used for a value.
* Precision It is a number used for real values. A precision n specifies that n
decimal places will be shown in output ,
* Conversion Character It is used to convert output value in a specified format ,
Different conversion characters are used for different type of data. Its use in format
specifier is compulsory.
* In format specifier the use of % and conversion character is compulsory. The use of
flag, field width and precision is optional ,

* For different types different format specifiers are used .


Different format specifiers are:
Format Specifier Data Type
a ) %d inf short
b) %f float
c) %lf double
d ) %e float, double ( exponential notation )
e) %g floating point (%f or %e whichever is shorter )
f ) %c char
g) % s character string
h) %u unsigned int; unsigned short
i ) %x unsigned hexadecimal integer
j) %i integers
[ Ch # io] Inpwt/Outpid 271 Computer Science Part-11

k ) %ld 1 on IT integers
Program :
Write a program to declare and initialize data into an integer type variable x and
print the value of x in:
o Decimal format .
o The ASCII character of the integer value,
o The Hexadecimal value of the integer value ,

o The Octal value of the integer value.


#include<stdio.h>
void main ( )
{
int x = 97;
printffThe decimal value of x = %d\n’\x);
printf( “ The ASCII value of x = %c\rf ,x );
printf( iThe Hexadecimal value of x = %X \n” x ) ;
4
?

printflfThe octal value of x = %o\n” ,x );


}
Output:
The decimal value of x 97
The ASCII value of x a
The Hexadecimal value of x = 61
The octal value of x 141
Q3. What are field width specifiers? Explain with the help of examples,
An $ ,
Field Width Soecilier :
* It is defined as the number of columns used to display a value on the screen .
* Its use is optional
* If the value requires more columns, then the field is expanded .
[ Ch # io] Iriput/Outpuf 272 -
Computer Science Part 11

* If the value is smaller than the specified number of columns then the extra spaces arc
padded before or after the value ,

* The space will be printed as an extra character in output.


Example:
Integers:

Program Statement with Held width Output ( 0 means spaces)


specifier
Printf ( "%d",786); 786
Printf ( “ %4d ” ,786 ); 786
printf ( “ %5d” ,786); 786
printf ( “ %4d ” ,-786); -786
,
printf ( %5 d" -786 );
l
-786
printf ( “ %ld” ,786); 786 ( expanded if width is small )
printf ( “ %2d ” ,-7 86 ); -786 (expanded if width is small )
Float:
• In floating point we must specify the total field width and the desired decimal places
(precision ).
• The total field should be large enough lo accommodate all digits before and after the
decimal point.
• Total Held should include a space for a decimal point as well as for the minus sign ,
• Zero is always printed before a number in which integral pari is not mentioned
( means zero e. g. .12 ) or less than 1.
• The general form for the floating point will be %m.nf
• m represents the total field width and n represents the desired number of decimal
places .
Program Statement with field width specifier Output ( means spaces)
printf ( “ %6.2f \ -25.41 ); -25.41
printf ( “ %5.2f ,3.14159); 3.14
printf ( “ %6.2f \ . 123); 0.12
printf ( “ %5. If ’,3.14159); 3.1
printf ( “ %8.5f ’,3.14159); 3.14159
>
printf ( “ %4.2f 0,007 ); -0, 01

>
printf ( “ %8.5f 0.007); -0.00700
printf ( <‘%, 4f ’,-3. I 4159); -3.1416
printf ( “ %5.3f ’.3.14159 ); 3, 141
[ Ch # io] Inpwt/Outpid *73 -
Computer Science Part 11
printf f “ %4.2f ’,.6789); 0.69
-
printf ( “ %8.3f \ .O07); D-0,007
-
printf ( “ %.3f ’, - 007 ) ; -0.007
Program :
Write a program to declare and initialize data to a variable x of float type and
print its value on the screen using the control characters %f, %e, %E, %g and %G .
# inc1 ude<s tdio .h>
void main ( )
I

float x = 6714.987697f;
printf(*'Value of x using control character 1' = %fn’\ x );
prinllT Value of x using control character e = %e\n” ,x );
'

printf(“ Va) ue of x using control character E = %E\n” ,x );


4
printf( 'Value of x using control character g = %g\n",x );
printf{“ Value of x using control character G - %G\n” ,x);
)
Output :
Value of x using control character f = 6714.987793
Value of x using control character e = 6.714988e+03
Value of x using control character E = 6.714988E+03
Value of x using control character g = 6714.99
Value of x using control character G = 6714 99 ,

Q4 - What are escape sequences?


Ans .
Escape Sequences:

* These are characters which are used to control output on the output devices .
* These characters arc not printed on the output devices ,
* An escape sequence is a combination of a backslash and a single character .
* Backslash \ is called control character ,

* And next single character after backslash is called code character ,


[ Ch # io] Inpwt/Outpid 274 -
Computer Science Part 11

* These arc used in control string.


* These characters cause a different meaning from the normal interpretation .
* Different Escape Sequences are:
Lsca pe Sequence Pu rpose
a ) \n New line
b ) \t Tab
c ) \b Back space
d ) \r Carriage return ( Enter key)
e ) \f Form feed
f) V Single quote
g) V Double quote
h ) \\ Backslash
i) xdd ASCII code in hexadecimal notation (each cl represent a digit )
j) ddd ASCII code in octal notation ( each d represent a digit )
k ) \? Question mark
Examples:
Program Statement with escape sequence Output
printf ( "Namedroll NoVtMarks” ); Name Roll No Marks
printf{"Amir \ n ali” ); Amir
ali
printf{“ Amir V'AliV ” ’); Amir “ Ali ”
printf(“ Amir VAliV ” ); Amir ‘Ali ’
printf(“ Annr WAliW” ); Amir \Ali\
Q5. What is an input statement? Also discuss its different types.
A ns .
Input Statements:

* Input statements ( functions ) arc used to provide data to the program .


* The input given to the computer through keyboard is called standard input .
* There are two types of input
T Design time input
[ Ch # io] Inpwt/Outpid 275 -
Computer Science Part 11
2 Run time input
,

Design Time Input:

* It is also called programmer’ s input or simple input .


* It is given by the programmer at the time of writing programs ( coding) .
* It remains constant during the execution of the program.
Example:
int x=5 y=9;
? //programmer assigns values to the variables in the program
float a= 10.2;
Run Time Input:
* It is given at the time of execution of the program ( after compilation ) .
* It is called user input
* Examples are:
* scanf( ) Function // to get value of variable
* getchQ Function // to get a single character from keyboard
* getche() Function // to get a single character from keyboard
scanfQ Function :
* It is used to get values of the variables ( numeric and string ).
* It can be pronounced as scan -eflf function.
* It can be accessed by including standard input / output header tile stdio . h in the
program (means stdio .h is a prototype for scanf( ) function) .
* It takes formatted control string and list of variables as an argument to hold the value
of variables.
* scanf() requires the address of the variable to store the value into it .
* Ampersand sign {& ) is used before the variable name as an address of operator
* If & sign is omitted the scanf function will not locate the variable in memory.
Svntax :
scanff 'List of Format specifiers &var- U &var-2 & var-3
? ? );
Examples :
Input of a single variable
mt a ;
[ Ch # io] Inpwt/Outpid 276 -
Computer Science Part 11
scanf( “ %tT \ & a); 11 To get the value of a at run time
%d is format specifier for integer variable a
% is format symbol .
Input of more than one variabl *I
int a ,b;
float c;
scanf( “ %d%tr &a &b) ;/ / To get the value of a and b at run time
? ?

scanf (“ %f \ &c); 11 To get the value of c at run time


scanf(“ %d%f%cT, &a,&c,&b); 1/ To get the value of a c and b
?

Program :
Write a program to input the marks obtained by a student in three subjects ,
Calculate the total marks and their average and print the results on the screen .
# include<stdio h > ,

void main ( )
i

float total, s1,s 2 s3,avg;


?

printff ‘Enter marks of first subject?' ); 1

scanf(“ %r, &sl );


printf("Enter marks of second subject?” );
scanf( “ %f &s2);

^
printf 'Enter marks of third subject?’1);
scanf( “ %f ’ &s3 );
?

total sl +s 2+s3;

avg - total/3 ;
printf(“ \nTotal marks = %f \ total);
printf(“ \ nAverage marks = %f \avg);
}
Output :
Enter marks of first subject ? 92
Enter marks of second subject ? 95
[ Ch # io] Inpwt/Outpid 277 -
Computer Science Part 11
Enter marks of third subject 7 98
Total marks = 285.000000
Average marks = 95 000000 ,

Q6. What are getch () and gctche( ) functions ?


An* .
getch () Function :
* It is used to get a single character as input from the keyboard during the execution of
the program .
* When a character key is pressed, the entered character is not displayed on the screen ,
* The prototype of getch ( ) function is in conio.h (console input/output ) header file.
* It does not accept any argument .
* There is no requirement of pressing enter key after typing the character.
Syntax:
_
getch ( ); or variable name = getch ( );
variable name is optional .
etche() Function ;
* It is similar to gctch() function and stands for get character with echo ,
* It is also used to get a single character as input from the keyboard during the program
execution.
* Difference between gelchf ) and getche( ) function is wTen a character key is pressed ,
the entered character is displayed on the screen.
* The prototype of getche( ) function is conio, h ( console input /output ) header file,
* It does not accept any argument .
* There is no requirement of pressing enter key after typing the character.
Syntax: getche( ) ; or variable = getche( ); Variable is optional .
Program :
Write a program in C language that takes a number of three digits from user and
prints it in reverse order,
#include<stdio.h>
# i n c 1 ude<Con10 h> ,

void main ( )
[ Ch # io] Inpwt/Outpid 278 -
Computer Science Part 11
1

int n,x,y,r;
clrscr( );
printf(“ Enter any number of three digit$\ t” );
scanf(“ %d’ \ &n ) ;
x=n/ 100;
n=n%100;
y=n / l 0;
n=n% J 0;
1=11* ] 00 + v* 10 + x ;

pr mlt (' Ro\ er sc of number is %d ” ,r );


getch ( );
Output :
Enter any number of three digits 584
Reverse of number is 485
Program :
Write a program in C language that takes roll number, name and address of a
student and display it on screen ,

#include<stdio,h>
#include<conio.h>
void main( )
j

int rollno;
char name[30], address[ 50 J :
clrscr( );
printf(“ Enter Your Roll Number\t” J;
scanf( “ %d ” &rollno );
t

prmtf(“ Enter Your Name\f ’);


scanf("%s", &namc );
print f( Enter Your Address\f ’);
44

scanf(“ %s% &address );


printfCYour Roll Number is %d\tf \ rollno ) ;
printf(“ Your Name is %s\ n ' \ name );
[ Ch # io] Inpwt/Outpid 279 -
Computer Science Part 11
prmtf(“ Your Address is %s\n” , address );
getc h( );
}
IC/tafrte? ii\

DECISION CONSTRUCTORS
Qi . What are control structures ? Also discuss its different types *

An $ +

Control Structures:
* These are the statements used to control the flow execution in a program or function .
* These instructions enable us to group individual instructions into a single logical unit
with one entry point and one exit point ,

* All programs use control structures to implement the program logic.


There are three types of control structures:
1* Sequence
2 * Selection
3. Repetition / Iteration / Loops
* Sequence
o The instructions arc executed in a sequence in which they are written in the program
,

o It is default flow of the program ,

o The execution of the program starts from first instruction and all instructions are
executed one by one in a sequence.
Example: compound statement:
>
Statements
St - 1
St - 2

I
* Selection
o A structure that selects w hich statement or block of statements is to execute.
[Cfi#nJ Decision Constructors 294 -
Computer Science Part 11
o In selection structure instruction are divided into two or more groups and the
selection is done after testing a condition .
Examples:
1. if - else
2. switch
* Repetition / iteration / loops:
0 These statements are used to repeat a set of statements as long as condition is true.
Examples:
I. for- loop
2 while loop
,

3 do-while loop
,

Q 2. What is an if statement? Explain with the help of an example and flow chart
Ans .
if statement:
* If is a keyword in C language. It is used to execute or ignore a set of statements after
testing a condition .
* A condition is a relational or logical expression and it produces either true ( means 1 )
or false ( means 0) result . If the condition is true then the block of statement is
executed and if the condition is false then the block of statement is ignored and the
control is transferred to the next statement after if statement .
Syntax :
if (relational or logical condition )
}

Block of statements
}
next statement after if
Example: Even or Odd Number
# mclude<stdio.h >
void main ( )
{
int n,r;
printf( “ \ n Enter any Number:
scanf(t4%d” , &n );
r= n % 2;
if(r==0)printf (“ \ ii The Number is Even “ );
if(r== l ) printf(“ \n The Number is Odd “ );
[Cfi#nJ Decision Constructors -
Computer Science Part 11
}
Flow Chart:
Start

F
Condition

If condition true then block of if statements

Next Statements after if

Slop

Program :
Write a program in C language that takes marks from user and display “ PASS ' if
marks are greater than or equal to 50.
# include<stdio .h>
# indudc<como h> +

void main( )
f
i
intm;
drser( );
printf("Enter your marks\ t” );
scanf(f 6%d” J&m);
if(m>=50)
printfCTASS” );
getch( );
}
Output :
[Cfi#nJ Decision Constructors 296 -
Computer Science Part 11
Enter your marks 60
PASS
Program :
Write a program in C language that takes two number and displays a message if
first number is square of second
#include<stdio,h>
#include<conio,h>
void main ( )
{
mt x? y;
clrscr( );
printf("Enter first numberit” );
scanf( “ %d ” &x );
printf("Enter second number ” );
scanf( “ %d’ \ fey);
(
^
if( x= y* y)
printf(< 4%d is square of %d \ y x ); '

getchf );
)
Program :
Write a program lo find out the roots of quadratic equation:
#include<stdio.h>
# ine I ude<math h> ,

void main ( )
*
float a 9 b 9 c,rl ? r2 ? dise.rcal ? itnag;
printfl Enter value of A?ss);
^
scanf( “ %f \ &a£
printf{“ Enter value of B?” ) ;
scanf( “ %f ’ ? &b );
printfl(“ Enter value of C?” );
scanf (“ %f >J &c);
disc = b*b-4.0*a*c;
if ( disc<0 )
>
real = -b/( 2.0*a );
imag = sqrt(-disc)/(2 .Q * a );
printf{“ Roots are imaginary if );
1
[Cfi#nJ Decision Constructors 297 -
Computer Science Part 11
printf(“ Rootl = %f +i %f \iT\ real , imag);
printf (“ Root2 = %f -i %f \n” , real , imag);
}
if ( disc = = 0)
/

rl = r2 = -b/(2.0*a);
printf(“ Roots arc real & cqual \rT );
printf(“ Rootl = %f \m \ rl );
printf{“ Root 2 = %f W \ r2);
}
if ( disc > 0 )
f

printf (“ Roots arc real and differentVi” );


rl = -b/(2.0*a) + sqrt(disc )/( 2 0*a );
,

r 2 = -b/(2.0*a ) - sqrt( disc)/(2.0* a);


printff ‘Rootl = %f \n” srl );
printfC‘Root2 = % f \ n ” r2);
}

Q3.
>What is an if-else statement? Explain with the help of an example and flow
chart.
A ns.
if-else statement:
* It is similar to if statement i.e. It is also used to execute or ignore a set of statements
after testing a condition . It is a two way decision making statement
* In if-else statement one condition and two blocks of statements are given. A condition
is a relational or logical expression and it produces either true (means 1 ) or false
( means 0 ) result . If the condition is true then the first block of statement is executed
and 2nd is ignored . And after executing the first block , the control is transferred to
next statement after if-else structure . If the condition is false then the first block of
statement is ignored and the 2nd block of statement is executed And after executing
.

the 2nd block of statement the control is transferred to the next statement after if-else
structure.
Syntax:
if ( relational or logical condition )
)

first Block of statements


>else
[Cfi#nJ Decision Constructors 298 Computer Science Part-11

\
2 ' 1lI block of statements
}
Next statements after if- else
[Cfi#nJ Decision Constructors 299 -
Computer Science Part 11

Flow Chart:

Start

Condition
T F

v >t
If condition true then block If condition false then
of if statements else part

>

Next Statements after if -else

I
Stop

Program :
Write a program in C language that finds whether a given year is leap year or not *

Leap year is a year that is divisible by 4 .


#include<stdio,h>
# inelude<conio h> ,

void mam( )
>
int y;
clr$cr( );
printfrEnter Year\t” );
[Cfi#nJ Decision Constructors 300 -
Computer Science Part 11
scanf( “ %d ” &y);
if( y%4 = =0 )
print Leap year” );
else
print f(“ Not leap year") ;
getch( );
}
Output :
Enter year 2008
Leap year
Program :
Even or Odd Number
# inckide<stdio .h>
#inc I ude<coni o h > ,

void main ( )
{
int n r;
?

printf (“ \n Enter any Number: “ );


scanf("%d’ \ & n ) ;
r=n%2 ;
if(r=0)
printf("\n The Number is Even “ );
else
printf("\ n The Number is Odd te );
}
Q4. What is conditional or ternary operator? Explain with the help of example.
Arts .
Conditional Operator or Ternary Operator:
* It is used as an alternative to simple if-else statement and it is also called ternary operator.
* It requires three expressions. First expression is relational or logical expression
( condition ) and it produces either true ( means 1) or false ( means 0) result ,

liJ
]

* If the condition is true then 2 expression after question mark (?) is executed and if
the condition is false then the 2nd expression is ignored and 3rd expression after colon
( : ) is executed.
Syntax :
Conditional Stateinent?true case statement: false case statement ;
[Cfi#nJ Decision Constructors 30 ] -
Computer Science Part 11
Example: Even or Odd Number
#include<stdio.h>
#inchide<conio. h >
void main ( )
{
int n,r;
printf(tt\n Enter any Number:
scanf( “ % d” , & n );
r= n % 2;
r== 0 ? printf(“ \n Even INumber“ ): printf ( “ \n Odd Number w);
}
Q 5. What is a switch statement? Explain with the help of example.
Ans.
Switch Statement:
* Switch is also a control structure and it is used to select one option from a set of
options .
* It compares the value of an expression against a list of cases.
* The case labels and the value of expression must be an integer or a character
* It must not be a float or double value. If the value of expression in switch is float or
double type then the compiler will generate an error message.
Svntax :
switch ( express ion )
{
ease label - 1 :
statements - 1 ;
break ;
case label - 2:
statements - 2 ;
break;
case label - 3:
statements - 3 ;
break ;

case label - n:
statements - n ;
break ;
[Cfi#nJ Decision Constructors 302 Computer Science Part-11
default ;
statements ;
}
* The value of expression is compared to each case label .
* The case whose case value matches the value returned by the expression is executed .
The use of break keyword :
* It must be included at the end of each ease statement and is used to exit from the body
of switch.
* If all break statements are omitted then the code of other cases after the matching case
will be executed sequentially.
The use of default keyword:
* Its use is optional and if none of the case label is matched . Then the statements under
default are executed.
* The position of default is not fixed . It may be placed before the tlrst case or after the
last case.
[Cfi#nJ Decision Constructors 3°3 Computer Science Part-11

Start

Case -1 Block 1
T

Case- 2
T i Block 2

F,

Case-m Block m
T

Default > Default Statements


[Cfi#nJ Decision Constructors 304 -
Computer Science Part 11

Example: Vowel or a Consonant:


# inchidc<stdio, h >
# inchidc<conio , h >
void main ( )
{
char ch;
printf(“ \n Enter any Character:
scanf(“ % c” , & ch ) ;
switcli(ch)
{
case £ a’ : case 4 A ?:
printf(££\n Vowel Character A “ );
break;
case V: case E’ : (

printf ( “ \ n Vowel Character E


break;
case T: case T:
printfC£ \ ii Vowel Character I t );
£

break;
case £ o’ : case ‘O’:
printf(£t\n Vowel Character O ££ );
break;
case £ u ?: case ‘IT:
printf ( “ \ n Vowel Character U £ ) ;£

break;
default:
priiitf{t £ \ ii It is a Consonant Character “ );
}
}
Q6. What is nested if statemnt? Explain with the help of example and flow chart.
Ans.
Nested - if statement :
* if statement within another if statement is called nested if statement .
* It is used for multi -way decision making.
* Nesting can be done up to any level . Increase in nesting also increase the complexity
of program .
* The else statement is optional It may be used with outer or inner if statement .
Syntax :
if( eondition - l )
{
if( condition - 2)
{
statements of inner if
}
) •
[Cfi#nJ Decision Constructors 3°5 -
Computer Science Part 11

Flow Chart:

Condition * Statements if true

Statements if false Statements if


false Condition

Statements if
true

Program :
Comparison of 3 values:
# include<stdio h > ,

void main ( )
i
i

int a.b.c ;
printf{"\ n Enter three Numbers :
scanf( “ %d %d % dT\ & a , &b, & c );
if(a>b)
{
if( a>c)
printf(“ \n first value a is largest");
else
[Cfi#nJ Decision Constructors 30G -
Computer Science Part 11

printf (“ \n third value e is largest * );


L

}
else
V

if( b>c )
print f{*'\n second value b is largest*');
else
printf(“ \n third value c is largest11);
}
}
Q7 . What is if-else-if statement? Explain with the help of example and flow chart .
A ns.
if-else-if statement:
- -
* If there are more than two alternatives, then wc use if else if instead of nested if
statement.
* It is used when multiple options are available and only one option is to be selected .
* Nesting can be done up to any Icvch
* The conditions in if are evaluated in a sequence .
* All the conditions are evaluated until a true condition is reached .
* When a true condition is found, then the statements under tme conditions are
executed and the remaining conditions arc ignored .
* If all conditions arc false, then the last statement - k after else is executed .
Syntax:
if( condition - l )
statement - 1

^
else if condition - 2 )
statement - 2
else if( condition -3 )
statement - 3

else if{condition - n )
statement - n
else
[Cfi#nJ Decision Constructors 3°7 -
Computer Science Part 11
statement - k
Program :
Perform arithmetic operations using if-else-if
# include<stdio .h>
# include<conio h> +

void main ( )
{
float a, b;
char op;
printf(“ \n Enter two Numbers :
scanf( %f %f \ &a , &b);
kt

printf(" n Enter operator + - * or / :


scanf( %c'\ & op);
bL

if( op printf(“ The Result = %.2 f \ a +b);


else if{op printflf 'The Result = %. 2 r,a - b );
+ ) prmtf The Result = %.2 f *,a*b ) ;
else if{op
^
i t; ?

else if(op=75) printf{“ The Result = %. 2 f \ a / b);


else printff Operator is invalid “ );
i
Flow Chart:
[Cfi#nJ Decision Constructors 308 Computer Science Part-11

Start

Condition Statements if true T

Conditio
Statements if true
jn else
*

Conditio
in else Statements if true

Statement if false

Stop

Comparison of nested if and sequence of if statement :


1) Sequence of if is simple than nested Nested if is more complex than sequence
if statement of if statement
In nested if when a logical decision is true
2) All conditions must be tested .
then the remaining conditions are ignored .
In nested if mostly statements are executed
3) In sequence of if statement , mostly
or ignored by testing the condition in outer
CPU time is consumed in testing all
structure, therefore, it is a time saving
conditions.
process.
Distinguish between if - cJse if statement and switch statement:
The “ nested if-else” and “ switch ” Statement:
Both the nested " hf-clsc and switch statement arc used for multiple selections but

following are the differences between these statements :


Nested if -else Statement Switch Statement
(i ) It becomes complicated for multiple It is easy to understand for multiple
[Cfi#nJ Decision Constructors 3°9 -
Computer Science Part 11
selections , selections.
(iO Jt uses an independent expression It uses a single expression for all cases but ,

for each ease, each ease must have a constant value of


integer type or character type.
( iii ) The Lest condition can be given in a Only a single expression is given in the
specified range of values. switch Statement which returns a single
If the given condition matches then value. The test condition cannot be given in
the statements under it will be a specified range. It is the major drawback
executed. of the switch statement.
Program ;
Write a program to locate a point in the coordinate plane.
#mclude<stdio.h>
void main( void )
/

int x , y ;
printf{"\ n Enter x - and y-coordmates?” );
seanf("%d %d’\ & x &y);
7 ?

iffx = = 0)
{
if( y= = 0)
printff “ The point is on the origin. );
11

else
printfp The point is on y-axis.’ );
1

}
else iffx > 0 )
{
if(y = = 0)
printff The point is on x -axis ." ) ;

else iffy > 0 )


printffThe point is in 1 st quadrant .” );
else
printffThe point is in 4 th quadrant . ) ;11

}
[Cfi#nJ Decision Constructors 310 -
Computer Science Part 11
else

if( y = = 0 )
printfCThe point is on x -axis / ' ) ;
else iffy > 0 )
printf("The point is in 2 nd quadrant /’ );
else
printf (‘Thc point is in 3rd quadrant /’);
}
}
IChaftM 12\

LOOP CONSTRUCTORS
01. What is a loop ? Also write its different types.
Ans *

It is a statement that is used to repeat a set of statements up to a fixed number of


times or until a given condition is satisfied.
There are two types of Loops
Conditional Loop { while and do-while loop )
Counter l o ( F o r Loop )
Conditional Loo
It is a loop that executes a set of statements as long as a given condition remains
true . There arc two types of conditional loops
While Loop
do-while Loop
Counter Loo 3
Counter loop is used lo repeat a set of statements for a specified number of times.
For Loop
02- What is w hile loop ? Explain with the help of example and flow chart .
Ans .
While Loo 3
While loop statement is used to repeat a set of statements until a given condition
is satisfied.
Syntax:
While ( Relational or logical expression i c. condition)
+

{
Statements ( Body of loop )

Explanation :
* When while statement is executed , the computer checks the given condition written in
parentheses.
* If the given condition is true then the statements enclosed in the braces (body of loop)
are executed .
[ Ch #iaJ Loop Constructors 328 Computer Science Part - fl
* After the completion of first iteration control is shifted to while and the condition is
again tested ,

* This process is repeated until the condition is true.


* If the condition is false then control is transferred the statement that comes after the
body of loop.
* Infinite loop: If the condition of loop never false then the loop never ends and it is
called infinite loop .
* Tn loop body there must be a statement such that the condition in while loop becomes
false.
* This loop is useful where the programmer does not know in advance how many times
the body of loop will be executed .

Start

Initialization

While Executes
Statements if test
fails

Execution of loop
If condition is true
Stop

Increment or
Decrement
[ Ch #iaJ Loop Constructors 329 Computer Science Part - fl
* Loop control variable: A variable whose value controls the number of iterations is
known as loop control variable .
* Loop control variable is always initialized before starting of the loop and incremented
and decremented inside the loop body.
Program:
Program to print first 10 natural numbers and find their sum .
# include<stdio .h>
void main(void)
{
int c= l , s=0; //declare and initialize loop control variable.
while (c < — 10 ) //condition
f

printir\ n %d > \ c ); //body of loop


s=s+c ;
c 7 increment or decrement pari
/
}
printf(“ Suin = %d ” s );?

}
Program :
Write a program in C language that display numbers from 1 to 5 square and cube
of each number using while loop ,

#include<stdio.h>
#include<conio,h>
void main( )

int n;
n= l ;
drscr( );
while( n <=5 )
{
printf(“ %d\t%d\t%d n’ \ rui*n, n * n*n );
n=n + 1 ;
}
getch ( );
}
Output :
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
[ Ch # ia] Loop Constructors 33° Computer Science Part - fl
Program :
Write a program in C language that takes an integer and prints it in reverse order .
#mclude<stdio h> «

# include<conio h> ,

void mainf )
>» .

int n , x = 0;
drscr( );
printf(“ Enter a number'd” );
scanf( “ %d '\ &n ) ;
whilc{n ! = 0)
>1
x=n% 10 + 10*x;
n=n / 10;
}
printf(“ %ds\x);
getch ( );
}
Output :
Filter a number 4321
1234
Program :
Write a program in C language that takes a number and decides whether it is
prime number or not ,

#include<stdioJi>
# i nc I ude<conio h> ,

void mainf )
f
\

int n , d , p;
drscr( );
p= l ;
[ Ch #iaJ Loop Constructors 331 Computer Science Part - fl
d=2;
printf(“ Enter a number\ t");
scanf(“ %d ” , & n );
while(d <=n/2)
{
if( n %d= =0)
p=0;
d=d+ l ;
}
if(p - =0)
printf("Not a prime number");
else
printf{“ Prime number");
getchf );
}
Output :
Enter a number 11
Prime number
Q3. What is a do-while loop? Explain with the help of example and flow chart .
Ans.
do - while Looi
It is similar to while loop i e. do- w' hile loop is used to repeat a set of statements
,

until a given condition is satisfied . In do- while loop condition is tested after the end of
loop body.
Syntax : do //keyword and starting of loop
{ // beginning of loop ody
Statements
} // end of loop body
While ( Relational or logical expression he. condition );
-
* In do while the condition is written at the end of loop body therefore loop is executed
at least once.
* After the execution of loop statements ( first iteration) it tests the condition.
* If the given condition is true then the statements enclosed in the braces ( body of loop )
are executed again . This process is repeated until the condition is true.
[ Ch #iaJ Loop Constructors 332 Computer Science Part - fl
* If the condition is false then control is transferred the statement that comes after the
while statement .
* Infinite loop: If the condition of loop never false then the loop never ends and it is
called infinite loop .
* In loop body there must be a statement such that the condition in do-while loop
becomes false.
* This loop is useful where the programmer does not know in advance howr many times
the body of loop will be executed ,

* -
The do while loop is important in such situations where we need to execute a certain
statements at least once.
* Loop control variable: A variable whose value controls the number of iterations is
known as loop control variable.
* Loop control variable is always initialized before starting of the loop and incremented
and decremented inside the loop body.
[ Ch # ia] Loop Constructors 333 Computer Science Part - fl

lirialization

Evecules ].»[ip

Increment / Urcrr
meiil

ii
4 While icmdilUni
1r in -

Next Statements
after liiop
[ Ch #iaJ Loop Constructors 334 Computer Science Part - fl

Program :
Program to print first 10 natural numbers using do while -
#include<stdio h> ,

void main ( void )


{
int c= 1 ;
do // starting of loop

printf (” \n%d \ c ) ;
?
//body of loop
c // increment or decrement pail
}
while (c < = 10); // condition
}
Program :
Write a program in C language that display all even numbers in a specified range
using do while loop.
#include<stdio.h>
#include<canio.h>
void main( )
{
int n , start , end ;
clrscr( );
printf(“ Enter stalling number\t” );
,
scanfi(ti%d \&star1j);
printf(“ Enter ending number\t");
scanf( “ %d \ &end );7

n=start;
do
i
if( n %2 = =0}
printf(“ %d \ jrsn );
n=n+ l ;
} \vhile( n<= end );
gctch ( );
}
Output :
Enter starting number 1
Enter ending number 10
2
4
6
8
[ Ch # ia] Loop Constructors 335 Computer Science Part - fl
10
[ Ch #iaJ Loop Constructors 335 Computer Science Part - fl

Program :
Write a program in C language that takes two numbers from user and displays the
result of first number raise to power second using do while loop
,

# include<stdio .h>
# include<a > nio , h>
void main ( )
i

int x , y ,z,r;
clrscr( );
printf(“ Enter first numberM'’ );
,
scanf( “ %d \&x);
printff ‘Enter second numbcr\t ” );
scanf(“ %d” f &y);
z= t :
i= l ;
do
{
r = r *x ;
z — z+ 11
} \vhile( z<=yj;
printf{“ Answer is %d \ r);
getch ( );
}
Output:
Enter first number 3
Enter second number 4
Answer is 81
Q4- What are the differences and similarities of while and do-while loop?
Ans.
Similarities and Difference between while and do-while loo
* Both are conditional loops.
* Both executed a set of statements as long as given condition is true.
* In while loop condition is tested before starling the loop .
[ Ch #iaJ Loop Constructors 337 Computer Science Part - fl
* In while loop statements arc executed if the given condition is true only ,
* while statement does not end with semicolon ( ; ).
* In do-while condition is tested after execution of loop statements .
* In do- while loop the condition is tested after the loop body therefore statements are
executed at least once.
* do-while statement ends with semicolon ( ;) .
Q5 * What is for loop? Explain with the help of example and flow chart *

Ans .
For Loo i 9
This loop is used to repeat a set of statements for a fixed number of times i e, in ,

for we knowr how many times the body of loop is executed .


Syntax :

for( initialization ; condition; incremcnt /dccrcmcnt)


{
Statements ( loop body )
}
* There arc three expressions in for loop.
* Initialization of loop control variable: It is executed only in first iteration . Data type
for this variable usually integer,
* Test condition : After initialization condition is tested and if condition is true then the
loop body is executed .
* Increment or decrement : After execution of statements the increment or decrement
part is executed.
* For the next iteration , the condition is again tested.
* If it is true then loop body is executed and then increment and decrement part is
executed and condition is checked again *

* This process continues as long as loop condition is true *

* If it is false, then the for-loop is terminated *

* The control is transferred to the instruction following the for loop.


* All the expressions are separated by semicolon are optional . Its syntax is:
[ Ch #iaJ Loop Constructors 33* Computer Science Part - fl
for ( ;) It is an infinite loop
Star!

Initialization

TEST Execute
FOR Statement? if
condition is false

Execution of loop
If condition is true

Increment or
Decrement

Similarities & Difference between w hile and for Looi IS


* Both are used to repeat set of statements
* The structure of for loop is different from while and do while loop,
* In for loop all the three parts ( initialization, condition , and increment/decrement ) are
in the same line and while and do while contains these part at different places ,
* The while and do while executes a set of statements until a given condition is true but
in for loop number of iterations are specified .
Example: program to print first 10 natural numbers using for loop
# includc<stdio .h>
void main (void)
{
mt c ;
for ( e= l ;c<=10 ;e++ ) // starting of loop
>» .

printf (” \n%d5 \ c ); // body of loop


[ Ch #iaJ Loop Constructors 339 Computer Science Part - fl
}
}
Example : Print 10 Even Numbers in descending order and find sum using for loop.
# include<stdio .h>
void main( )
i

ini i . s=0;
for( i =20 ;t 2? =2 )
~

{
printf(“ \ni = %d” ,i );
s += i;
}
printfTAn Sum = %d” , s);
}
Example : Print 10 Even Numbers in ascending order and find sum using for loop .
#inc 1 ude<stdio.h>
void main ( )
{
int Ls =0;
for( i=2 ;i <=20; i +=2 )
i
print f(“ \ ni = %d” fi);
s += i;
}
printfl(“ \n Sum = %d" s);
I
Example: Print 10 odd Numbers in ascending order and find sum using lor loop.
# include<stdio .h>
void main ( )

int its= 0;
for( i= l ;i <=19;i +=2 )
!
printf(“ \ni = %d” ,i);
s += i;
[ Ch #iaJ Loop Constructors 340 Computer Science Part - fl
}
printf{“ \n Sum = %d” , s);
}
Example: Calculate sum of reciprocal of 10 Natural Numbers using for loop.
S= l + l / 2 + l / 3+ + 1 / 10
# include<stdio .h>
void main ( )
1
1
int i ;
float s= 0;
for( i = l ;i <=10;i ++)
s — s + 1.0/i ;
printf{“ \ n Sum = %.2f \ s ) ;
}
Example: Calculate sum of reciprocal of 10 even Numbers using for loop.
S= l /2+ l /4+1/6+-- +1/2(1
#include<stdio.h>
void main( )
>
int 1;
float s= 0;
for( i =2 ;i <=20; i +=2 )
s = s + 1 0 / i; ,

print An Sum = %, 2 f\ s );
} ^
Example: Print squares of 10 natural numbers and Calculate sum of squares of 10
natural Numbers using for loop.
S= l 2+22+32+ +102
# include<stdio .h>
void main( )
{
int u s=0 ;
for( i= 1 ;i<= 10;i++)
i
,
print f( “ \n %d \t %d s i, i *i );
?

s = s + ( i * i );
[ Ch #iaJ Loop Constructors 34 ^i Computer Science Part - fl
}
printf (“ \n Sum = %d” , s);
}
Example: Print cubes of 10 natural numbers and Calculate sum of cubes of 10
natural Numbers using for loop.
S= l 3+23+33+ + 103
#include<stdio.h>
void main ( )
i

int i . s-0 ;
for( KL ;i<= ] 0; i ++)
i

print f{“ \n %d \t %d ' \ i,


s. = s + ( i * j * i );
}
printf(“ \ n Sum = %d' \ s);
}
Q 6- What is nested loop ? Explain with the help of example and flow chart.
Ans .
Nested Loo 0
* Nested loop mean loop inside the body of another loop is called nested loop.
* Nesting can be done up to any level .
* Nested loop increases the complexity of the program.
* There is no restriction on the type of loops diat may be placed in the body of other loops.
Example: Produce the following output using nested FOR loops
*

if: f: ft +
I: JJ:

# Pf*
iji J}E Sji
^ SfS sji
#include<stdio, h>
void main ( )
y

irit r,c;
for ( c= I ;c<= 7; C++)
i
i
for (r = l ;r < = c ; r ++ )
[ Ch # ia] Loop Constructors 342 Computer Science Part - fl
printfC *” );4

} ^
printff iT);

}
Example ; Produce the same output using nested loops ( internal loop is while)
#include<stdio. h>
void main ( )
>i
int r,c;
for ( c=7;c
{
- l ; c— )

while(r<=c )

printf(“ *” ) ;
r++;
}
printf(“ \n” );
}
}
Example: Produce the following output using nested FOR loops
UIJ u r IXJ hL u V uj vL
rp JJI m PTi m in PTB

+ 33CD(C I+= 3SC


#
sj? rfz
^

*
# inelude<stdio . h>
void main ( )
{
mt r, c ;
for ( c= 7;c> 1 ; c --)
f
I
for ( r = l ; r <=c;r++ )
>
*
printfT*");
[ Ch # ia] Loop Constructors 343 Computer Science Part - fl
}
printf(“ \n” );
}
}
Example ; Produce the same output using nested loops ( internal loop is while)
#include<stdio, h>
void main { )
!

int r,
c;
for (c=7;c
!
- ; c—
1 )

r= l ;
while(r<=c )
s
\
printf( ^ ^);
44

r++;
}
printf(“ \ ti” );
}
}
Example; Produce the same output using nested loops ( internal loop is do-while )
# indudc<stdio , h>
void main { )
s
\
mt r, c ;
for ( c= 7;c>= l ; c )
{

r= l ;
do
{
printf( );
T++;
}
[ Ch # ia] Loop Constructors 344 Computer Science Part - fl
whilc(r<=c ) ;
prmtff ' n” );
}
}
Example: Produce the above output using nested loops (both Loops are while )
# inchide<stdio . h>
void main ( )
{
int r, c;
C= 7 ;
whilc(o- L )
{
i= i ;
whi I e(r<=c)
I
printf{“ *” );
r++ ;
}
c--;
printf{"\ n” );
}
}
Example: Produce the above output using nested loops ( outer loop is do-while)
# include<stdio .h>
void main ( )
i
int r, c ;
C= 7 ;
do
{
=i;
whi I e(r<=c)
(
printf{“ *” );
r++ ;
]
[ Ch #iaJ Loop Constructors 345 Computer Science Part - fl
c-;
printf(“ \iT);
}
while{c>= l );
}
Q7. What is sentinel control loop? Explain with the help of example*
Ans .
Sentinel controlled loo a
* The values which are used to end the loops are called sentinel values and the loop that
ends with a sentinel value is called sentinel controlled loop .
* Sentinel loop is used when exact number of repetitions is unknow n.
* General form of sentinel controlled loop :
o Get a data value.
o Compare data value with sentinel value ,
o If it is not sentinel value then process the data
,

o Get another value using loop.


Example; find the average marks of the students in a class *
# inelude<stdio , h>
void main ( )
{
int sum=0, marks, tot _std =0;
float avg;
do
{
printf{“ \nEnter marks of a student or press -vc number to exit ” );
scanf(e‘%<T7 &marks );
if( marks >=0 )
{
_
tot std++;
sum = marks;—
}
}
while (mark $>=0 );
if( tot _std > 0 )
{
[ Ch #iaJ Loop Constructors 346 Computer Science Part - fl
avg = sum / ( float )totstd ;
printf(“ \n Average Marks are = %.2f ' , avg );
}
else
printf(“ \n Enter marks of at least one student “ );
}
Q8. What is goto statement? Explain with the help of an example.
Ans .
goto Statement :
* The goto statement performed unconditional transfer of control to the named label .
* The label must be in the same function .
Syntax :
goto label;

label : statement
Example : calculate the square root of positive numbers *
# include<stdio . h>
#i n c1 Lide<m ath , h>
void main ( )
y

float num ;
c: printf( “ \n Enter a + ve Number M );
scanf( “ %f \ & num ) ;
iff num < 0 )
goto c;
else
printffAn Square root of Number is %,2f \sqrt(num));
}
Example: Print the factorial of a number using while
# include<stdio . h>
void main ( )
f
t
int n ,c= l ;
printf{"\ n Enter any Number 0 to 7
scanfCL%d’\ &n );
[ Ch #iaJ Loop Constructors 347 Computer Science Part - fl
whilc{n >= l )
*
c =c*n ;
n-s
>printf(“ \n The Factorial of given number = %d fi
\ c );
}
Q9. What is an array? Explain with the help of an example.
Ans.
ARRAY :
* It is a collection of variables stored in a contiguous portion of memory having
common name and same data type.
* Each element of an array has separate subscript .
* The index always starts with 0 .
* Declaration of the array:
Data type arraynatuefsize];
Example:
char name[30 ] ;
int a[ 5 ];
name array contains 30 cells (variables of character type ) and variables starts from
name [0 ] to name [ 29] and a[5] array contains 5 variable of int type which are: a[ G],
a[ l ], a[2], a[a and a[4].
Example: Input and output of an array
#include<stdio h> ,

void main( )
{
int a [5J ;
a[0]=0;a[ l ]=10; a[2]=20;a[3]=30;a[4]=40; // initialization
printf(“ %d %d %d %d %d” , a[0],a[ 1 ],a[ 2]. a[3],a[4]);
}
[ Ch #iaJ Loop Constructors 34® Computer Science Part - fl
Q . 10 Explain the purpose of “ continue11 statement .
Ans.
continue statement :
The continue statement is usually used inside the body of a loop. It transfer the
control back to the beginning of the loop. When the continue statement is executed , the
control ignores the remaining statements in the loop body . It directly moves back to the
first statement as a next iteration. Consider the following example :
Program :
Write a C program that prints digits from I to 10 but 3 and 7 shouldn ’ t be printed.
# include <stdio.h>
# include <conio.h>
void main ( )
i
V

int a ;
for ( a = 1 ; a < = 10 ; a + + )
i

>
if ( ( a. = = 3}|| ( a = = 7 )
continue;
print f (‘* .n \t %d ” , a );
}
getch { );
}
Program :
Write a program in C language that displays the following output using nested
loop.
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
# include <stdio h> ,

# include <conio.h>
[ Ch # ia] Loop Constructors 349 Computer Science Part - fl
void main ( )
!
hit x, y ;
clrscr( ):
for ( x = 1 ; x < = 4 ; x ++ )
!

for ( y = 1 ; y < = 5;y++ )


printfC%d \f \ x *y);
printf( “ \n” );
}
getch { );
}
Program :
Write a program in C language that displays the following output using nested loop.
1
1 4
1 4 9
1 4 9 16
1 4 9 16 25
# include <stdio. h>
# include <conio. h>
void main ( )
i

mt x,y;
clrscr( );
x= l ,
for (x = 1 ; x < = 5;x4 )
t
>
for (y = 1 ; y < = x ;y++)
printf(“ %d\t” ,y*y);
prmtf(“ \[f );
}
getch { );
[ Ch #iaJ Loop Constructors 35 ° Computer Science Part - fl
}
Program :
Write a program in C language that displays the following output using nested loop.
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
# include <stdio. h>
# include < conio. h >
void main ( )
{
int x,y;
clrscr( );
x= l ;
for ( x = 1 ; x < = 5 ;x++)
i
i
for ( y = 1 ; y < = x ;y++)
prmtf("%d ,t” ,y);
printf(“ \n ” );
}
getch { );
}
Program :
Write a program to print numbers from 1 to 10 in ascending order by using one
variable and 10 to 1 in descending order by using another variable. Use only one for loop .
# include <stdio.h>
void main ( )
{
int a.b;
for ( a= 1 ,b= 10;a<=l 0:a++, b )—
printf(“ a = %d\t b = %d\n” , a, b);
)
Program :
Write a program to print the output as shown below:
[ Ch # ia] Loop Constructors Computer Science Part fl
-
35
'
1 2 3 4 5
1 3 5 7 9
1 4 7 10 13
# include <stdio.h>
void main { )
{
int u,ui;
elr$CT( );
u = l;
while (u<=3)
*
\

i = 1;
n = 1;
whiIe (i<=5)
{
printf(“ %d”,n);
n - n~u;
i = i+ 1;
}
printf{“ \n”);
u = u+1;
}
printf{“ \nPress a key to continue ,. , ” );
}
ICJuiflw /£ I

FUNCTIONS
01. What is a Function? Also write down its advantages *
Ans *
Function :
* A function is a complete independent program that performs a specific task .
* The main function call these type of functions according to requirement of a program *

* A program may have repetition of piece of code at various places and it is very
difficult to understand and debug larger programs, therefore, a larger program is
divided into simple and independent modules called functions ad this type of
programming is called modular programming.
Advantages of functions:

Functions make the program easier to understand and maintain.


They increase the readability of the program .
Functions may be reused in multiple programs .
The length of programs can be reduced using functions.
Functions can be executed as many times as necessary in the program .
When an error arises, rather than examining the whole program , the infected function
is debugged only.
Q 2 - What are different types of Functions ? Explain w ith the help of examples.
Ans *
Types of functions:
There are two types of functions in C .
o Built - in functions
o User defined functions .
Built-in functions :
-
* These are predefined functions provided by high level language All built in functions
*

are available in library and therefore called library functions .


* All the C library functions arc defined in header tiles which must be included in
writing C program.
[ Ch # i 3 Functions
j
37° -
Computer Science Part 11
Examples are :
o printf{ ) and scanf{ ) functions use stdio. h
o sqrt ( ) function uses math . h
O geteh ( ) ? getche( ) ? clrscr( ) functions use conio.h
User defined functions:
* The functions created by user are called user defined functions .
Q3 * How to create and use a user defined function ?
Ans .
* There arc three steps to create a user defined function
o Function prototype or function declaration .
o Function definition ,

o Function calling.
Function Prototype or Function Declaration :
* It is a statement that provides the basic information that the compiler cheeks and uses
a function correctly.
* The function prototype ( declaration ) consists of name of function its return type,
number of parameters and type of parameters ( arguments) .
* Function prototype is usually written at the beginning of the source flic (before main
function ).
* It is similar to variable declaration.
Syntax :
Retum type function name (parameter list ) ;
Return type :
* It represents the data type returned by the function e .g . int, float
,

* If the function does not return any value then the keyword void is used as return type.
Function name :
It specifics the name of the function e. g. sum , multiply etc .
Parameters ( arguments ) :
* The information provided to the functions is called parameters or arguments.
* In function declaration we specify the type of parameters separated by comma .
* If no parameter is used the keyword void is used between the parenthesis.
* The parameters specified in the function header are called formal parameters .
* The parameters passed to a function in the function call are called actual parameters.
[ Ch # i 3 Functions
j
37 ' -
Computer Science Part 11
Example:
o int sum ( int, int ); or int sum ( int x , int y) ;
o void display(void );
o float divide(float, int) ; or float divide(float x , int y);
* Semicolon represents the end of function declaration ,
Function Definition :
* Variable declaration and the function logic are implemented in function definition .
* The actual code of the function is called function definition.
* It is written outside the main function (before or after ).
* There are two parts of the function definition
o Function header
o Function body.
Function Header:
* It is the first line of the function definition ,
* It is similar to function prototype.
* it is not terminated with semicolon.
Function Body :
* Variable declaration and the function logic are implemented in function definition .
* It is enclosed in curly braces.
Return Statement:
* The return statement in the function body is used to specify the value returned by a
function.
* It is the last statement in the function body.
* The general form of return statement is
* return value/variable/expression;
* When return statement is executed , expression is evaluated and returned as the value
of the function.
* Execution of the function body stops when the return statement is executed.
* If the type of function is void then there is no need of return statement .
Function Calling
* It is a process that is used to invoke ( execute ) a function to perform a specific task .
* A function can be called at any point in the main program.
[ Ch # i 3 Functions
j
372 -
Computer Science Part 11

* A function can be called with its name and correct sequence of parameters.
* When function call statement is executed . Then the control is transferred to the
function body. And the statements in function body arc executed .
* After executing the last statements in the function, the control is transferred to the
calling function .
Q4 - What are local and global variables?
Ans .
Local Variables:
* All variables that we have declared within a pair of curly braces are called local
variables and their scope is local.
* The local variables can only be accessed in the function in which they are declared .
* They are not available outside the function.
* These are also called automatic variables. Variables in the functions are automatically
created when the function is executed and destroyed when the function terminates,
* The lifetime of a variable is the duration in which a variable exists in memory ( the
creation and destruction of the memory variable ).
* The scope of a variable refers to the region of a program in which it is accessible.
* The name of a variable is valid only within its scope not outside the scope.
Global Variables :
* The variables that wc have declared outside all the blocks of the program arc called
global or external variables.
* The scope of a variable refers to the region of a program in which it is accessible.
These variables can be accessed in any function at any time during the execution.
* They are available for all the functions in the program , following their point of
declaration.
* The lifetime of a global variable is until the termination of the program .
Q .5 What are static variables ?
Ans , Static Variables:
Static variables are special variables that are declared inside a function by using
the keyword “ static '. Like local variables, these can only be accessed in the function in
1

which they are declared but they remain in existence for the lifetime of the program .
Another difference between local variables and static local variables is that the
initialization in the static variables takes place only once when the function is called for
the first time. Each time a function containing a static variable is called, it uses the values
in the static variable assigned to it during the last execution of the function .
[ Ch # i 3 Functions
j
373 -
Computer Science Part 11
Since a static variable is initialized only once and is not destroyed , the function
containing static variables runs faster. The static variables are usually used to count the
number of times a function was called .
Q .6 How is data provided to the function ?
Ans , Passing Arguments to Functions ;
The arguments are used to provide data to the function. The function performs
operations on the data and produces result. The arguments are placed in parentheses. The
arguments arc either constants or variables . They arc written in the same sequence in
which they are defined in the function declaration. The arguments in the function
definition of the function are called formal arguments or formal parameters.
When a function is called , values are provided to the function . These values are
called actual arguments or actual parameters . The data type of actual arguments in the
function call must match the corresponding data types in the function declaration .
Actual arguments > temp (a, b . 16 , 2 ); a, b 16, 2 arc actual arguments
Formal arguments * void temp {int x, int y, float z ) x y, z arc formal arguments
?

Program :
Write a program in C language that displays a message by using a function.
# include <stdio h> ,

# include <conio. h>


void display( void );
void main ( )
{
clrscr( );

^
display );
getch );
(

}
void display( void )
{
printf(“ Paldslan” );
}
[ Ch # i 3] Functions 374 -
Computer Science Part 11
Output :
Pakistan
[ Ch # i 3 Functions
j
375 -
Computer Science Part 11

Program :
Write a program in C language that find maximum number from three numbers
by using a function .
# include <stdio, h>
# include <conio.h>
void max (int, int , int);
void maln( )
{
int x , y z ?

clrser( );
print f(*‘Enter first number \f ') ;
scanf( “ %d &x );
^
printf{“ Enter second number \tr’);
scanf(“ %d’\&y);
printf("Enter third number \t");
scanf("%d", &z );
max (x , y, z) ;
getch ( );
}
void max ( int a , int b, int c )
{
int m;
m=a;
iffh>m)
m = b;
if( c>m)
m=c ;
printf(“ Maximum Number is % d '\ m );
/

Output:
Enter first number 10
Enter second number 20
Enter third number 5
Maximum number is 20
[ Ch # i 3 Functions
j
376 -
Computer Science Part 11
Program :
Write a program in C language that find minimum number from three numbers by
using a function .
# include <stdio h> ,

# include <conio.h>
void min(int, int , int);
void main( )
{
intx, v z
?

drscr( );
printff 'Enter first number \t” );
scanf(“ %d’\&x);
printff 'Enter second number \f *);
scanf( “ %d ',&y);
7

printf(“ Entcr third number \t” );


scanf[H%d” >&z );
min(xf y, z);
getch( );
}
void minfint a , int b, int c )
{
mt m;
m=a;
if(b<m)
m = b;

m=c ;
printf{“ Minimum Number is %d’\ m);
}
Output :
Enter first number 10
Enter second number 20
Enter third number 5
Minimum number is 5
|Chaffin |
FILE HANDLING IN C
Ql. What is a stream ? Also discuss its different types.
A ns.
File:
* The data is stored in the form of files.
* A file is a set of related records .
Stream:
* A stream is a logical interface to a tile.
* A stream is associated to a file using an open operation.
* A stream is not associated to a file using a close operation.
* Stream refers to flow of data from source to destination .
* The process of entering data from the source is known as reading* fetching, getting or
extracting the data.
* The process of producing output data to the destination is known as writing, storing,
inserting orpuiting the data.
* There are two types of streams,
o Text Stream
o Binary Stream
Text Stream :
* A text stream is a sequence of characters.
* Character translations may occur in a text stream e .g. newr line is represented as
carriage return.
* There may not be one to one relation between the characters written and those on the
external device.
Binarv Stream:
* It is a sequence of bytes.
* The number of bytes written or read is always the same as those on the external
device. It means there is one to one relation between the bytes written or read and
those on the external device .
* No character translations occur in binary stream .
* Some additional bytes such as the file sector on the disk are added to the binary stream .
[ Ch # i 4] Fib Handling in C 392 -
Computer Science Part 11
Q2. What are tile markers? Explain the use of BOF, EOF and New Line.
Ans .
BOF, EOF, New line:
* A flic contains a number of characters or bytes and each file stored on a disk has a
start and an end .
* The start of first byte or character is called Beginning of file ( BOE ) .
* The end of last byte or character is called End of file ( EOF) .
* The position where data read or data write operations are performed is called current
position .
* EOF characters are placed after the last character in C .
* Enter key is used in text editor for new line but in C new line character is \n to be
7

placed at the end of each line,

Q3. Howr to open a tile using c language? Also discuss its different file opening
modes.
Ans .
File Openint;:
* Before read or write operations, a tile must be opened.
* All standard 111 e handling functions of C are declared in stdio.h.
* When a file is opened, a potion of memory is reserved for file to read and write this
memory is called memory buffer.
* When a file is Tead , it is first stored in the memory buffer and then program reads the
file from the memory buffer.
* When a file is written , then it is written in buffer, then the contents are transferred on
the disk ,
* The transfer of data from buffer to the disk is called flushing of buffer .
* The writing and reading through file through disk is time consuming. Therefore time
of reading and writing data to a tile is reduced through buffer.
The File Pointer:
* A pointer is like a variable whose content is the address of another memory cell
(variable).
* * represents a pointer to the variable with which it is used .
* A file is not directly accessible in C .
* Files are accessed through I/O buffers.
[ Ch # i 4] Fib Handling in C 393 -
Computer Science Part 11

* A file pointer is a variable of FILE type defined in stdio. h


* FILE * represents a pointer to a variable of FILE type
* The fopenf ) function is used to open a file.
* The function prototype is :
FILE *fp; // it specifies the file pointer.
fp= fopen ( filc mode ); ?

* fopen function takes two parameters.


Name of a file: if the tile is not in the current directory then its absolute path is given
and use escapes \ and \\ in the absolute path.
Opening mode : It is a string and enclosed in double quotes . Mode is a type of
operation that is performed on the file
Example:
FILE *fp
fp=fopen(‘‘XYZ DAT” ,” r” ); *

Example:
FILE * fpr
fpr= fopen(“ c:\\ tc \\XYZ. DAT” fV *);
File opening Modes :
* “ f open a text file for reading, each file must exists before reading
* “ w” open a text file for writing, if the file already exists then it contents are
overwritten, if it does not exists, it will be created
,

* “ a ’ open a text file for append . Data is appended at the end of existing file . If the file
'

does not exist , it will be created.


* “ r+” opens a file for both reading and writing . The file must already exists
*
<
Lw+” opens a file for reading and writing, its contents are overwritten. If the file does
not exist, it is created.
* “ a + opens a text file for both reading and appending. If the file does not exist, it is
"

created for both reading and writing.


* The fopen function returns the null pointer , if it fails to Open the file ( most common
reason is file does not exist ).
Q4- How to close a file in c language?
Ans .
Pile CLosin 3
* An open file must be closed after completing the tasks.
* When a file is closed then the buffer is flushed ( data is transferred on the disk ) ,
* If the file is not closed then the data may be lost.
[ Ch # i 4] Fib Handling in C 394 -
Computer Science Part 11

* The fcloseO function is used to close a file.

* Syntax:

* fclosc ( fp );

* Where fp is a file pointer associated to a file which is to be closed ,

* fclose () function returns 0 if the close operation is successfully completed ,

* fclose ( ) function returns EOF if any error occurs .


Q 5, How to read from and write character to a file using C language?
Ans .
HEADING AND WRITING CHARACTERS TO A FILE:
Once a file has been opened depending on its opening mode then either a
character can be read from a file or a character can be written to a file using the following
functions

ISSI9
* The putc ( ) function writes a single character to the file ,

* The putef ) function returns the character, if it successfully writes it ,

* The putc ( ) function returns the EOF if an error occurs.

* Syntax:
* putc(character ch ? file_pointer );

* Character ch can be character, inf constant or a variable .


* File pointer specifics variable of FILE type associated with the file in which character
is to be written .
Fxample: Design a program to write characters into a text file *

# inelude<stdio . h>
#inc I ude<c oni o h> *

void mainO
>

FILE * fp;
[ Ch # i 4] File Handling in C 395 -
Computer Science Part 11
char ch;
clrscr();
fp = fopcn( "c: \\tcst.txt","w");
pi intf ( 'Press ESC key to finish : \n ");
1

while(ch!=27)
{
ch=getcheO;
putc( ch.fp);
ifi(ch==V)prmtf("\n");
}
fclosc( fp);
}
Example: Design a program lo append data into an existing Fde writing character
bv characters into a text file.
# include<stdio . h>
#mclude<cotiio.h>
void main ()

FILE *fp;
charch , filename[30 ] ;
clrscr();
printf{"\ n Enter Name of file to append data 4 ");
seanf( tT%s’’ f &filename );

fp fopen( filenam a ,"a");
,,
] f ( fp== NULL )printf ( \ n File Does not exist ’ );
1

,
else printf( JI Type Data press ESC to finish »>»\ n ’ );
M

while(ch ! =27)

ch - getche( );
putefch , fp);
if( ch = V)printf( rViM );
}
fclose( fp );
}
[ Ch # i 4] Lie Handling in C 396 -
Computer Science Part 11

!53IS
* The getc( ) function reads the next character from the file.
* If an error occurs it returns EOF.
* The getc( ) function also returns EOF when the EOF is encountered .
* The file must be in open mode to use this function ,
* It automatically moves the next character when the function is again used .
Svnatx :
Variable gctc(filc_pointer);
~~

Variable is a character variable to which the character read from the tile.
Example; Write a program to copy data from one text file into another text file
( reading and writing character by character )
#include<stdio.h>
# inelude<conioJi>
void main ()
i
FILE * input;
FILE ^ output ;
char ch ;
clrscr( );
,
input = fopen( 'Tc:\\testLtxt LV);
if( input == NULL) printf{ ' p \ n can not Open tcstdxt filc\n");
else
{
output = fopen ( 11c :\\test2.txfVtwt1);
if( output = NULL )
,
printf( f \ n can not Open test 2.txt file\n");
else
whi 1e((ch=gcte ( input))! =EOF)
fputc(ch, output );
}
printf( "\ n After Execution data is copied from testl .txt to test2 txt \n ) ;
,
M

fclose( input);
fclose(output);
[ Ch # i 4] File Handling in C 397 -
Computer Science Part 11
Q 6. How strings are stored and retrieved in c language.
Ans .
String Handlin 3
Siring is a combination of characters and it is enclosed in double quotes.
Character array is used lo hold strings.
char name of string [sring_ length ] ;
char is data type and string length is the number of characters in a string.
A string variable can also be declared without specifying the number of characters .
The variable that is used to store a string is called string variable *
The last character of a string must be a Null character VO i .e * Null character \0 is
added to the end of the string.
Null character \0 is also included in the string length .
The string can be initialized:
char name[ 20 ] = “ Lahore";
char newstr [ ] = “ 1 Love Pakistan"
C uses string.h header file to handle the strings .
The most common string functions are:
o tputs( )
o fgets{ )
o strcpy( )
07. What is fputs() function ? Explain svith the help of an example.
Ans.
fputs( ) :
* It is used to write a string of characters in to a file.
'
T

* This function writes the string until the null character \0 is reached .
* It does not add the null character to the file ,

* The file must be opened or in append mode to write this function.


Syntax :

fputs(string: file pointer )


string are the characters that are to be written in the file.
[ Ch # i 4] File Handling in C 398 -
Computer Science Part 11
FILE * fp ;
,
fp = fopcn (“ tcstLtxf ? Hw ” ) ;
fputs(“ The String of your choice , fp );
The above string is written in test l .txt tile .
Example: Develop a program that writes three strings lengths of 50 by writing one
string at a time in a newr text file.
#mclnde<stdio.h>
#include<conioth>
void main( )

FILE * fp;
char str[50 ] ;
int r= l ;
clrscr( );
fp = fopen ( "c:\Ytest 1 .txt'VV1);
while(r<=3)
{
gets(str );
tputsfslr, fp);
fputs("\n",fp);
T++;

}
fclose( fp);
getch();
}
Example: Develop a program that appends three strings lengths of 50 by writing
one string at a time in an existing text file.
# include<stdio . h>
#inc1u de<c oni o h> *

void main( )

FILE * fp;
[ Ch # i 4] File Handling in C 399 -
Computer Science Part 11
char str[50 ],fname[30];
int r= l ;
drscr( );
printf{"\ n Enter Name of file to append Data »” ;
scanf( “ %s \ &fname);
fp = fopenffname, aNf ) ;
11

if( fp = = NULL ) printfi n File Does Not exist


while{r<= 3) ^ — ? ” );

{
gets(slr );
fputs ( str, fp );
fputs ("\ n"sfp );
r ++ ;
!
fclose( fp );
gctch ();
}
Q8. What is fgets() function ? Explain with the help of an example*
Ans *

fgets( ) :
* It is used to read a string of characters of a certain length from a file ,
* The file must be opened or in append mode to write this function.
Syntax:
Lr

fgcts(string or string variable, n , filc_pointer )


n is the number oF characters read from the tile .
Example : Program to display the contents of a file * Also compute and display the
number of lines of the file.
#include<stdio.h>
#include<conio h> +

void mainf )
{
FILE * sr;
char str[ 80 ],fn [ 12 ];
int c=0;
[ Ch # i 4] Fib Handling in C 400 -
Computer Science Part 11
clrscr();
printf(“ \n Enter Name of file to READ DATA »” ;
scanf( “ %s” , &fn ) ;
sr = fopen ( fn nrH);?

if(sr = = NULL) printfl[“ \n File Docs Not exist ?” );


while(fgets(stTj80 ?sr)!-NULL)
i

puts( str ) ;
c
}
printf{“ \n Total Number of Lines =% d \ c );
'

fclose(sr );
getchQ;
}
EXAMPLE : Write a program that name and telephone numbers of your friends
and write them in a file *
#incJude<stdio. h>
# i n e1 ude<eon i 0 h>
#include<string.h>
void main( )
1

FILE * fp ;
char name[30] lel[ 12] ; 1

fp=fopen(“ c: \\contact.txt” ,” w” );
if( fp = NULL ) printff “ \n can’ t open file for writing ! \ n” );
else
{
do
{
printf(“ \n Enter the Name or press Enter to quit
gets( name);
^ ” );

i f( strle u(na me )> 0)


i

printfC* Enter Telephone Number of maximum 10 characters : **);


[ Ch # i 4] File Handling in C 401 -
Computer Science Part 11
gets(tcl );
fputs(name, fp);
fputs(“ !", fp );
fputsftcl , fp);
fputs ( \n” , fp);
}
}
while ( strlen (name ) > 0 );
fclose(fp);
}
}
EXAMPLE : Write a program that will read your contact txt tile and display it on
*

the screen
# inelude<stdio . h>
# inelude<conio.h>
void main( )
{
FILE *fp;
char ch ;
int line =3;
clrscrf ); , ,
ip= fopen (“ c : \\contact.txt Vr ); ?

if( fp == NULL) printf("\n can ’ t open file for writing ! \ n");


else
>
printf(” Name “ );
gotoxy( 35, l );
printf(“ Phone #\n” );
print f(" \n” );
whi 1 e{(ch == getc( fp ))! = EOF )
1


ifl[ch ’!’)
gotoxy( 35 line );
else if )ch== \nJ ) ?
?

gotoxy( l , ++ line);
else
printfp/oc ” t ch );
}
}
[ Ch # i 4] File Handling in C 402 -
Computer Science Part 11
fclosc( fp );
getch ( );
}
EXAMPLE : Write a program that will append records in your contact .txt file.
# inelude<stdio . h>
#inelude<conioJh>
#include<strmg.h>
void main( )
1

FILE * fp;
char namepO], tel [ 12];
fp=fopen(“ c:\\contacttxfyV*);
m ,
NULL ) printfO% can ’ t open file for writing ! \ n );
?

else
\

do
1

printfOAn Enter the Name or press Enter to quit ” );


gets( name );
if( str1en ( namc )> 0 )
{
prmtf( ” Enter Telephone Number of maximum 10 characters :
gets(tel );
fpnts ( name, fp);
fputs(“ r fp );
fputs(tel, fp );
,
tputs(“ \nT fp );?

while ( strlen (name) > 0 );


[ Ch # i 4] File Handling in C 4°3 -
Computer Science Part 11
fclose ( fp );
>
}
Q9. How to read from and write to formatted data in a fde using c language?
A ns.
Formatted I /O:
* The formatted file input and output functions are used for reading and writing
formatted data .
Jn formatted I/O data is read or data is written in a specific manner in the fde.
The fprintf( ) function is used for formatted output in a file .
Its Syntax is:
fprintf{ file pointer, control string , arguments );
The arguments are variables and are optional .
The fscanf{ ) function is used to read formatted data from a tile.
Its syntax is:
fscanf( file _pointers contro [ string, arguments );
EXAMPLE : Write a program that name and telephone numbers of your friends
and write them in a file using formatted I/O.
# include<stdio . h>
#inc1 LI d e<c oni o. h>
#include<string, h>
void main( )
s
FILE * fp;
char name[ 30], tel 112];
fp= fopen( “ c:\\contact. txf 71w” );
if( fp == NULL ) printfOn can’t open file for writing ! \ n” );
else
s
do
{
printf{" n Enter the Name or press Enter to quit ” );
gets( name );
if(strlen( name )> Q )
s
printf("Enter Telephone Number of maximum 10 characters : ” );
gets( tel );
fprintf( fp, “ %s!%s n\ name, tel );

}
}
[ Ch # i 4] File Handling in C 404 -
Computer Science Part 11
while ( strlen (name) > 0 );
fclose( fp );
}
}

You might also like