Computer 12 Class Notes (Book)
Computer 12 Class Notes (Book)
Computer 12 Class Notes (Book)
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 ,
* 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.
2 Adil FSc
3 Umer I . Com
Record
[Ch # i ] Data Basics Computer Science Part-1 ]
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
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.
,
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 .
«
* Ffficient means stored data can be accessed very easily and quickly . Compact means
that stored data takes up as little space as possible ,
* 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 ,
* Hierarchical Model
o In a hierarchical data model , data are organized into a tree-like structure .
ELECTRONICS
PORTABLE
TELEVISIONS
ELECTRONIC
^
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 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
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 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 ]
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
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 ]
* 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,
o At this stage migration of data from one DBMS to another is very difficult
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.
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 ]
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 ,
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 Database Administrator
A database administrator ( DBA ) is a person who is responsible for the
environmental aspects of a database In general, these include :
*
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 The starting address of each field and its length is used to identify its storage location ,
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 Entity can be a person , object, concept or anything about which you can think of ,
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
* 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 .
, ,
* 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 ]
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]
* 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 ]
* 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
,
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
,
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 ,
o Designers first create a conceptual model of how data items relate to each other ,
EMPLOYEE
o The name of relationship is displayed over the line that represents the type of
connection *
Stocks
BOOK BOOK STORE
Sells
Returns
Above figure shows different connections between BOOK and BOOK STORE ,
country.
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
,
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
,
* 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".
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 ,
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
,
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
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 .
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
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 In this way user can easily understand the entities and attributes
,
* 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 ,
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 ,
M
history
i.
^
j y
IWy Doame ^ tt
m
Desktop
*
Favorites
* 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 ,
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*
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
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 .
* 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.
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 ,
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
* .
Employee ID
h
OK Cancel
Emfinyr. fi ID : 1 I
tille: [SatesfieDressrtaUve
* 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 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
J 9 9 fi
:i V63LUUS
G2 :i 12133 !
1997
92 5143/ 03
2 92 5145,(155
3 105 5143,320
109 5175,1 69
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 .
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 ,
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.
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 ,
ft
— —- —-
-
Ci
Ci
& B
b
-D-
El Forms
0 Reports
^
2
Pages
Macros
^ Modules
Groups
Favorites
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
'
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. +
Ans .
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 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.
Byte 0-255 1
* 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
@\!
^ 120
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
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
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 .
?
L Letter A through Z
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 *
^ 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
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
* 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
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
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.
To create a relationship
5 * Click and drag the primary key field from parent tabic and drop to the same field
on child table.
Cancel
ROIINQ •I Roll No
Join Type R R
Create NSW i
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
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
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
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) ,
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
* 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
,
Wildcard/Operator Explanation
and bill
> 0 and <=10 All numbers greater than 0 and less than 10
Summary Options ,
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
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
4. Select the fields that may contain duplicate values using arrow buttons.
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<
6 , Now select the field which you want to display along with the selected fields.
Find Duplicates Query Wizard
Do you want to view the query results, or modify the query design?
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.
Hum Wizard
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
6 , Now select the visual style for the form and press next button .
Form Wizard
7. This is the final screen for form creation. Here enter the name for form and press
finish button *
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 ,
* 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 This type of form is often used for the basis of sub form.
"
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
* ,
^ 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
,
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 ,
,
o Drag the sizing handles until the control is in the size you want.
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 .
2. Click the gray box before the row whose tab order is to he changed ,
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
* 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
,
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
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
IB
MBIUill UI1U
! IIBIIBBI IIP
^
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
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
»
<
«
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
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
Those are all the answers the wizard needs to create your combo
box ,
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 These are used when only one option from many is to be selected ,
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
P Kttt
JiWi \ \
I
'
<* What latiel do you want For each option?
Label Names
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 .
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
9 . Choose the type and style of option group and press next .
Option Group Wizard
"
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 ,
+
Categories: Actions ;
-
I Display Help on cust omiz in g the but t on
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
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
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
What data tvculd you like to usa far yiour subform or subreport?
— —- —
* 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.
^ ^ 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
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
^
b
1 - . - 2 - 3
l Qpen [ j Ne] “
O Ci D
i ! » * i i
4 Form Header
objects Create form in Design vie
.
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 $ +
1 , Click the tab control from toolbox and draw on the form .
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
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 *
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
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:
TableslQueries
[Table: Student
Available Fields: Selected Fields :
>
Name
Adctess >>
DOB
<
«
2 Select the information source for the report, select table/queries and their fields using
,
arrow buttons.
Report Wizard
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
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
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,
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
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 ,
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
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 ,
* 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.
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
\ f
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
* 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:
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 .
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
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 ,
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 ,
* 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
'
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 *
* 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 *
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
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.
"
, ,
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
,
Float 4 '
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
, +
* When the value assigned to a variable is less than the minimum allowable limit of an
integer i . e . -32768, an underflow occurs .
'
* 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 .
,
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
*
* Single line comments arc inserted by typing two forward slashes before the beginning
of a line *
* 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:
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
^
printfl Multip1ication is %d \ n > u1 );
printf( Division is %d\n” ,div);
46
* 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 .
,
—
* 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
,
* 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 ,
* 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
/, %
&& (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.
,
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
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 +
% 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 ,
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 ,
* If the value is smaller than the specified number of columns then the extra spaces arc
padded before or after the value ,
>
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 );
'
* 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 ,
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
^
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 ,
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 ;
#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
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 ,
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
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
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 )
)
\
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
>
I
Stop
Program :
Write a program in C language that finds whether a given year is leap year or not *
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;
?
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
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:
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
}
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
Start
Conditio
Statements if true
jn else
*
Conditio
in else Statements if true
Statement if false
Stop
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 ." ) ;
’
}
[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 *
{
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 ,
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
}
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> ,
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 ,
Initialization
TEST Execute
FOR Statement? if
condition is false
Execution of loop
If condition is true
Increment or
Decrement
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
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
*
# 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
,
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 ++ )
!
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:
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> ,
^
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
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
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
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
'
* Syntax:
* fclosc ( fp );
ISSI9
* The putc ( ) function writes a single character to the file ,
* Syntax:
* putc(character ch ? file_pointer );
# 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 ,
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
{
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
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);?
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);
^ ” );
the screen
# inelude<stdio . h>
# inelude<conio.h>
void main( )
{
FILE *fp;
char ch ;
int line =3;
clrscrf ); , ,
ip= fopen (“ c : \\contact.txt Vr ); ?
—
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
}
}
[ Ch # i 4] File Handling in C 404 -
Computer Science Part 11
while ( strlen (name) > 0 );
fclose( fp );
}
}