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

Computer PDF

The document is a comprehensive guide for Punjab Board Part-2 Computer Science students, created by Sir Taha Naveed, containing notes, MCQs, and practice questions across 14 chapters. It emphasizes understanding concepts over rote memorization, encourages active engagement with the material, and provides strategies for effective study and revision. The guide also includes tips for using the notes effectively and maintaining communication with the instructor for additional support.

Uploaded by

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

Computer PDF

The document is a comprehensive guide for Punjab Board Part-2 Computer Science students, created by Sir Taha Naveed, containing notes, MCQs, and practice questions across 14 chapters. It emphasizes understanding concepts over rote memorization, encourages active engagement with the material, and provides strategies for effective study and revision. The guide also includes tips for using the notes effectively and maintaining communication with the instructor for additional support.

Uploaded by

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

Punjab Board-Part 2-Computer Science by Sir Taha

Punjab Board
Part-2

ICS - Computer
Science
Chapters 1-14

Quick Notes
Important MCQs
Important Short Questions
Important Long Questions
Punjab Board-Part 2-Computer Science by Sir Taha

How To Use These Notes


Computer Science koi boring theory ka subject nahi... it's a full-on game of logic, flow aur thoda swag."

Assalam-o-Alaikum future legends!


Main hoon Taha Naveed — tumhara CS instructor, mentor, aur
banda jo chahata hai ke tum CS ke paper mein sirf pass na ho,
top karo.
Yeh file tum logon ke liye specially banayi gayi hai. Pure chapters
ke notes, tricky MCQs, board-targeted short & long questions —
sab ek hi jagah. Ab sirf focus karna hai aur grind shuru karo!

Kaisay Use Karni Hai Yeh File?

1. Pehle Notes Parho, Aaram Se


Jald baazi mein mat ghuso. Concepts ko samjho. Agar nahi
samajh aa raha, 2nd time parho.
Feel aa jaye toh kisi ko samjha ke dekhna – agar samjha
sakte ho, toh clear hai!

2. MCQs = Game Time!


Har MCQ khud solve karo. Key
baad mein
check karo.
Galti hui?
Chill karo.
Wapis concept
samjho aur try
again.
Har galti tumhe ek level aur
pro bana rahi hai.

3. Short/Long Questions = Apni Practice Book Mein


Likhna!
Copy-paste karo ge toh yaad nahi hoga.
Apni language mein likho, phir file se compare karo.
Jo question bar bar board mein aya hai, uspe laga do aur baar baar revise karo.

4. Repeat Until You Own It!


1 baar revision se kaam nahi chalega. Har chapter ko kam az kam 2 baar revise karo.
Paper ke 2 din pehle sirf practice karni hai, tension nahi leni.

Taha Sir’s Power Tips


Punjab Board-Part 2-Computer Science by Sir Taha

• Ratta nahi, logic samjho.


CS mein samajh zaroori hai — jo samjhta hai, woh yaad bhi rakhta hai aur likhta bhi mast hai.
• Flowcharts aur diagrams draw karo.
Visual memory strong hoti hai — plus examiner ko lagta hai "acha student hai".
• File ko share karo apne scene walay doston ke saath.
Smart log team banake padhai kartay hain.
• Mujhse baat karni hai? Toh WhatsApp open karo rn!
Papers ke tips, tricky questions, aur thodi motivation bhi chahiye ho toh just message:
0310-4539691
Message likhna: "Hi Sir Taha, CS squad mein add kar lo!"
And boom — you’re in!

Last Thing…
Tum paper likhne jaa rahe ho with a weapon — this file.
Use it smartly, stay chill, stay consistent. Aur haan, CS ka paper halke mein mat lena — full form mein dena!
All the best champs! CS ka paper phaad do!
– Sir Taha Naveed
Punjab Board-Part 2-Computer Science by Sir Taha

Table of Contents

Chapter 1: Data Basics ............................................................................................................................................5


Chapter 2: Basic Concepts and Terminology of Databases .................................................................................10
Chapter 3: Database Design Process ....................................................................................................................15
Chapter 4: Data Integrity and Normalization .......................................................................................................20
Chapter 5: Introduction to Microsoft Access ........................................................................................................25
Chapter 6: Table and Query ..................................................................................................................................30
Chapter 7: Microsoft Access-Forms and Reports .................................................................................................35
Chapter 8: Getting Started With C ........................................................................................................................40
Chapter 9: Elements of C.......................................................................................................................................44
Chapter 10: Input / Output ....................................................................................................................................48
Chapter 11: Decision Constructs ...........................................................................................................................51
Chapter 12: Loop Constructs .................................................................................................................................54
Chapter 13: Functions in C ...................................................................................................................................58
Chapter 14: File Handling in C.............................................................................................................................62
Punjab Board-Part 2-Computer Science by Sir Taha

• Stores executable instructions (.exe, .com


Chapter 1: Data Basics files).
Quick Notes:
5. File Organization Techniques
1. Data and Information
a. Sequential
• Data: Raw, unprocessed facts and figures. It has
• Records are stored in a specific sequence.
no meaning unless interpreted. Example: "Ali",
Access is slow and linear.
"85", "Lahore".
• Ideal for magnetic tape storage.
• Information: Processed, organized data which is
b. Direct (Random)
meaningful and useful for decision-making.
• Each record has an address calculated using a
Example: "Ali scored 85% in the Lahore Board."
key. Allows fast access.
• Why It’s Important: Forms the basis of all
c. Indexed Sequential
computing processes. Helps in making
• Combines sequential storage with indexing.
decisions, understanding patterns, and driving
Allows both fast and ordered access.
actions.
6. Database and Database System
2. Data Processing
• Database: An organized collection of logically
• The manipulation of data to produce
related data.
meaningful information.
• Database System: Includes the database,
• Activities in Data Processing:
hardware, software, and users.
o Data Capturing: Collecting data using
• Advantages: Efficient access, less redundancy,
source documents or devices.
more integrity.
o Data Manipulation: Includes operations
such as classifying, sorting, calculating,
7. Database Models
and summarizing.
a. Hierarchical Model
o Managing Output:
• Tree-like structure. One parent per child.
▪ Storage and Retrieval
b. Network Model
▪ Reproduction
• Allows multiple parent-child relationships.
▪ Communication
More flexible than hierarchical.
• Example: Exam scores collected → Total marks
c. Relational Model
calculated → Result sheets generated and
• Data stored in tables (relations). Most
emailed.
widely used model today.
3. Files, Records, and Fields
8. DBMS (Database Management System)
• Field: A single unit of data (e.g., Name).
• Software to create, manage, and interact with
• Record: A collection of fields about one entity
databases.
(e.g., a student's complete data).
• Key Features:
• File: A collection of related records (e.g., the full
o Data Dictionary
student database).
o Query Language (SQL)
• Importance: This structure is foundational for
o Report Generator
both file systems and databases.
o Access Security
o Backup and Recovery
4. Types of Files in Data Management
a. Master File
9. Data Independence
• Main data file, regularly updated, holds the
• Data structure is separate from application
latest info.
programs.
b. Transaction File
• Allows database changes without affecting
• Temporary file used to store data before it
code.
updates the master file.
c. Backup File
10. Data Integrity & Consistency Constraints
• Used to create duplicates of important data
• Integrity: Ensures accuracy and reliability.
for recovery.
• Constraints: Rules applied to maintain data
d. Data File
validity (e.g., roll number must be numeric and
• Stores data used by application programs.
unique).
e. Program File
Punjab Board-Part 2-Computer Science by Sir Taha

(c) Using code to auto-generate data


(d) Accessing files offline
Important Multiple-Choice
Questions (MCQs) Q9: Which of the following is a sequential access
Q1: Which of the following best represents data storage device?
integrity? (a) Hard disk
(a) The backup of information (b) Flash drive
(b) Avoiding duplicate data (c) Magnetic tape
(c) Accuracy and consistency of data (d) SSD
(d) Storing maximum data in less space
Q10: Which of the following is not a primary purpose
Q2: What is the key feature of the relational model? of a DBMS?
(a) Data in tree format (a) Data backup
(b) Parent-child relationship (b) Memory overclocking
(c) Data stored in tables with keys (c) Access security
(d) Binary-level indexing (d) Query processing

Q3: In direct file organization, records are accessed by: Q11: Which file is used to recover data in case of
(a) Scanning sequentially system failure?
(b) Calculating storage location using a key (a) Master file
(c) Index search (b) Program file
(d) Program-based linkage (c) Backup file
(d) Transaction file
Q4: Which file organization supports both sequential
and random access? Q12: A collection of interrelated data and a set of
(a) Direct file programs to access that data is called:
(b) Random file (a) Programming system
(c) Indexed Sequential file (b) Operating system
(d) Linear file (c) Database system
(d) Hardware system
Q5: Which component of DBMS helps define and Q13: Which model is considered most flexible and
manage metadata? widely used?
(a) Report writer (a) Relational
(b) Data dictionary (b) Hierarchical
(c) Query language (c) Network
(d) Backup manager (d) Object
Q14: What is the function of SQL in DBMS?
Q6: Which of these can result from redundant data? (a) Designing GUIs
(a) Better storage utilization (b) Connecting databases with HTML
(b) Faster search (c) Querying and modifying data
(c) Data inconsistency (d) Managing hardware
(d) Indexing problems Q15: What happens if a record breaks consistency
constraints?
Q7: What differentiates network model from (a) It is automatically corrected
hierarchical model? (b) It is allowed to save
(a) Uses only sequential access (c) It is rejected by DBMS
(b) Has cyclic child-parent links (d) It deletes other records
(c) Allows many-to-many relationships Q16: The parent node in a hierarchical model:
(d) Uses no pointers (a) Always has children
(b) Cannot have siblings
Q8: What does data independence allow? (c) Is also called the root
(a) Storing data without formats (d) Must be numeric
(b) Changing data structure without affecting program Q17: Which of these is NOT a valid file organization
type?
Punjab Board-Part 2-Computer Science by Sir Taha

(a) Sequential
(b) Random
Important Short Questions with
(c) Linear indexed Answers (2 marks each)
(d) Indexed sequential Q1: Define Data and Information. (2)
Q18: A program file usually has which extensions? Ans:
(a) .txt / .doc Data is a collection of raw facts and figures without
(b) .exe / .com context.
(c) .bat / .xls Information is processed data that is meaningful and
(d) .pdf / .png useful.
Q2: What is a Transaction File? (2)
Q19: Which operation is not a part of data Ans:
manipulation? A transaction file temporarily stores data before
(a) Summarizing updating the master file. It is usually used for batch
(b) Capturing processing.
(c) Calculations Q3: Differentiate between Record and Field. (2)
(d) Sorting Ans:
Q20: A data model that visually shows entities and • Record is a group of related fields (e.g., all data
their relationships is called: about a student).
(a) Access Map • Field is a single piece of information (e.g.,
(b) Flowchart student name).
(c) Data Model Q4: What is DBMS? (2)
(d) Relationship Tree Ans:
DBMS (Database Management System) is software used
to create, manage, and manipulate databases
MCQ Answer Key Table efficiently.
MCQ No. Correct Option Q5: What is meant by Data Integrity? (2)
Ans:
Q1 (c)
Data Integrity refers to the accuracy and consistency of
Q2 (c) data in a database throughout its life cycle.
Q3 (b) Q6: What are Consistency Constraints? (2)
Ans:
Q4 (c)
Consistency constraints are rules that ensure only valid
Q5 (b) and logical data can be entered into a database (e.g.,
Q6 (c) unique ID, not null).
Q7 (c) Q7: What is Data Independence? (2)
Ans:
Q8 (b) Data Independence is the ability to change the structure
Q9 (c) of the database without modifying the application
Q10 (b) programs.
Q8: Define the Relational Data Model. (2)
Q11 (c)
Ans:
Q12 (c) It is a data model where data is stored in tables (called
Q13 (a) relations), and relationships are formed using keys.
Q9: What is a Backup File and why is it important? (2)
Q14 (c)
Ans:
Q15 (c) A backup file stores a copy of important data. It helps
Q16 (c) restore data in case of system failure or loss.
Q17 (c) Q10: What is a Data Dictionary? (2)
Ans:
Q18 (b) A data dictionary stores definitions and structures of
Q19 (b) data elements in a database (e.g., data types, field
Q20 (c) names).
Punjab Board-Part 2-Computer Science by Sir Taha

Real-world Example:
IMPORTANT LONG QUESTIONS (8 A bank processes customer transactions to calculate
marks each) interest, update account balances, and generate
monthly statements that are either printed or emailed
Q1. Explain in detail the process of Data Processing to customers.
with examples. (8 Marks)
Answer: Q2. Describe different types of files and their uses in
Data processing is the procedure of collecting, DBMS. (8 Marks)
organizing, transforming, and communicating data to Answer:
produce useful and meaningful information. It is a core Files are essential components in data management
activity in computer systems and is crucial for accurate systems. They store data in organized formats for
decision-making. efficient processing, updating, and retrieval.
Main Stages of Data Processing: 1. Master File
• The main file that stores the latest version of
1. Data Capturing data.
o This step involves collecting raw data • Updated regularly.
from different sources such as forms, • Example: A student record file with up-to-date
surveys, sensors, or input devices marks and attendance.
(keyboard, mouse, scanner).
o Example: A school collects marks of 2. Transaction File
students through exam answer sheets. • Temporary file used to hold data before it
updates the master file.
2. Data Manipulation • Acts as a buffer.
o The collected raw data is then • Example: Fee payments stored in a transaction
manipulated using different operations file before updating the main fee ledger.
to make it more useful:
▪ Classifying: Grouping data into 3. Backup File
categories (e.g., students by • Contains a copy of original data to protect
grade). against data loss.
▪ Sorting: Arranging data in a • Critical for recovery processes.
specific order (e.g., ascending • Example: Weekly backups of the student
by roll number). database stored on external storage.
▪ Calculations: Performing
arithmetic operations like totals 4. Data File
and averages. • Created and used by applications to store data.
▪ Summarizing: Reducing large • Example: MS Excel worksheet storing inventory
volumes of data into concise data.
forms like reports.
5. Program File
3. Managing Output Results • Contains executable instructions.
o After processing, the output must be • Typically has extensions like .exe, .com.
managed effectively for future use: • Example: A payroll software executable that
▪ Storage: Saving processed data processes salaries.
to storage devices (e.g., hard
disks, cloud). Significance:
▪ Retrieval: Fetching stored data These files are used in combination to ensure data
when needed. accuracy, continuity, and integrity within a DBMS.
▪ Reproduction: Generating
duplicate copies (e.g., printing Q3. Discuss various file organization techniques and
report cards). their advantages. (8 Marks)
▪ Communication: Sharing data Answer:
through networks, email, or File organization refers to the way records are arranged
apps. within a file. It affects access time, flexibility, and
storage efficiency.
Punjab Board-Part 2-Computer Science by Sir Taha

1. Sequential File Organization • Example: Organizational charts.


• Records are stored one after another in a
defined sequence (e.g., roll numbers). 2. Network Model
• Advantages: • Each child can have multiple parent nodes.
o Simple and easy to implement. • Represents complex relationships.
o Best for batch processing. • Characteristics:
• Disadvantages: o Many-to-many connections.
o Slow access for large files. o More flexible than hierarchical.
o Inefficient for random access. • Example: Student-course registration systems
(many students enrolled in many courses).
2. Direct or Random-Access File Organization
• Uses a key to calculate the storage location of a 3. Relational Model
record. • Data is organized into tables (relations).
• Allows immediate access to any record without • Uses primary and foreign keys to relate tables.
scanning the entire file. • Characteristics:
• Advantages: o Most popular and flexible.
o Extremely fast for large databases. o Based on mathematical relations.
o Suitable for interactive applications. • Example: Inventory, billing, and customer
• Disadvantages: records in modern businesses.
o Wastage of storage due to space
allocation. Comparison:
• Hierarchical is fast but inflexible.
3. Indexed Sequential File Organization • Network is complex but versatile.
• Combines the benefits of sequential and • Relational is standard today due to ease of use
random access. and powerful query support.
• Uses an index file to quickly locate records.
• Advantages: Q5. What are the components of a database system?
o Balanced access speed. Explain their role. (8 Marks)
o Supports both sequential and random Answer:
operations. A Database System is a combination of various
• Disadvantages: components working together to manage and process
o Index file management can add data effectively.
complexity.
1. Data
Use Case Comparison: • Core content of the system.
• Sequential: Payroll processing. • Represents facts, transactions, and operations.
• Direct: ATM systems. • Example: Customer names, order details.
• Indexed Sequential: Library management
systems. 2. Hardware
• Physical devices used for data storage and
Q4. Explain different database models with processing.
characteristics and use-cases. (8 Marks) • Includes servers, storage media, input/output
Answer: devices.
A database model is a logical structure that determines • Example: Hard drives, cloud servers.
how data is stored, connected, and accessed in a
database system. 3. Software
• Includes the DBMS, operating system, and
1. Hierarchical Model related application software.
• Data is structured like a tree with parent-child • DBMS is responsible for managing data access,
relationships. storage, retrieval.
• Only one parent per child node. • Example: Oracle, MySQL, MS Access.
• Characteristics:
o Fast for predefined queries. 4. Personnel (People)
o Rigid structure. • Users who interact with the system.
Punjab Board-Part 2-Computer Science by Sir Taha

• Types: • No two records can have the same primary key.


o Database Administrator (DBA): • Cannot contain NULL values.
Manages the entire DBMS. Example:
o Application Programmers: Develop RollNo in STUDENT table.
apps to interface with databases.
o End Users: Retrieve, input, and 4. Foreign Key
manipulate data. Explanation:
• Example: Teachers entering marks in school • A key used to link two tables together.
management software. • It refers to the primary key in another table.
• It helps maintain referential integrity.
Summary: Example:
Each component has a vital role in maintaining the In the MARKS table, the "RollNo" can be a foreign key
efficiency, security, and functionality of the database referring to the STUDENT table.
system. The harmony between them is what allows
complex data environments to run smoothly. 5. Candidate Key and Alternate Key
Explanation:
• A candidate key is any field or combination of
Chapter 2: Basic Concepts fields that can act as a unique identifier.
• Out of all candidate keys, the one chosen as the
and Terminology of primary key is selected.
• The rest are called alternate keys.
Databases Example:
In EMPLOYEE (EmpID, NIC, Name), both EmpID and NIC
can be candidate keys. If EmpID is chosen as PK, NIC is
Quick Notes: alternate key.
1. Table, Rows, Columns (Relation, Tuple, Attribute)
Explanation: 6. Composite Key
• A table (also called a relation) is a two-
Explanation:
dimensional structure to store data. • A key composed of two or more attributes.
• Each row in a table is called a tuple or record
• Used when no single attribute can uniquely
and represents a single entry. identify a record.
• Each column is called an attribute and
Example:
represents a data field.
RollNo + Subject = Composite key in EXAM_RESULTS
Example: table.
STUDENT (RollNo, Name, Class)
• "STUDENT" is the table.
7. Secondary Key and Sort Key
• "RollNo", "Name", and "Class" are attributes.
Explanation:
• A row like (102, Ali, ICS) is a tuple.
• Secondary Key: A non-unique field used for
data retrieval.
2. Entity and Attribute • Sort/Control Key: Used to sort table records in
Explanation: a specific order (ascending/descending).
• An entity is anything about which data is stored
Example:
(like a person, object, concept).
"City" can be a secondary key. "Name" can be used as a
• An attribute is a characteristic or property of an
sort key.
entity.
• Attributes become the columns of a table.
8. Data View (Virtual Table)
Example: Explanation:
Entity: Student • A view is a virtual table generated by a SQL
Attributes: RollNo, Name, DOB, Class query.
• Doesn’t store data physically — displays data
3. Primary Key derived from base tables.
Explanation: • It enhances security and customizes data
• A field (or combination of fields) that uniquely
presentation for different users.
identifies each row.
Punjab Board-Part 2-Computer Science by Sir Taha

Example: (c) Unique


CREATE VIEW ICS_Students AS (d) Duplicated
SELECT RollNo, Name FROM Student 6. An attribute that refers to the primary key in
WHERE Class = 'ICS'; another table is called:
(a) Secondary key
9. Roles of Database Users (End User, Data (b) Composite key
Administrator, DBA) (c) Foreign key
Explanation: (d) Sort key
• End User: Accesses and manipulates data using 7. Which key may contain duplicate values?
applications. (a) Primary key
• Data Administrator (DA): Responsible for (b) Candidate key
deciding what data to collect and how to (c) Secondary key
organize it. (d) Composite key
• Database Administrator (DBA): Manages 8. The attribute or combination of attributes that
database system, ensures security, can be a primary key is called:
performance, backup, user permissions. (a) Alternate key
(b) Candidate key
10. Properties of Relations (c) Composite key
Explanation: (d) Secondary key
1. Each row is unique. 9. A primary key made up of multiple fields is
2. No duplicate rows allowed. called:
3. Column order is insignificant (referred by (a) Composite key
name). (b) Foreign key
4. Atomic attributes only (no multi-valued fields). (c) Sort key
5. Each column has a unique name. (d) Secondary key
These rules ensure data integrity, logical storage, 10. A view is also known as a:
and reliability in relational databases. (a) Base table
(b) Virtual table
(c) Derived table
Important Multiple-Choice (d) Subtable
Questions (MCQs) 11. Which of the following ensures data is not
1. A relation is also known as: duplicated in a table?
(a) Tuple (a) Foreign key
(b) Table (b) Primary key
(c) Attribute (c) View
(d) Field (d) Index
2. Each row in a table is known as a: 12. The user who manages the database is called:
(a) Field (a) Developer
(b) Attribute (b) End-user
(c) Tuple (c) Data administrator
(d) Column (d) Database administrator
3. The named columns in a relation are called: 13. A field used for sorting data is called:
(a) Records (a) Primary key
(b) Fields (b) Composite key
(c) Tuples (c) Sort key
(d) Attributes (d) Foreign key
4. The basic unit of a database is a: 14. A field or set of fields that helps in record
(a) Record retrieval but is not unique is:
(b) Table (a) Primary key
(c) File (b) Candidate key
(d) Column (c) Foreign key
5. A primary key must be: (d) Secondary key
(a) Composite 15. A table that contains a foreign key is called a:
(b) Nullable (a) Parent table
Punjab Board-Part 2-Computer Science by Sir Taha

(b) Dependent table MCQ # Answer


(c) Index table
18 a
(d) Root table
16. SQL stands for: 19 b
(a) Structured Question Language 20 c
(b) Structured Query Language
(c) System Query Language
(d) System Question Language
17. Which command is used to insert new data in a Most Important Short Questions
table? (2 Marks Each)
(a) ADD
(b) INSERT
(c) UPDATE Q1. Define Tuple. (2)
(d) NEW Answer: A tuple is a single row in a table or relation.
18. A record is a collection of: It represents a single record in the database.
(a) Fields Q2. What is a Primary Key? (2)
(b) Files Answer: A primary key is an attribute or a set of
(c) Tuples attributes that uniquely identifies each record
(d) Keys (tuple) in a table. It cannot contain null or duplicate
19. What is the minimum number of primary keys values.
in a table? Q3. Define Foreign Key. (2)
(a) 0 Answer: A foreign key is an attribute in one table
(b) 1 that refers to the primary key of another table. It is
(c) 2 used to establish a relationship between two tables.
(d) Unlimited Q4. Differentiate between Candidate Key and Primary
20. What does a Data Administrator (DA) do? Key. (2)
(a) Writes queries Answer:
(b) Designs reports A candidate key is an attribute or
(c) Develops policies for data management combination of attributes that can uniquely
(d) Executes SQL commands identify a record.
Answer Key Table The primary key is the selected candidate
MCQ # Answer key used to identify records.
Q5. What is a View? (2)
1 b Answer: A view is a virtual table created by
2 c querying data from one or more tables. It shows
3 d only selected data and helps ensure data security.
Q6. What is a Composite Key? (2)
4 b
Answer: A composite key is a primary key that is
5 c made up of two or more attributes. It uniquely
6 c identifies a record using the combination of fields.
Q7. What is an Entity? Give two examples. (2)
7 c
Answer: An entity is anything about which data is
8 b stored in the database, such as a person, place, or
9 a object. Examples: Student, Car.
10 b Q8. What are the responsibilities of a Database
Administrator (DBA)? (2)
11 b Answer: A DBA manages database security,
12 d performance, backups, user permissions, and
13 c ensures the integrity of the data.
Q9. What is a Sort Key? (2)
14 d
Answer: A sort key is an attribute or combination of
15 b attributes used to order records in a specific way,
16 b either ascending or descending.
Q10. Differentiate between Attribute and
17 b
Punjab Board-Part 2-Computer Science by Sir Taha

Tuple. (2) o Example: Roll_No and CNIC in a student


Answer: table can both be candidate keys.
Attribute is a column in a table that holds specific 5. Alternate Key:
data (also called a field). o A candidate key that is not selected as
Tuple is a row in a table, representing a single the primary key.
record. o Still unique and useful for searching.
o Example: If Roll_No is selected as the
primary key, then CNIC becomes an
Most Important Long Questions alternate key.
(8 Marks Each) 6. Secondary Key:
o A field or combination of fields used for
Q1. What is a Key? Explain different types of keys used data retrieval, not necessarily unique.
in a database. (8) o Used in queries and search operations.
Answer: o Example: City in a student table – many
In database terminology, a key is an attribute or a set of students can belong to the same city.
attributes that uniquely identifies a record (or row) in a 7. Sort/Control Key:
table. Keys are essential components of the relational o Used to physically sort records in a
database model. They ensure data integrity and particular order.
establish relationships between different tables. o Helps in generating ordered reports or
Types of Keys: search efficiency.
1. Primary Key: o Example: Sorting students by marks or
o A primary key uniquely identifies each alphabetical names.
record in a table.
o It cannot contain duplicate or NULL Q2. What are the properties of a relation? Explain in
values. detail. (8)
o Each table can have only one primary Answer:
key. In relational database systems, a relation is a table with
o Example: Student_ID in a student table. rows and columns. For a structure to qualify as a proper
2. Foreign Key: relation, it must satisfy certain properties. These
o A foreign key is a field in one table that properties ensure the consistency, integrity, and
refers to the primary key in another usability of the database.
table. Properties of a Relation:
o It is used to establish a relationship 1. Unique Rows (Tuples):
between two tables. o No two rows in a relation are identical.
o Ensures referential integrity. o This uniqueness is typically enforced
o Example: Department_ID in the using a primary key.
Employee table referencing ID in the 2. Atomicity of Values:
Department table. o Each attribute contains only one value
3. Composite Key: (atomic value).
o A composite key consists of two or more o Multi-valued attributes are not allowed.
fields that together uniquely identify a o For example, instead of a single field for
record. phone numbers, multiple columns or a
o Used when a single field cannot new table should be created.
uniquely identify a record. 3. Irrelevant Row Order:
o Example: In an Exam table, (Student_ID, o The order of the rows does not affect
Subject_Code) may form a composite the table’s meaning.
key. o Rows can be displayed in any sequence,
4. Candidate Key: and the relation remains valid.
o All fields or combinations of fields that 4. Irrelevant Column Order:
can uniquely identify records are o The sequence of columns (attributes) is
candidate keys. also not important.
o One of the candidate keys is chosen as o They are accessed by name, not
the primary key. position.
o Others become alternate keys. 5. Uniquely Named Attributes:
Punjab Board-Part 2-Computer Science by Sir Taha

o Every column in the relation must have


a unique name. Q4. Write a note on the responsibilities of a Database
o This avoids ambiguity when querying Administrator (DBA). (8)
the database. Answer:
6. Same Domain: A Database Administrator (DBA) is a professional who
o Each attribute in a column must be of manages the overall performance, security, and
the same data type. organization of databases within an institution or
o For example, if a column is for dates, organization.
every row must contain a valid date. Key Responsibilities of a DBA:
These properties ensure that the data is structured 1. Database Design:
logically, making operations such as SELECT, INSERT, o Create the structure of the database
UPDATE, and DELETE efficient and accurate. according to the needs of the
organization.
Q3. How are tables/relations formed in a relational o Decide on the tables, fields, data types,
database system? (8) relationships, and constraints.
Answer: 2. Access Control:
In a relational database, information is stored in the o Assign permissions to users depending
form of tables, also known as relations. A relation is on their role.
formed based on the concept of entities and their o Ensure sensitive data is accessed only
attributes. by authorized individuals.
Process of Forming Tables/Relations: 3. Backup and Recovery:
1. Identify the Entity: o Regularly back up the database to
o An entity is anything about which data prevent data loss.
is to be stored. o Implement recovery procedures in case
o Example: Student, Teacher, Product, of hardware failure or corruption.
etc. 4. Monitoring Performance:
2. List the Attributes: o Optimize the speed and efficiency of
o Each property of an entity is called an queries.
attribute. o Identify and fix performance
o Example: For Student – RollNo, Name, bottlenecks.
Class, City. 5. Data Integrity and Consistency:
3. Structure the Table: o Apply rules and constraints to ensure
o Attributes become the columns of the data is accurate and consistent.
table. o Prevent duplicate or invalid data
o Rows (tuples) represent individual entries.
records of the entity. 6. Maintenance and Upgrades:
o Example Table: o Keep the database system updated with
RollNo Name Class City the latest software and patches.
o Ensure compatibility with new
101 Ali 10th Lahore
technologies.
102 Sana 10th Karachi 7. Communication with Users:
4. Choose a Primary Key: o Help users understand the database
o One or more attributes that uniquely system.
identify a row are selected as the o Provide training and support when
primary key. needed.
o Example: RollNo The DBA plays a critical role in maintaining a secure,
5. Normalize the Data: reliable, and high-performing database system.
o Avoid data redundancy and ensure data
integrity by organizing attributes in Q5. Explain the concept and use of Views in a database
separate tables if necessary. system. (8)
Thus, forming a relation involves logical planning to Answer:
ensure each record is uniquely identified, data is stored A view in a database is a virtual table that represents
efficiently, and future queries can be performed with data from one or more tables through a query. It does
ease. not store data itself but displays data dynamically based
Punjab Board-Part 2-Computer Science by Sir Taha

on the SELECT statement used to create it. • Types of Relationships:


Purpose of Views: o One-to-One (1:1)
1. Data Security: o One-to-Many (1:N)
o Hide sensitive fields from users who o Many-to-Many (M:N)
don't have permission to view them. o Recursive (entity related to itself)
o For example, a view for students may
exclude salary fields from the teacher 3. Cardinality and Modality
table.
2. Simplified Access: • Cardinality tells the number of instances that
o Provide users with an easy-to- can participate in a relationship.
understand interface for complex o Example: One department can have
queries or multiple joined tables. many teachers → One-to-Many
o Avoid writing long SQL queries • Modality tells whether a relationship is optional
repeatedly. or mandatory.
3. Customized Data Presentation:
o Different users can be provided 4. ERD (Entity-Relationship Diagram)
different views according to their
needs. • A visual representation of entities, attributes,
o Example: A teacher might see only and relationships.
names and grades, while an admin sees • Symbols used:
fee status too. o Rectangle → Entity
4. Data Integrity: o Oval → Attribute
o Since views don’t store data, there is no o Diamond → Relationship
risk of data duplication or inconsistency. o Line → Connection
Creating a View (SQL Example):
CREATE VIEW ICS_Students AS 5. Data Modeling
SELECT RollNo, Name, Class
FROM Student • Process of defining and analyzing data
WHERE Class = 'ICS'; requirements for a database system.
• Includes:
This view will show only RollNo, Name, and Class of o Entities
students from ICS class. The base data remains in the o Attributes
original Student table, ensuring data security and o Relationships
efficient retrieval. • Helps to understand what data is needed and
how it should be stored.

Chapter 3: Database Design 6. Logical vs Physical Design

Process • Logical Design: Describes what data is stored


Quick Notes: and how relationships work (not concerned
with actual implementation).
1. Entity and Attribute
• Physical Design: How the data will be stored
(files, indexes, records, etc).
• An Entity is a real-world object (like student,
car, teacher) about which data is stored.
• An Attribute is a property that describes the 7. Data Distribution Strategies
entity. For example, attributes of a Student can
be Name, Roll No, Age, etc. • Centralized: All data at one site.
• Partitioned: Divided into fragments.
• Replicated: Copy of database at multiple sites.
2. Relationship
• Hybrid: Combination of above.
• A Relationship defines how entities are
connected to each other. For example, a 8. File Organization
Teacher teaches a Student.
Punjab Board-Part 2-Computer Science by Sir Taha

• How records are stored on a disk. 6. Which term describes whether participation is
• Types: Sequential, Direct, Indexed. optional or mandatory?
• Affects speed of access and storage efficiency.
• (a) Dependency
9. Database Development Process • (b) Cardinality
• (c) Connectivity
• Phases: • (d) Modality
1. Planning
2. Analysis 7. In an ERD, a rectangle is used to represent:
3. Design (Logical & Physical)
4. Implementation • (a) Attribute
• (b) Relationship
• (c) Entity
• (d) Cardinality
Important Multiple-Choice
Questions (MCQs) 8. Which of the following defines the correctness
and consistency of data?
1. The characteristics or properties of an entity are
called: • (a) Modality
• (b) Data Integrity
• (a) Field • (c) Redundancy
• (b) Entity • (d) Relation
• (c) Attribute
• (d) Class 9. The last stage of database design is:

2. A logical connection between entities is called: • (a) Logical Design


• (b) Planning
• (a) Attribute • (c) Implementation
• (b) Relationship • (d) Physical Design
• (c) Class
• (d) Object 10. Which strategy involves storing the entire
database at one site?
3. A recursive relationship means:
• (a) Partitioned
• (a) One entity related to another • (b) Replicated
• (b) An entity related to itself • (c) Centralized
• (c) Relationship with a key • (d) Hybrid
• (d) A reversed relation
11. In hybrid distribution, critical fragments are
4. An ERD represents relationships using: stored at:

• (a) Oval • (a) One site


• (b) Rectangle • (b) Multiple sites
• (c) Diamond • (c) No site
• (d) Triangle • (d) All sites

5. The number of instances involved in a 12. An example of one-to-many relationship is:


relationship is called:
• (a) Person – Phone
• (a) Modality • (b) Country – Capital
• (b) Dependency • (c) Mother – Child
• (c) Cardinality • (d) Student – RegNo
• (d) Entity Count
Punjab Board-Part 2-Computer Science by Sir Taha

13. Which of the following best represents data 20. The type of relationship in which one entity is
modeling elements? related to only one instance of another is:

• (a) Tables, Rows, Columns • (a) One-to-Many


• (b) Queries, Reports • (b) One-to-One
• (c) Entities, Attributes, Relationships • (c) Many-to-One
• (d) Files, Indexes, Keys • (d) Many-to-Many

14. The graphical representation of database MCQ Answer Key


structure is known as:
MCQ No. Correct Option
• (a) Conceptual Diagram
1 c
• (b) ER Diagram
• (c) Normalization Diagram 2 b
• (d) Flowchart 3 b
4 c
15. An index improves:
5 c
• (a) Complexity 6 d
• (b) Redundancy 7 c
• (c) Performance
8 b
• (d) Modality
9 d
16. Which phase defines input, output, and data 10 c
requirements? 11 b

• (a) Physical Design 12 c


• (b) Planning 13 c
• (c) Requirement Analysis 14 b
• (d) Implementation
15 c
17. A method for arranging file data on a disk is: 16 c
17 b
• (a) Data Modeling 18 b
• (b) File Organization
• (c) Data Integrity 19 a
• (d) Indexing 20 b

18. Which model describes the data in terms of ER


diagrams?
Important Short Questions (2
Marks Each)
• (a) Logical
• (b) Conceptual Q1. What is an Entity? (2)
• (c) Physical Answer: An entity is a real-world object like a
• (d) Analytical person, place, or thing that we store data about
in a database. For example, Student, Teacher, or
19. Which component of physical database design Course.
holds data rules? Q2. What is an Attribute? (2)
Answer: An attribute is a property or
• (a) Integrity Constraints characteristic of an entity. For example, Name,
• (b) Indexes Age, and RollNo are attributes of the Student
• (c) Views entity.
• (d) Reports
Punjab Board-Part 2-Computer Science by Sir Taha

Q3. Define Relationship. (2) 1. Entities


Answer: A relationship is a logical connection o An entity is an object or thing in the real
between two or more entities. For example, a world that can be distinctly identified.
Teacher teaches a Student. o Example: Student, Course, Teacher.
Q4. What is Cardinality in a relationship? (2) 2. Attributes
Answer: Cardinality defines the number of o Properties or characteristics of an
instances of one entity that can be associated entity.
with instances of another entity. It can be one- o Example: For Student → RollNo, Name,
to-one, one-to-many, or many-to-many. Age.
Q5. Define Modality in a relationship. (2) 3. Relationships
Answer: Modality defines whether the o A logical association between entities.
participation of an entity in a relationship is o Example: A Student "enrolls in" a
optional or mandatory. Course.
Q6. What is an ER Diagram? (2) Common Symbols in ER Diagrams:
Answer: ER Diagram (Entity Relationship Symbol Meaning Example
Diagram) is a graphical representation of
Rectangle Entity Student, Teacher
entities, attributes, and relationships in a
database. Oval Attribute Name, Age, ID
Q7. What is File Organization? (2) Diamond Relationship Enrolls, Teaches
Answer: File organization refers to how records
Line Connector Links entities and attributes
are physically arranged on a disk to ensure fast
and efficient data retrieval.
Q8. Name the major types of data distribution Example ER Diagram Explanation:
strategies. (2) Suppose we want to design a system where students
Answer: Centralized, Partitioned, Replicated, enroll in courses.
and Hybrid. • Entities: Student, Course
Q9. What is the purpose of physical database • Attributes:
design? (2) o Student → RollNo (PK), Name, Age
Answer: The main purpose is to implement the o Course → Code (PK), Title, Credits
database using files, indexes, and storage • Relationship: Enrolls
structures to improve performance and data o A student can enroll in many courses,
accessibility. and a course can have many students
Q10. Differentiate between Logical and (Many-to-Many)
Physical Design. (2) The ER diagram visually shows entities, attributes, and
Answer: Logical design defines how data is the “Enrolls” relationship using the symbols mentioned.
logically stored and related, whereas physical Purpose of ER Model:
design deals with actual storage on hardware. • Helps visualize database structure.
• Improves communication between
stakeholders.
• Reduces chances of data redundancy and
Most Important Long Questions (8 inconsistency before implementation.
Marks Each)
Q2. Discuss different types of relationships with
Q1. What is an ER Model? Describe its symbols and examples. (8)
components with examples. (8) Answer:
Answer: In ER modeling, relationships describe how two entities
The Entity-Relationship (ER) Model is a high-level are associated with each other. Understanding types of
conceptual data model introduced by Peter Chen in relationships is essential for designing accurate
1976. It is used in the early stages of database design to database schemas.
visually map out the structure and relationships of data Types of Relationships:
in an organization. ER modeling helps database
designers to systematically and logically organize data 1. One-to-One (1:1):
before it is physically implemented in a DBMS. • Definition: Each instance of Entity A relates to
Key Components of an ER Model: exactly one instance of Entity B, and vice versa.
Punjab Board-Part 2-Computer Science by Sir Taha

• Example: A Person has one Passport, and one o Many-to-Many (M:N): Students can
Passport belongs to one Person. take many courses, and each course has
Diagram Representation: many students.
Person ——— (has) ——— Passport
Modality
2. One-to-Many (1:N): • Describes the minimum number of times an
• Definition: One instance of Entity A can relate to entity can participate in a relationship.
many instances of Entity B, but Entity B can • Types:
relate to only one instance of Entity A. o Optional (0): Participation is not
• Example: A Teacher can teach many Students, mandatory.
but a Student is taught by one Teacher (in a Example: A student may or may not
specific subject context). register for a club.
Diagram Representation: o Mandatory (1): Participation is
Teacher ———< (teaches) ——— Student compulsory.
Example: Every student must be
3. Many-to-Many (M:N): assigned to a class.
• Definition: Many instances of Entity A relate to
many instances of Entity B. Diagram Explanation:
• Example: A Student can enroll in many Courses, • A vertical line (|) denotes “one” (mandatory).
and a Course can be taken by many Students. • A circle (O) denotes “zero” (optional).
Diagram Representation: • A crow's foot (<) denotes “many”.
Student ———< (enrolls in) >——— Course Example:
Teacher —|———< Class
4. Recursive Relationship: • This means: Each teacher must teach at least
• Definition: When an entity has a relationship one class, and each class is taught by only one
with itself. teacher.
• Example: An Employee may supervise another
Employee. Significance:
Diagram Representation: • Helps in defining constraints between entities.
Employee ——— (supervises) ———> Employee • Ensures correct representation of real-world
rules.
Importance in Database Design: • Guides database normalization and foreign key
• Helps in building correct foreign key design.
relationships.
• Prevents data redundancy. Q4. Describe and compare the basic data distribution
• Clarifies system requirements logically. strategies in physical design. (8)
Answer:
Data distribution refers to how a database is split and
Q3. Explain the concept of Cardinality and Modality in physically stored across multiple locations or systems in
relationships. Use diagrams if needed. (8) a distributed environment. It directly affects data
Answer: accessibility, speed, and reliability.
Cardinality and Modality define how entities participate
in relationships in ER modeling. 1. Centralized Strategy
• All data is stored at a single location or site.
Cardinality • Advantages:
• Describes the maximum number of instances of o Simplicity in maintenance.
one entity that can be associated with another. o Lower implementation cost.
• Types of Cardinality: • Disadvantages:
o One-to-One (1:1): A country has one o Single point of failure.
capital. o Poor performance for remote users.
o One-to-Many (1:N): A teacher teaches o High communication cost in networks.
many students.
2. Partitioned (or Fragmented) Strategy
Punjab Board-Part 2-Computer Science by Sir Taha

• Data is divided into segments and each segment • Understands the current system and identifies
is stored at different network nodes. gaps or inefficiencies.
• Advantages: • Data collection from users through interviews,
o Improves performance for localized surveys, etc.
access. • Outputs: requirement specifications and data
o Reduces load on a single server. flow models.
• Disadvantages:
o Requires complex data management 3. Design
techniques. • Subdivided into two stages:
a. Logical Design:
3. Replicated Strategy • Represents data using models like ER
• Entire database or portions are copied and diagrams.
stored at multiple locations. • Identifies entities, attributes, relationships,
• Advantages: keys, constraints.
o High data availability. • Independent of DBMS.
o Faster data access for local users. b. Physical Design:
• Disadvantages: • Converts logical design into actual database
o Synchronization issues. structures: tables, indexes, access paths.
o Increased storage cost. • Decides how data is stored, retrieved,
backed up.
4. Hybrid Strategy • Includes data distribution strategy, file
• Mix of partitioning and replication. Critical data organization, and indexing.
is replicated; non-critical data is partitioned.
• Advantages: 4. Implementation
o Balanced performance and reliability. • Physical creation of the database using SQL
o Tailored to organization’s needs. commands in a specific DBMS (e.g., MySQL,
• Disadvantages: Oracle).
o High complexity in design and • Includes:
maintenance. o Data definition
o Data entry and testing
Conclusion: o Performance tuning
Each strategy has its own use case. Choice depends on o Security setup
organizational needs like response time, data criticality, Conclusion:
network setup, and cost constraints. A well-planned design process ensures:
• Minimal redundancy.
Q5. Explain the complete database design process with • Data integrity.
its phases. (8) • Efficiency.
Answer: • Scalability of the database system.
Database design is a systematic process that ensures It also bridges the gap between user requirements and
the structure of the database meets all functional technical implementation, resulting in a robust and
requirements of the organization. It involves multiple efficient system.
phases to transform user requirements into a working
database system.
Chapter 4: Data Integrity
Phases of Database Design Process:
1. Planning and Normalization
• Initial phase where goals, scope, and resources
are identified.
• Involves feasibility studies: is the project
practical, affordable, and needed? Quick Notes:
• Outputs: objectives, time schedule, estimated 1. Data Integrity
costs. Data integrity ensures the correctness, consistency, and
accuracy of data in a database. It prevents invalid or
2. Analysis
Punjab Board-Part 2-Computer Science by Sir Taha

contradictory data from being entered. It's enforced • It has no transitive dependency (non-key
using constraints. The two major types are: attribute depending on another non-key
attribute).
• Entity Integrity: Ensures that the primary key in
a table is never NULL. 8. Synonyms and Homonyms

• Referential Integrity: Ensures that the foreign • Synonym: Same data described using different
key in one table must match a primary key in names in different tables.
another table or be NULL.
• Homonym: Same name used for different data
2. Functional Dependency in different tables.
Functional dependency (FD) is a relationship between
two attributes. If attribute B is functionally dependent 9. Partial and Transitive Dependencies
on attribute A (denoted as A → B), then for each value
of A, there is only one corresponding value of B. It is • Partial Dependency: A non-key attribute
crucial for normalization. depends only on part of a composite primary
key.
3. Anomalies in Database Design
Anomalies are problems that occur when inserting, • Transitive Dependency: A non-key attribute
deleting, or updating data. These include: depends on another non-key attribute.

• Insertion Anomaly: Can’t add data without the 10. Determinants


presence of another piece of data. A determinant is an attribute that determines the value
of another attribute in a functional dependency. It
• Deletion Anomaly: Deleting one piece of data appears on the left-hand side of the FD (e.g., A → B, A is
also removes important related data. the determinant).

• Update Anomaly: Requires changing data in


multiple places.
Most Important MCQs
4. Normalization
Normalization is the process of organizing data to Q1. In 3NF, which form of dependency is removed?
reduce redundancy and improve data integrity. It breaks (a) Functional
down large tables into smaller, related ones and (b) Non-functional
ensures data is stored logically. (c) Associative
(d) Transitive
5. First Normal Form (1NF) Q2. A relation is in 2NF if it is in 1NF and all its non-key
A table is in 1NF if all attributes contain only atomic attributes are:
values (no repeating groups or arrays). Every field must (a) Dependent on part of the primary key
hold only one value. (b) Dependent on the entire primary key
(c) Independent of the primary key
6. Second Normal Form (2NF)
(d) Independent of any other relation
A table is in 2NF if:
Q3. A relation is in third normal form if it is in second
normal form and:
• It is already in 1NF.
(a) Dependent on part of the key
• All non-key attributes are fully functionally (b) Dependent on all of the key
dependent on the entire primary key. (c) Independent of the key
(d) Has no transitive dependencies
7. Third Normal Form (3NF) Q4. What is the goal of normalization?
A table is in 3NF if: (a) Get stable data structure
(b) Increase number of relations
• It is in 2NF. (c) Create redundancy
(d) Improve performance only
Q5. Which of the following is removed in 2NF?
(a) Functional dependency
Punjab Board-Part 2-Computer Science by Sir Taha

(b) Partial dependency Q15. Which form of data causes mutual exclusiveness
(c) Transitive dependency problems?
(d) Associative dependency (a) Integer
Q6. In 1NF, a table must: (b) Yes/No
(a) Be free of repeating groups (c) String
(b) Have transitive dependency (d) Date
(c) Have composite key Q16. Which of the following is removed when a table is
(d) Contain derived values in 1NF?
Q7. Which integrity constraint ensures that primary (a) Partial dependency
keys are not null? (b) Repeating groups
(a) Entity integrity (c) Transitive dependency
(b) Referential integrity (d) NULL values
(c) Domain integrity Q17. Which anomaly prevents insertion of a record
(d) Foreign key integrity unless another record exists?
Q8. Referential integrity applies to: (a) Deletion anomaly
(a) Primary key (b) Insertion anomaly
(b) Composite key (c) Update anomaly
(c) Foreign key (d) Redundancy anomaly
(d) Candidate key Q18. Which rule ensures correctness of relationships
Q9. Which error occurs when the same attribute is across tables?
stored with different names? (a) Functional dependency
(a) Homonym (b) Referential integrity
(b) Redundancy (c) Determinant
(c) Synonym (d) Indexing
(d) Mutually Exclusive Q19. Which term is used when same name is given to
Q10. What is removed when a relation moves from different attributes?
2NF to 3NF? (a) Synonym
(a) Composite keys (b) Homonym
(b) Transitive dependency (c) Ambiguity
(c) Foreign keys (d) Replication
(d) Repeating groups Q20. A relation with atomic values only is in:
Q11. In a functional dependency A → B, A is called: (a) 1NF
(a) Foreign key (b) 2NF
(b) Dependent (c) 3NF
(c) Determinant (d) 4NF
(d) Candidate key
Q12. Which of the following is not a database MCQ No. Correct Answer
anomaly?
(a) Insertion
(b) Deletion Q1 (d)
(c) Modification
(d) Normalization
Q13. A relation with minimal redundancy and high Q2 (b)
usability is called:
(a) Clean
(b) Well-structured Q3 (d)
(c) Simple
(d) Complex
Q14. Storing the same data in multiple ways causes:
Q4 (a)
(a) Homonyms
(b) Synonyms
(c) Redundancy
Q5 (b)
(d) Exclusiveness
Punjab Board-Part 2-Computer Science by Sir Taha

Q1. What is Data Integrity? (2)


MCQ No. Correct Answer Data integrity refers to the correctness and consistency
of data. It ensures that the data remains accurate and
reliable throughout its lifecycle and is usually enforced
Q6 (a) through constraints.

Q2. What is Entity Integrity? (2)


Entity integrity is a rule that states the primary key of a
Q7 (a)
table must not contain NULL values. It ensures each
record in a table is uniquely identifiable.
Q8 (c) Q3. What is Referential Integrity? (2)
Referential integrity ensures that a foreign key in one
table matches a primary key in another table,
Q9 (c) maintaining consistency across related tables.

Q4. Define Normalization. (2)


Q10 (b) Normalization is the process of organizing data to
reduce redundancy and dependency by dividing large
tables into smaller, related ones.
Q11 (c)
Q5. What is a Functional Dependency? (2)
A functional dependency is a relationship between
Q12 (d) attributes in a table where the value of one attribute
determines the value of another. Represented as A →
B.
Q13 (b)
Q6. What is a Synonym Error? (2)
A synonym error occurs when different names are used
for the same attribute in different tables, leading to
Q14 (c)
inconsistency.

Q7. What is a Homonym Error? (2)


Q15 (b) A homonym error occurs when the same name is used
for different attributes in different tables, causing
confusion.
Q16 (b)
Q8. What is an Insertion Anomaly? (2)
An insertion anomaly occurs when it is not possible to
Q17 (b) insert a record into a table unless another related
record also exists.

Q18 (b) Q9. Define Partial Dependency. (2)


Partial dependency exists when a non-key attribute is
dependent on part of a composite primary key rather
Q19 (b) than the whole key.

Q10. What is Transitive Dependency? (2)


Q20 (a) Transitive dependency exists when a non-key attribute
depends on another non-key attribute instead of
depending directly on the primary key.

Important Short Questions with


Answers (2 marks each)
Punjab Board-Part 2-Computer Science by Sir Taha

Important Long Questions with Student(RollNo, Name, PhoneNumber) — multiple rows


for multiple phone numbers.
Answers (8 marks each)
2. Second Normal Form (2NF):
Q1. What is meant by Data Integrity? Explain its types A relation is in 2NF if it is in 1NF and every non-key
in detail. (8) attribute is fully functionally dependent on the whole
Answer: primary key.
Data integrity refers to the accuracy, consistency, and Example:
reliability of data stored in a database. It ensures that If a table has a composite key (e.g., RollNo, Course), and
the data entered and maintained is valid and attributes like StudentName only depend on RollNo,
trustworthy. Integrity is maintained through rules that violates 2NF.
known as constraints, which are applied to attributes in
tables. The main types of data integrity are: 3. Third Normal Form (3NF):
A relation is in 3NF if it is in 2NF and no transitive
1. Entity Integrity: dependencies exist. That means a non-key attribute
Entity integrity ensures that every table has a primary should not depend on another non-key attribute.
key and that this primary key is never NULL. This is Example: If in the Student table, Advisor depends on
because a primary key must uniquely identify each row Subject, and Subject depends on RollNo, then Advisor is
in a table. If it is NULL, uniqueness is lost and transitively dependent.
duplication may occur. For example, in a "Student"
table, the RollNo cannot be NULL. Q3. What are Database Anomalies? Explain Insertion,
Deletion, and Modification Anomalies. (8)
2. Referential Integrity: Answer:
Referential integrity is concerned with the relationships Anomalies are issues in databases that occur due to
between tables. It states that if a table has a foreign redundancy or poor structure. They are typically
key, the value in that foreign key must match an existing resolved through normalization.
value in the referenced table's primary key or must be
NULL. 1. Insertion Anomaly:
Example: If a "Marks" table has a RollNo (foreign key), it Occurs when we can't add data because some other
must match the RollNo in the "Students" table (primary unrelated data is missing.
key). This ensures consistency and prevents orphan Example: Can't add a new salesperson unless a sale is
records. made.

Integrity rules help maintain accurate data and avoid 2. Deletion Anomaly:
inconsistencies that might arise from insertions, Occurs when deleting a record causes loss of unrelated
deletions, or updates. data.
Example: Deleting a student’s record removes all details
Q2. What is Normalization? Discuss 1NF, 2NF, and 3NF of their advisor.
with examples. (8)
Answer: 3. Update (Modification) Anomaly:
Normalization is a systematic approach to organizing Occurs when changing a value requires multiple
data in a database. Its purpose is to eliminate updates.
redundancy and ensure logical data storage. It involves Example: Updating a teacher’s phone number in
dividing a database into two or more tables and defining multiple student records.
relationships between the tables.
These anomalies make the database unreliable, which is
1. First Normal Form (1NF): why normalization is essential.
A relation is in 1NF if it contains only atomic values (no
repeating groups).
Example:
Before 1NF: Q4. What is Functional Dependency? How does Partial
Student(RollNo, Name, PhoneNumbers) Dependency affect a relation? (8)
After 1NF: Answer:
A functional dependency exists when one attribute in a
Punjab Board-Part 2-Computer Science by Sir Taha

relation uniquely determines another attribute. It is


denoted as A → B. Chapter 5: Introduction to
Example: In a Student(RollNo, Name) table, RollNo →
Name. Microsoft Access
Quick Notes:
A partial dependency occurs when a non-key attribute List of the Most Important Topics with Detailed
depends only on part of a composite key. Explanations
Example:
1. Microsoft Access as a DBMS
Student(RollNo, Class, Name, ClassRoomNo) Microsoft Access is a powerful relational database
management system (RDBMS) that allows users to
• RollNo + Class is the composite key. create and manage databases through a graphical user
• If ClassRoomNo depends only on Class, it is a interface. It integrates easily with other Microsoft Office
partial dependency. applications, making it an ideal tool for small to
medium-sized applications.
Problems caused by partial dependency: 2. Database Window and its Components
The database window in MS Access is a centralized
• Data redundancy panel used to manage all database objects. It consists of
• Insertion and deletion anomalies the title bar, object bar (Tables, Queries, Forms,
• Complex updates Reports, Macros, etc.), and work area. This helps
organize the structure of your database efficiently.
Solution: Move the partially dependent attribute to 3. Database Objects
another table. MS Access provides key objects including:
• Tables: Store raw data in rows and columns.
Q5. Define Transitive Dependency. How is it removed • Queries: Retrieve specific data from one or
during normalization? (8) more tables.
Answer: • Forms: Used for data entry and viewing.
A transitive dependency exists when a non-key • Reports: Provide formatted outputs for printing
attribute depends on another non-key attribute, rather or sharing.
than directly on the primary key. • Macros & Modules: Automate tasks and add
For example: custom logic.
Student(RollNo, Name, Department, HOD) 4. Integrated Development Environment (IDE)
IDE in MS Access offers tools and features like wizards,
• RollNo → Department menus, toolbars, and property sheets to simplify
• Department → HOD database creation and management. It also includes
• So, RollNo → HOD is a transitive dependency. Visual Basic for Applications (VBA) for advanced
customization.
Problems it causes: 5. Queries and SQL
Queries are used to retrieve and manipulate data using
• Redundant data SQL (Structured Query Language). MS Access allows
• Anomalies during updates users to build queries using a graphical query designer
or by directly writing SQL code.
Removal: 6. Reports and Their Significance
Split the table into two: Reports are formatted outputs generated from queries
or tables. They help in analyzing data visually and are
• Student(RollNo, Name, Department) essential for presentations, audits, and decision-making.
• Department(Department, HOD) 7. Data Types in MS Access
MS Access supports several data types:
Now both tables are in Third Normal Form (3NF), with • Text
no transitive dependencies. • Memo
• Number
• Date/Time
• Currency
• AutoNumber
• Yes/No
Punjab Board-Part 2-Computer Science by Sir Taha

• OLE Object structure for the data in a database?


• Hyperlink (a) Table
8. Forms for Data Entry (b) Query
Forms provide an interactive layout for entering and (c) Report
viewing data. They can be customized with controls like (d) MS Word
buttons, drop-down lists, and checkboxes. Q8. The smallest meaningful unit of data in a database
9. Creating and Opening Databases is called:
Databases can be created using: (a) Byte
• Blank database (b) Record
• Database wizards (c) Character
• Existing templates (d) Field
Opening databases can be done through the Q9. The output of a query is in the form of a:
startup dialog or file menu. (a) Table
10. Macros and Automation (b) Form
Macros in Access allow automation of repetitive tasks. (c) Report
They can be linked to events like opening a form or (d) Macro
clicking a button. Q10. MS Access saves database with which extension?
(a) .msdb
Important Multiple-Choice (b) .mdb
(c) .madb
Questions (MCQs) (d) .accdb
Q1. A database consists of various components called: Q11. A query is written using:
(a) Tools (a) HTML
(b) Properties (b) XML
(c) Entities (c) SQL
(d) Objects (d) DDL
Q2. Which of the following object of database is used Q12. Which component provides graphical shortcuts
to retrieve data from database? for actions?
(a) Queries (a) Status bar
(b) Forms (b) Toolbar
(c) Reports (c) Scroll bar
(d) Tables (d) Menu bar
Q3. An MS Access table contains: Q13. The actual data of a database is stored in:
(a) Record but no fields (a) Tables
(b) Fields but no records (b) Forms
(c) Both records and fields (c) Reports
(d) None of these (d) Queries
Q4. Which option in MS Access is used to create a new Q14. Each set of related items in a table is called:
database from scratch? (a) Table
(a) Access template (b) Record
(b) Blank Database (c) Field
(c) Existing Database (d) Query
(d) New Folder Q15. Each word on the menu bar represents a:
Q5. What is displayed in Title bar of an open database? (a) Button
(a) Program name (b) Menu
(b) Database name (c) Window
(c) Object type (d) Form
(d) All of above Q16. Forms are used for:
Q6. Which of the following is NOT a database object? (a) Printing documents
(a) Table (b) Entering and viewing data
(b) Query (c) Backing up data
(c) Report (d) Sorting tables
(d) MS Word Q17. A report is usually based on:
Q7. Which object is used to store data and define (a) A form
Punjab Board-Part 2-Computer Science by Sir Taha

(b) A macro structured format.


(c) A table or a query Q5. What is the purpose of the Object bar? (2)
(d) A toolbar Ans: The Object bar categorizes the database objects. It
Q18. Which object is used to automate tasks in MS allows users to view and select objects like Tables,
Access? Queries, Forms, and Reports.
(a) Report Q6. What is a macro in MS Access? (2)
(b) Macro Ans: A macro is a tool that automates tasks by grouping
(c) Form actions together. It helps execute multiple commands
(d) Table through a single trigger.
Q19. Which object lets you view Access data on a Q7. What are Tables in MS Access? (2)
webpage? Ans: Tables are objects that store raw data in rows
(a) Form (records) and columns (fields). Each row represents one
(b) Macro record.
(c) Pages Q8. What is the function of IDE? (2)
(d) Report Ans: IDE stands for Integrated Development
Q20. Queries can be created using: Environment. It provides all tools needed to design and
(a) Design View or SQL View manage a database, including forms, reports, and
(b) Command prompt queries.
(c) Forms Q9. Name any two database objects. (2)
(d) Reports Ans: Tables and Queries.
Q10. What is an OLE Object? (2)
Ans: OLE stands for Object Linking and Embedding. It
allows insertion of objects like Excel sheets or images
MCQ Answer Key Table into the database.

Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8 Q9 Q10
Important Long Questions with
d a c b d d a d a b Answers (8 marks each)
Q11 Q12 Q13 Q14 Q15 Q16 Q17 Q18 Q19 Q20 Q1. What are the advantages of using Microsoft Access
IDE? (8)
Answer:
c b a b b b c b c a
Microsoft Access provides an Integrated Development
Environment (IDE) which simplifies database
development and management. Some of the extended
Important Short Questions with advantages include:
Answers 1. User-Friendly Interface:
Q1. What is MS Access? (2) MS Access has a graphical user interface (GUI)
Ans: MS Access is a powerful relational database that allows users to create and manage
management system developed by Microsoft. It helps databases without requiring deep technical
users to create, manage, and query databases using a knowledge. The drag-and-drop design and form
graphical interface. builders are ideal for beginners and non-
Q2. What is the use of reports? (2) programmers.
Ans: Reports are used to retrieve and present database 2. Sample Databases and Templates:
information in a formatted, printable layout. They help MS Access includes pre-built sample databases
users analyze and communicate results effectively. and templates for common use cases (e.g.,
Q3. Define Query. (2) contact management, inventory, orders, etc.).
Ans: A query is a command used to retrieve specific These serve as learning tools and can be
data from a database based on defined criteria. It can customized to meet user-specific needs.
also be used to update, delete, or manipulate data. 3. Wizards for Rapid Development:
Q4. What is the difference between a form and a Access includes several wizards such as Table
report? (2) Wizard, Query Wizard, and Report Wizard.
Ans: A form is used for data entry and editing, whereas These wizards guide the user through step-by-
a report is used for printing and presenting data in a step procedures to create database objects
Punjab Board-Part 2-Computer Science by Sir Taha

easily. The Access main window opens with a blank


4. Graphical Relationship Manager: database. The Database Window shows all
The Relationship Window in MS Access allows object types like Tables, Queries, Forms,
users to create and visualize relationships Reports, etc.
between tables. It is easier to establish one-to- Method 2: Using the File Menu
one, one-to-many, and many-to-many 1. Go to File > New:
relationships using graphical links. After launching MS Access, choose the ‘New’
5. Integration with Other Office Applications: option from the File menu.
Access databases can be linked with Excel, 2. Select ‘Blank Database’:
Word, and Outlook. For example, data from Choose from the available templates or click on
Access can be exported to Excel for advanced ‘Blank Database’.
analysis, or reports can be merged with Word 3. Complete Steps as Above:
for mailing purposes. Follow the same steps as in Method 1 to name
6. Built-in Macros and VBA: and save your database.
The IDE supports macros for automating Method 3: Using Database Wizard
repetitive tasks. For more complex logic, Visual 1. Launch Access and Select Database Wizard:
Basic for Applications (VBA) can be used to Choose “Access database wizards, pages, and
write functions and event-driven procedures, projects”.
enhancing the database's functionality. 2. Select a Template:
7. Rapid Prototyping and Development: Choose a template from the list (e.g., Contact
With easy-to-use tools, you can quickly Management).
prototype a solution for a real-world problem 3. Customize Fields and Layout:
and demonstrate it. This is ideal for small Follow the wizard’s steps to select fields,
businesses or educational institutions that need formats, and other preferences.
a low-cost solution. 4. Name and Save the Database:
8. Data Security and Validation: Provide a name and location for the new file
MS Access provides data validation features like and click Create.
input masks, lookup fields, and field-level MS Access then generates a fully functional sample
validation rules. This ensures the consistency database, which you can customize.
and accuracy of stored data.
Q3. Describe the various database objects used in
Q2. Explain the procedure for creating a new database Microsoft Access. (8)
in MS Access. (8) Answer:
Answer: Microsoft Access uses several objects to manage and
Creating a database in MS Access can be done through manipulate data effectively. These objects are stored
multiple methods. Here is the detailed step-by-step within a database file and include the following:
procedure: 1. Tables:
Method 1: Using Blank Database from Startup Dialog o The core object where data is stored.
Box o Data is organized into rows (records)
1. Launch Microsoft Access: and columns (fields).
Open Access from the Start menu or desktop o Each field stores a specific type of data
shortcut. such as text, number, or date.
2. Select ‘Blank Database’ Option: 2. Queries:
From the startup dialog box, choose “Blank o Queries are used to retrieve specific
Database”. data based on criteria.
3. Name the Database: o SQL (Structured Query Language) is
A dialog box will appear asking for the database used to write queries.
name. Enter a meaningful name, such as o They can also perform calculations and
StudentRecords. update data.
4. Choose Save Location: 3. Forms:
Navigate to the folder where you want to save o Graphical user interfaces for data entry
the database file. Access files are saved with and display.
.mdb (older versions) or .accdb extensions. o Easier for users to interact with data
5. Click Create: than using tables directly.
Punjab Board-Part 2-Computer Science by Sir Taha

o Can contain buttons, lists, and Suppose there is a Students table with fields: RollNo,
validation rules. Name, Class, Marks.
4. Reports: You want to find all students who scored above 600.
o Used to format and print data from SQL Query:
tables or queries. SELECT Name, Class, Marks FROM Students WHERE
o Ideal for summaries, invoices, and Marks > 600;
decision-making reports. Result:
o Can include headers, footers, and visual The query returns a datasheet showing only the
elements like charts. students who scored above 600 marks.
5. Macros: Queries are crucial in dynamic databases to keep data
o Used to automate repetitive tasks like retrieval efficient, flexible, and meaningful.
opening forms or running reports.
o Macros can run multiple actions with a Q5. Describe the steps to open an existing database
single command. file in MS Access. (8)
6. Modules: Answer:
o Allow advanced customization through To open an existing Access database file, follow any of
VBA (Visual Basic for Applications). the methods below:
o Used for event-driven programming and Method 1: Using the Startup Dialog Box
logic-based automation. 1. Start MS Access:
7. Pages (Deprecated in newer versions): Launch MS Access from the Start menu or
o Data Access Pages (DAP) were used to shortcut.
publish Access data to a web page. 2. Select 'Open an Existing File':
Together, these objects make MS Access a robust From the startup dialog, choose “Open an
platform for database applications. existing file”.
3. Browse and Select File:
Q4. What is a query in MS Access? Explain its Choose the desired .mdb or .accdb file from the
importance with an example. (8) list or click “Browse” to locate it manually.
Answer: 4. Click OK/Open:
Definition: The database will open in Access and the
A query in MS Access is a powerful tool used to extract Database Window will appear.
and manipulate data from one or more tables based on Method 2: Using the Main Menu of MS Access
specific criteria. It allows users to search, filter, sort, 1. Start MS Access and Cancel Startup Dialog:
calculate, and even update data. Cancel any startup options to go to the main
Importance of Queries: window.
1. Data Retrieval: 2. Use the File Menu:
Queries help retrieve only relevant data, saving Click on File > Open or press Ctrl + O.
time and improving efficiency. For instance, 3. Navigate to File Location:
instead of searching an entire student table, a Locate the database file in your directories.
query can fetch only those students who scored 4. Click Open:
more than 80%. The selected database opens and is ready to
2. Data Analysis: use.
They allow you to analyze trends or summarize Method 3: Double-Clicking from File Explorer
data. E.g., finding the average salary of 1. Navigate to the file location using Windows
employees. File Explorer.
3. Data Update: 2. Double-click the database file (e.g.,
Action queries can be used to update, delete, or school.accdb).
append records in bulk. 3. It will automatically open in MS Access.
4. Report Generation: Note:
Reports are often based on query results for When opening a database, you may get a security
focused data presentation. warning. If you trust the source, click “Enable Content”
5. Multiple Table Joins: to activate all features.
Queries can combine data from multiple related
tables into one datasheet view.
Example:
Punjab Board-Part 2-Computer Science by Sir Taha

to match text patterns in query criteria.


Chapter 6: Table and Query ▪ * matches any number of
Quick Notes: characters.
▪ ? matches a single character.
▪ # matches a single digit.
1. Design View and Datasheet View
6. Queries in MS Access
o Design View is used to define and
o A query extracts specific information
modify the structure of a table by
from tables based on given criteria.
specifying field names, data types, and
o Select Queries retrieve and display
descriptions. It also allows setting field
data.
properties such as field size, default
o Action Queries perform tasks like
values, and input masks.
deleting, updating, or adding data:
o Datasheet View is used to enter,
▪ Append Query – adds data to
modify, and view the data in table rows
an existing table.
and columns. It presents data in a
▪ Delete Query – removes
spreadsheet-like layout and is primarily
records.
used for data entry.
▪ Update Query – changes data in
2. Field Data Types
existing records.
o MS Access supports multiple field data
▪ Make Table Query – creates a
types such as Text, Memo, Number,
new table from selected data.
Currency, Date/Time, Yes/No,
7. Creating Queries Using Design View
AutoNumber, OLE Object, and
o Fields are selected from a table.
Hyperlink.
o Criteria are specified using operators or
o Choosing the correct data type ensures
wildcards.
accurate data input and enables
o Sorting order and calculated fields can
appropriate operations on the data.
be applied.
3. Field Properties
o Queries can be saved and reused.
o These determine how data is stored,
8. Relationships and Referential Integrity
entered, and displayed in fields.
o Relationships link tables using common
o Key field properties include:
fields.
▪ Field Size – limits the number of
o One-to-many is the most common type
characters or digits.
of relationship.
▪ Format – customizes how data
o Referential Integrity ensures
appears.
consistency between linked tables,
▪ Default Value – pre-fills a field.
preventing orphan records.
▪ Input Mask – enforces a pattern
9. Sorting and Filtering
for data entry.
o Sorting reorders records in
▪ Validation Rule & Text –
ascending/descending order based on
restricts and explains input
selected fields.
criteria.
o Filtering temporarily hides data that
▪ Required – determines if a field
does not match criteria.
must have a value.
10. Difference Between Sorting, Filtering, and
▪ Indexed – improves searching
Editing
and sorting.
o Sorting arranges data.
4. Filters in MS Access
o Filtering hides unwanted data.
o Filters allow users to view specific data
o Editing modifies data content.
by applying criteria.
o Filter by Selection – filters records that
match selected field data. Important Multiple-Choice
o Filter by Form – creates a custom filter Questions(MCQs)
with multiple field values.
o Filters are temporary and don’t modify
Q1: Every field in a table has:
underlying data.
(a) Field name and a data type
5. Wildcards in Queries
(b) Field name and a field number
o Wildcards such as *, ?, and # are used
Punjab Board-Part 2-Computer Science by Sir Taha

(c) Field number and a data type Q10: Which property is used to provide a default
(d) Field name, field number and data type value to a field?
(a) Field Size
Q2: A field’s width indicates: (b) Format
(a) Number of characters it can contain (c) Default Value
(b) Number of inches it takes on the screen (d) Validation Rule
(c) Number of pixels it takes on screen
(d) Number of characters visible to the user Q11: Which query type is used to extract data from
one or more tables based on specific criteria?
Q3: Which data type is the default type? (a) Append query
(a) Memo (b) Delete query
(b) Number (c) Select query
(c) Text (d) Make table query
(d) Auto Number
Q12: Which type of query is used to add new
Q4: What is the default field size of a text data records to the end of an existing table?
type field? (a) Append query
(a) 2 (b) Delete query
(b) 5 (c) Update query
(c) 20 (d) Parameter query
(d) 50
Q13: A query that prompts a user to input a value
Q5: Which data type can be used to define a field at runtime is called:
that stores numbers and allows calculations? (a) Action query
(a) Text (b) Parameter query
(b) Memo (c) Crosstab query
(c) Number (d) Union query
(d) Date / Time
Q14: Which of the following queries permanently
Q6: Which data type can store large amounts of removes records from a table?
text (over 64,000 characters)? (a) Select query
(a) Text (b) Make-table query
(b) Memo (c) Delete query
(c) Number (d) Append query
(d) Currency
Q15: Which property specifies a pattern for how
Q7: What is the purpose of OLE Object data type? data should be entered into a field?
(a) To store hyperlinks (a) Validation Rule
(b) To store objects like Excel sheets or pictures (b) Caption
(c) To store numeric values (c) Format
(d) To perform arithmetic operations (d) Input Mask

Q8: Which field property specifies how many Q16: Which wildcard is used to represent any
characters a field can hold? number of characters in a query?
(a) Format (a) ?
(b) Field Size (b) *
(c) Caption (c) #
(d) Input Mask (d) &

Q9: The Format property in MS Access is used to: Q17: In query design grid, the criteria row is used
(a) Change data type to:
(b) Rearrange field order (a) Sort records
(c) Control how data appears (b) Set primary key
(d) Delete records (c) Filter records
Punjab Board-Part 2-Computer Science by Sir Taha

(d) Rename fields marks each):


Q18: What does the Validation Text property do? Q1: What is the use of Design View in MS Access? (2)
(a) Specifies allowed data values Ans: Design View is used to define the structure of a
(b) Displays message if validation rule fails table. It allows the user to set field names, data types,
(c) Displays column heading and field properties. It is also used to set primary keys
(d) Sets default value and validation rules.

Q19: Which view in MS Access is used to define the Q2: How does Datasheet View differ from Design
table structure? View? (2)
(a) Datasheet view Ans: Datasheet View is used to enter, modify, and view
(b) Design view data in a table in rows and columns format, whereas
(c) Layout view Design View is used to define or modify the table
(d) Query view structure including fields and their properties.

Q20: The result of a select query appears in the Q3: What is a Primary Key in MS Access? (2)
form of a: Ans: A Primary Key is a field (or combination of fields)
(a) Report that uniquely identifies each record in a table. It
(b) Form prevents duplicate entries and ensures data integrity.
(c) Table-like datasheet
(d) Macro Q4: Define Field Size Property. (2)
Ans: Field Size is a property used to specify the
Answer Key Table maximum number of characters for a Text field or the
storage size for Number fields in a table. It controls the
Q.No Answer
amount of data that can be stored.
Q1 a
Q2 a Q5: What is a Validation Rule? (2)
Ans: A Validation Rule is a condition set on a field to
Q3 c
restrict the type of data that can be entered. It ensures
Q4 d data correctness, for example: >=0 AND <=100 for
Q5 c marks field.
Q6 b
Q6: What is the purpose of the Default Value
Q7 b property? (2)
Q8 b Ans: The Default Value property automatically assigns a
Q9 c predefined value to a field when a new record is
created, saving time and ensuring consistency.
Q10 c
Q11 c Q7: What is a Select Query? (2)
Q12 a Ans: A Select Query retrieves data from one or more
tables based on specific criteria. It is used to filter and
Q13 b display selected data in a datasheet format.
Q14 c
Q15 d Q8: What is a Parameter Query? (2)
Ans: A Parameter Query prompts the user to input a
Q16 b value when the query is run. It uses that value as a
Q17 c criterion to filter records.
Q18 b
Q9: Define Input Mask with an example. (2)
Q19 b Ans: Input Mask controls how data is entered into a
Q20 c field. For example, to accept a phone number in the
format (999) 000-0000, the Input Mask would be (000)
000-0000.
Important Short Questions (2
Q10: What is the purpose of using wildcards in
Punjab Board-Part 2-Computer Science by Sir Taha

queries? (2) This method allows you to fully control the table’s
Ans: Wildcards are used in queries to search for structure, ensuring data integrity, applying validation,
patterns in text. For example, A* will return all values and formatting your data before any entries are made.
starting with the letter A. ? represents any single
character. Q2: Define and explain different data types available in
MS Access. (8)
Important Long Questions (8 Ans:
MS Access provides a range of data types to define
marks each): what kind of data can be stored in each field of a table.
Q1: Explain the procedure for creating a table in MS Each data type has its own purpose:
Access. (8) 1. Text:
Ans: o Stores alphabetic characters, numbers,
Creating a table in MS Access involves defining the or symbols.
structure of data you want to store. There are multiple o Maximum length is 255 characters.
methods to create tables in Access, but the most o Default field size is 50 characters.
detailed and flexible one is using the Design View. The o Cannot perform calculations on this
procedure is as follows: data type.
1. Create a New Database: 2. Memo (Long Text):
o Open MS Access. o Stores long blocks of text (up to 65,535
o Click “Blank Database.” characters).
o Enter a name for the database and click o Useful for comments, notes, or
“Create.” descriptions.
2. Open Design View: o Not suitable for indexing or primary
o In the “Tables” section, click “Table keys.
Design.” 3. Number:
o This opens the Design View where you o Stores numeric values that can be used
define the table structure. in calculations.
3. Define Fields: o Field size options include Byte, Integer,
o In the first column (Field Name), enter Long Integer, Single, Double.
the name of your field (e.g., Roll_No, o Allows formatting like currency,
Name, Address). percentage, etc.
o In the second column (Data Type), 4. Currency:
select the appropriate data type (e.g., o Stores monetary values.
Text, Number, Date/Time). o Automatically rounds to two decimal
o In the third column (Description), places.
provide optional comments about the o Supports large numbers and prevents
field. rounding errors in financial data.
4. Set Primary Key: 5. Date/Time:
o Click on the field that will uniquely o Stores date and time values.
identify each record (e.g., Roll_No). o Supports date calculations and
o Click the "Primary Key" button on the formatting options.
toolbar to assign it. 6. AutoNumber:
5. Set Field Properties: o Automatically generates unique
o At the bottom of the Design View, you numbers for new records.
can configure field properties like Field o Commonly used for primary keys.
Size, Format, Default Value, Validation 7. Yes/No (Boolean):
Rule, Input Mask, etc. o Stores logical values like Yes/No,
o For example, you can set Field Size to 50 True/False, On/Off.
for text fields or format Date/Time o Ideal for flags, toggles, or binary
fields for consistent entry. choices.
6. Save the Table: 8. OLE Object:
o Click the “Save” icon or press Ctrl+S. o Stores objects like Excel spreadsheets,
o Enter a name for your table and click Word documents, images, or sound
OK. files.
Punjab Board-Part 2-Computer Science by Sir Taha

o Allows integration with other software Query Language) for advanced control.
through embedding. Advantages of Queries:
9. Hyperlink: • Time-saving and user-friendly data retrieval.
o Stores clickable links to websites, files, • Helps in decision-making by summarizing
or email addresses. relevant data.
10. Attachment (Newer versions): • Allows creation of dynamic forms and reports.
• Stores files like images, documents, PDFs • Reduces redundancy by filtering only the
directly in the database. needed information.
Each data type ensures data is stored efficiently and • Can be saved and reused for regular reporting
accurately according to the field’s requirements. or analysis.
Queries are powerful tools in MS Access that enable
Q3: What is a Query? Explain its types, uses, and complex data manipulation without programming.
advantages. (8)
Ans: Q4: What are Field Properties? Explain different types
A Query in MS Access is a tool used to retrieve specific of field properties. (8)
information from database tables. It allows users to Ans:
extract, filter, sort, and summarize data based on Field Properties define how data is stored, validated,
defined criteria. and displayed in each field of a table in MS Access.
Uses of Queries: These properties ensure data accuracy, enhance data
• Display records matching a condition. entry, and control formatting.
• Sort and organize data. Here are the main field properties:
• Perform calculations and summaries. 1. Field Size:
• Modify or delete records (action queries). o Sets maximum characters for Text fields
• Generate reports or serve as record source for (1 to 255).
forms. o Defines numeric data size (e.g., Byte,
Types of Queries: Integer, Long Integer).
1. Select Query: 2. Format:
o Retrieves specific records based on o Controls how data appears (e.g.,
criteria. currency format, date format).
o Displays data in datasheet view. o Example: Short Date, #,###.00.
o Most commonly used query type. 3. Input Mask:
2. Action Queries: o Guides data entry format.
o Perform changes on data: o Example: (000) 000-0000 for phone
▪ Update Query: Modifies data in numbers.
one or more fields. 4. Default Value:
▪ Delete Query: Deletes specific o Sets an automatic value when a new
records. record is added.
▪ Append Query: Adds records to o Example: Default city as "Lahore".
another table. 5. Validation Rule:
▪ Make Table Query: Creates a o Restricts data entry to specific criteria.
new table from selected o Example: >=0 AND <=100 for marks
records. field.
3. Parameter Query: 6. Validation Text:
o Asks the user for input when the query o Error message shown if validation rule is
is run. violated.
o Useful for dynamic searches like "Enter o Example: “Marks must be between 0
a city name." and 100”.
4. Crosstab Query: 7. Required:
o Summarizes data into a grid, showing o Ensures that a field must be filled.
aggregate values. o If set to Yes, Access will not allow blank
o Functions like Sum, Count, Avg are entries.
applied across rows and columns. 8. Allow Zero Length:
5. SQL Query: o Allows entry of an empty string ("")
o Written manually using SQL (Structured instead of Null.
Punjab Board-Part 2-Computer Science by Sir Taha

9. Indexed: setup.
o Improves speed of searching and Relationships are the backbone of relational databases,
sorting. making it easier to maintain accurate and efficient data
o Options: No, Yes (Duplicates OK), Yes structures.
(No Duplicates).
10. Caption:
• Sets a user-friendly label that appears as the
column heading instead of the field name.
These properties enhance the reliability, efficiency, and
Chapter 7: Microsoft
usability of the database.
Access-Forms and Reports
Q5: Define relationships in MS Access. Explain how to Quick Notes:
define them and why they are important. (8)
1. Forms in MS Access
Ans:
A Relationship in MS Access is a logical connection Definition:
between tables, typically through a common field, often A form is a graphical interface in MS Access used to
known as the primary key in one table and foreign key view, add, update, and delete data from tables. It
in another. provides an easier and more user-friendly way to
Types of Relationships: interact with data compared to datasheet view.
1. One-to-One: Purpose of Forms:
Each record in Table A relates to only one
• Make data entry easier and more structured.
record in Table B.
2. One-to-Many: • Control and validate user input.
A single record in Table A can be related to • Provide visual cues using buttons, dropdowns,
many records in Table B (most common). and checkboxes.
3. Many-to-Many: 2. Types of Form Layouts
Requires a junction table; each record in Table A
may relate to many in Table B and vice versa. MS Access provides four major layouts of forms:
Importance of Relationships: 1. Columnar Form
• Eliminate data redundancy. o Displays one record at a time.
• Ensure data consistency and integrity.
o Labels are displayed on the left and
• Enable joined queries to extract data from
data fields (textboxes) on the right.
multiple related tables.
• Support referential integrity to avoid orphan o Suitable for viewing and editing
records. individual records with detail.
Steps to Define Relationships in Access: 2. Tabular Form
1. Open Relationships Window: o Displays multiple records at once.
o Go to the “Database Tools” tab > Click
“Relationships”. o Appears in a table-like format where
2. Add Tables: each row represents a record and each
o Click “Show Table” and add the tables column represents a field.
you want to relate. o Useful for scanning or comparing many
3. Create Relationship: records.
o Drag the primary key from one table to 3. Datasheet Form
the matching foreign key in another.
o Appears similar to a datasheet or Excel
4. Set Referential Integrity:
spreadsheet.
o Check the “Enforce Referential
Integrity” box to ensure related records o Allows entry and viewing of multiple
stay consistent. records like in table datasheet view.
5. Choose Relationship Type: o Preferred when quick, bulk data entry is
o MS Access automatically identifies it needed.
(usually One-to-Many). 4. Justified Form
6. Save the Relationship:
o Click “Create” and save the relationship
Punjab Board-Part 2-Computer Science by Sir Taha

o Displays one record at a time but • Include charts, calculations, and graphics.
spreads fields across multiple rows and • Print clean and organized documents.
columns.
7. Types of Report Layouts
o Fields and labels are arranged side-by-
side for better aesthetics. 1. Columnar Report:
o Each field value appears in its own line
3. Form Controls
(column).
Controls are the elements added to forms to interact
o Ideal for printing one record at a time in
with data.
a readable format.
• Text Box: Used to enter and display data.
2. Tabular Report:
• Label: Provides field names or descriptions.
o Like a table, shows multiple records
• List Box: Shows a list of options. Users can with fields as columns.
select one or more items.
o Suitable for listing multiple items at
• Combo Box: A dropdown list that lets users once (e.g., product lists).
select one value from a list.
3. Justified Report:
• Check Box: Used for Yes/No, True/False type
o Similar to justified form, aligns data in a
data.
structured block format.
• Option Button (Radio Button): Allows the user
to select only one option from a group. 8. Conditional Formatting in Forms and Reports
• Allows the appearance of controls (e.g.,
• Command Button: Executes commands like
"Save", "Next Record", "Close Form" etc. background color, text style) to change based
on a condition.
4. Subform and Main Form (Parent-Child Relationship)
• Example: Marks below 40 are displayed in red,
• A Subform is a form embedded inside another above 80 in green.
form (Main form).
• Enhances readability and highlights important
• Used to display related data from another table. data automatically.
• Commonly used in One-to-Many relationships
(e.g., one customer, many orders).
9. Form vs. Report
• Example: The main form shows customer info;
the subform shows all orders placed by that Feature Form Report
customer.
Enter, edit, and view Display and print
5. Creating a Form Purpose
data data in a format
There are several methods:
Interactive – data can Static – data is
• Form Wizard: Step-by-step guide to create a Interaction
be changed read-only
form by selecting fields, layout, and style.
Output Paper or printable
• AutoForm: Creates a form instantly using all On-screen data entry
Format output
fields from the selected table.
• Design View: Allows full customization and Data Source Tables or queries Tables or queries
advanced form designing. Textboxes, labels, Mainly text and
Controls
6. Report in MS Access buttons, combo box labels
Definition:
A report is an object used to display data in a printed
10. Creating Reports Using Wizard
format. It is usually designed to show summarized and
structured information for decision-making or Steps:
presentation. 1. Choose table or query as data source.
Purpose: 2. Select fields to include.
• Generate formatted outputs from queries or 3. Set grouping levels (optional).
tables.
4. Choose sorting order.
• Use headers, footers, grouping, and sorting.
Punjab Board-Part 2-Computer Science by Sir Taha

5. Select layout and orientation. as:


6. Select a style. (a) Tabular Report
(b) Columnar Report
7. Name the report and finish. (c) Datasheet Report
Reports can also be created from multiple related (d) Justified Report
tables using primary-foreign key relationships.
11. Editing and Formatting Forms and Reports Q7. How many are layout of report?
(a) 2
• Gridlines and Snap to Grid: Help align controls
(b) 3
properly.
(c) 4
• Tab Order: Define the sequence in which (d) 5
controls are selected using the Tab key.
• Resizing Controls: Change control size to fit Q8. A report may be based on:
content. (a) A table but not a query
(b) A query but not a table
• Change Control Type: Convert one type of
(c) Both (a) and (b)
control to another.
(d) None of these
• Form Appearance: Change color, font, and
layout to improve aesthetics. Q9. Which of the following is NOT a function of report?
Important Multiple-Choice (a) Display data
(b) Edit data
Questions (MCQs): (c) Output of database application
Q1. Forms are designed to: (d) Print data
(a) Input data
(b) Manipulate data Q10. A single report can display data from:
(c) Accept data (a) One table
(d) All of above (b) Many tables
(c) Both (a) and (b)
Q2. A form that contains a subform is called: (d) None of these
(a) Form
(b) Main Form Q11. Which type of report lists every field for every
(c) Report record in a single column?
(d) None of these (a) Tabular bar
(b) Summary report
Q3. How many are basic layouts of form in MS Access? (c) Columnar report
(a) 2 (d) All of above
(b) 3
(c) 4 Q12. Which of the following can be previewed on
(d) 5 screen?
(a) Report
Q4. The forms are ____ end of our database in MS- (b) Form
Access? (c) Subform
(a) Back (d) None of these
(b) Front
(c) Both (a) and (b) Q13. Which of the following object is not used to enter
(d) None of these data into database?
(a) Queries
Q5. Which Auto form displays one record at a time? (b) Reports
(a) Tabular (c) Tables
(b) Columnar (d) Forms
(c) Datasheet
(d) Justified Q14. Which form layout is selected to display a single
record at a time?
Q6. A report that provides a column for each field of (a) Tabular
the records in rows under the column header is known (b) Datasheet
Punjab Board-Part 2-Computer Science by Sir Taha

(c) Columnar
Q.No Ans Q.No Ans Q.No Ans Q.No Ans Q.No Ans
(d) None of these

Q15. Which form layout is selected to display multiple Q4 b Q8 c Q12 a Q16 d Q20 c
records at a time?
(a) Justified
(b) Datasheet
(c) Columnar
(d) None of these Important Short Questions (2
marks each):
Q16. A form within another form is called:
Q1. What is a Form in MS Access? (2)
(a) Main form
Ans: A form is a window with visual components used to
(b) Special form
interact with a database. It allows users to enter, edit,
(c) Dialog box
view, and delete records using a graphical interface.
(d) Subform
Q2. What is the use of a Columnar Form? (2)
Ans: A columnar form displays one record at a time. It
Q17. The form which contains the subform is known
shows each field in a separate textbox, along with
as:
labels, making it ideal for detailed viewing and editing.
(a) Main form
Q3. Define a Subform. (2)
(b) Special form
Ans: A subform is a form embedded within a main
(c) Dialog box
(parent) form. It is used to display related data, typically
(d) Child form
from a child table in a one-to-many relationship.
Q18. A subform can be created using: Q4. What is the difference between Form and Report?
(a) Form wizard (2)
(b) Subform wizard Ans: A form is used for data input and editing, while a
(c) Drag and drop method report is used to display and print formatted data for
(d) All of above viewing and analysis.
Q5. What is a Tabular Form? (2)
Q19. What is the function of a Form in MS Access? Ans: A tabular form displays multiple records in a table-
(a) View one record at a time like format. Each row shows one record, and columns
(b) Add new data represent fields.
(c) Change existing data Q6. What is Conditional Formatting? (2)
(d) All of above Ans: Conditional formatting is applied to controls on a
form or report when a specific condition is met, such as
Q20. Which of the following is used to display yes/no highlighting values greater than a threshold.
values? Q7. What is the use of a List Box? (2)
(a) Checkbox Ans: A list box displays a list of items from which the
(b) Option button user can select one or more values. It saves space and
(c) Both (a) and (b) simplifies user input.
(d) None of these Q8. What is a Combo Box in a form? (2)
Ans: A combo box combines a textbox with a drop-
Answer Key Table down list. It allows users to either type a value or select
one from the list.
Q9. What is the function of a Checkbox? (2)
Q.No Ans Q.No Ans Q.No Ans Q.No Ans Q.No Ans
Ans: A checkbox is used for Boolean values (Yes/No,
True/False). Users can check or uncheck it to indicate
Q1 d Q5 b Q9 b Q13 b Q17 a selection.
Q10. What is a Report in MS Access? (2)
Q2 b Q6 a Q10 c Q14 c Q18 d Ans: A report is a database object used to display data
in a formatted layout. It is typically used for printing or
reviewing data summaries.
Q3 c Q7 b Q11 c Q15 b Q19 d
Important Long Questions (8
Punjab Board-Part 2-Computer Science by Sir Taha

marks each): represents a field.


• Similar to datasheet view but with
customization options.
Q1. What is a Form? Explain its uses and advantages.
• Ideal for viewing and comparing data.
(8)
3. Datasheet Form:
Ans:
• Looks like an Excel sheet with rows and
A Form in MS Access is a user-friendly graphical
columns.
interface that allows users to interact with a database
• Each row is a record and each column a field.
without writing SQL commands. It is a window with
• Good for bulk data viewing and editing.
visual components such as text boxes, labels, buttons,
• Fields are displayed with default formatting.
checkboxes, and combo boxes. These components are
4. Justified Form:
known as controls, and they help users input, modify,
• Displays all fields of a record in one or more
and view data easily.
rows.
Uses of Forms:
• Fields are arranged side-by-side with labels.
• Data Entry: Easily enter new records into tables.
• Offers an aesthetic, wide layout.
• Editing Records: Modify existing data directly in
• Suitable for reports and well-formatted data
the form fields.
display.
• Deleting Records: Remove data using form
Each of these layouts can be created using the Form
controls.
Wizard or by customizing in Design View.
• Searching Records: Users can search records
using form filters or navigation.
Q3. How is a form created using the Form Wizard?
• View Data: View one or multiple records in
Explain the step-by-step procedure. (8)
structured layouts like columnar or tabular
Ans:
format.
MS Access provides a Form Wizard to guide users
Advantages of Forms:
through creating a form step-by-step. This method is
1. User-Friendly Interface: Forms simplify complex
quick, especially for beginners.
operations for users with no technical
Steps to create a form using the Form Wizard:
background.
1. Open Database: Launch MS Access and open
2. Efficient Navigation: Forms provide buttons and
the database.
controls to move between records quickly.
2. Select Forms Object: In the navigation pane,
3. Data Validation: Controls like combo boxes and
click on Forms.
input masks ensure correct data entry.
3. Launch Wizard: Click “Create form by using
4. Security: Certain fields can be locked to prevent
wizard”.
unauthorized changes.
4. Choose Table/Query: From the dropdown,
5. Visual Appeal: Forms can be customized with
select the table or query whose data you want
styles, images, and colors.
in the form.
6. Flexible Layouts: Various layouts like columnar,
5. Select Fields: Move desired fields from
tabular, datasheet, and justified can be used
“Available Fields” to “Selected Fields” using the
depending on the need.
“>” or “>>” button.
6. Choose Layout: Choose layout type: Columnar,
Q2. Describe different types of form layouts in MS
Tabular, Datasheet, or Justified.
Access. (8)
7. Select Style: Choose a visual theme or style for
Ans:
the form.
MS Access offers various form layouts to suit different
8. Name the Form: Enter a name for the form,
data input and viewing requirements. These layouts
e.g., “StudentForm”.
determine how data appears to the user.
9. Finish: Click “Finish”. The form will be generated
1. Columnar Form:
and displayed for use.
• Displays one record at a time.
The form can then be further edited in Design View to
• Each field appears on a new line with a label.
customize controls, add validation, or change
• Ideal for detailed data entry.
appearance.
• Useful when a record has many fields.
2. Tabular Form:
Q4. What is a Report? Explain the different types of
• Displays multiple records simultaneously in a
reports and their uses. (8)
table format.
Ans:
• Each row represents one record; each column
Punjab Board-Part 2-Computer Science by Sir Taha

A Report in MS Access is a formatted output of data 3. Activate Control Wizard: Ensure the “Control
retrieved from one or more tables or queries. Reports Wizards” button is pressed.
are primarily used for printing, summarizing, and 4. Insert Control:
presenting data in a readable layout. o Click the List Box or Combo Box control
Types of Reports in MS Access: in toolbox.
1. Columnar Report: o Drag on the form to draw the control.
• Displays one record at a time. 5. Wizard Launches:
• Each field is shown in a separate row. o Choose whether the values are typed
• Used when detailed record information is manually or sourced from a
required. table/query.
2. Tabular Report: o Select fields if pulling data from a table.
• Presents multiple records in a table format. 6. Configure Options:
• Each row represents a record; each column a o Set field widths.
field. o Decide whether the selection will be
• Ideal for summary data and comparison. stored in a field.
3. Summary Report: 7. Finish Setup: Name the control and click Finish.
• Shows grouped or summarized data using Use Case:
aggregate functions. • Use a List Box for gender selection, e.g.,
• Good for statistical data like totals and Male/Female.
averages. • Use a Combo Box to search for and select a
4. Justified Report: student name from hundreds of entries.
• Displays data in a paragraph-like layout with
labels and values together.
• Offers an organized and professional
presentation.
Uses of Reports:
• Printing invoices, receipts, lists, and summaries. Chapter 8: Getting Started
• Displaying filtered data (e.g., top customers).
• Presenting charts and grouped data. With C
• Exporting data to PDF for formal sharing.
Reports cannot be used to edit data but are essential Important Multiple-Choice
for viewing, printing, and summarizing it. Questions (MCQs):
Q5. What are List Box and Combo Box controls? How Q1. Who developed the C language?
can they be added to a form? (8) (a) Ken Thompson
Ans: (b) Dennis Ritchie
List Box and Combo Box are controls used in MS Access (c) Bill Gates
forms to let users select values from a list, improving (d) Charles Babbage
data entry accuracy and user experience.
List Box:
Q2. The C programming language was developed in:
• Displays a vertical list of items.
(a) 1969
• Users can select one or more items.
(b) 1972
• All items are visible (if space allows).
(c) 1975
• Scrollbar appears for long lists.
(d) 1980
Combo Box:
• Combines a textbox and a dropdown list.
Q3. The standard version of C language is known as:
• Users can select from the list or type a custom
(a) Turbo C
value.
(b) Borland C
• Saves space and prevents errors by offering
(c) ANSI C
valid choices.
(d) AT&T C
Steps to Add a List or Combo Box to a Form:
1. Open Form in Design View.
Q4. A well-defined set of instructions given to a
2. Enable Toolbox: Click View > Toolbox if not
computer is called:
already visible.
Punjab Board-Part 2-Computer Science by Sir Taha

(a) Algorithm (c) Ctrl + F9


(b) Command (d) Alt + F9
(c) Program
(d) Syntax Q13. A single module implementing the entire logic is
found in:
Q5. What is the extension of a C source file? (a) Structured programming
(a) .cpp (b) Modular programming
(b) .c (c) Object-oriented programming
(c) .exe (d) Unstructured programming
(d) .obj
Q14. A language translator for Assembly language is
Q6. A program written in C language is called: called:
(a) Executable code (a) Compiler
(b) Source code (b) Interpreter
(c) Object code (c) Debugger
(d) Machine code (d) Assembler

Q7. Which program is responsible for converting Q15. High-level languages are:
source code to object code? (a) Difficult to debug
(a) Linker (b) Close to machine language
(b) Loader (c) Machine independent
(c) Compiler (d) None
(d) Interpreter
Q16. The braces { } used in C program are called:
Q8. What does a linker produce? (a) Terminators
(a) Source file (b) Delimiters
(b) Executable file (c) Indicators
(c) Header file (d) Markers
(d) None
Q17. The symbol used to start a preprocessor directive
Q9. The process of finding and fixing errors is called: is:
(a) Compiling (a) %
(b) Debugging (b) $
(c) Linking (c) #
(d) Saving (d) &

Q10. What kind of error occurs due to incorrect use of Q18. The file that contains built-in functions like printf
language rules? is:
(a) Runtime error (a) conio.h
(b) Logical error (b) stdio.h
(c) Syntax error (c) stdlib.h
(d) Execution error (d) string.h

Q11. Which error occurs during the program's Q19. Which type of error is the most difficult to
execution? detect?
(a) Syntax error (a) Syntax error
(b) Runtime error (b) Runtime error
(c) Logical error (c) Logical error
(d) Compilation error (d) Link error

Q12. Which key combination is used to run a C Q20. The instruction #define PI 3.14 is an example of:
program in Turbo C++? (a) Predefined variable
(a) Ctrl + F5 (b) Macro definition
(b) Alt + F5
Punjab Board-Part 2-Computer Science by Sir Taha

(c) Constant definition Ans: A compiler translates the entire source code of a
(d) Arithmetic operation program into machine code (object code) and detects
syntax errors.

Answer Key Table Q5. Define debugging. (2)


Q# Answer Ans: Debugging is the process of finding and removing
errors or bugs from a program to ensure it functions
Q1 b correctly.
Q2 b
Q3 c Q6. What is the main function in C? (2)
Ans: The main() function is the entry point of a C
Q4 c program where the execution starts. All program logic
Q5 b begins from here.
Q6 b
Q7. What are delimiters in C language? (2)
Q7 c Ans: Delimiters are braces {} used in C to indicate the
Q8 b beginning and end of a block of code or function body.
Q9 b
Q8. What is a logical error? (2)
Q10 c Ans: A logical error is an error in a program's logic that
Q11 b causes incorrect output. It doesn't stop the program
Q12 c from running, making it difficult to detect.
Q13 d Q9. What is the use of the #include directive? (2)
Q14 d Ans: The #include directive is a preprocessor command
Q15 c used to include the contents of a header file in a
program, such as standard functions like printf().
Q16 b
Q17 c Q10. What is machine independence in high-level
Q18 b languages? (2)
Ans: Machine independence means that programs
Q19 c
written in high-level languages can run on different
Q20 b types of computers with minimal or no changes.

Important Short Questions (2 Important Long Questions (8


marks each): marks each):
Q1. What is a computer program? (2)
Ans: A computer program is a well-defined set of Q1. Describe the history of the C language in detail. (8)
instructions written in a programming language that Ans:
directs the computer to perform a specific task. The C programming language was developed by Dennis
Ritchie in 1972 at AT&T Bell Laboratories. It evolved
Q2. Who developed the C language and when? (2) from an earlier language called B, which itself was a
Ans: The C language was developed by Dennis Ritchie in simplification of BCPL (Basic Combined Programming
1972 at AT&T Bell Laboratories. Language). The B language was created by Ken
Thompson around 1969–1970.
Q3. What is the difference between source code and
object code? (2) C was created specifically to write system software,
Ans: Source code is the original code written in a high- especially the Unix operating system, which was initially
level language, while object code is the machine-level written in assembly language. The development of C
code generated after compiling the source code. made Unix more portable and efficient since C programs
can be compiled on different machines.
Q4. What is the purpose of the compiler? (2)
Punjab Board-Part 2-Computer Science by Sir Taha

The early version of C was known as K&R C, named after programming errors in C. (8)
Brian Kernighan and Dennis Ritchie, who co-authored Ans:
the first book on C titled The C Programming Language. A bug is any kind of error in a program that causes it to
Later, in 1989, a standard version of C was created by behave unexpectedly or incorrectly. The process of
the American National Standards Institute (ANSI), identifying and removing these errors is called
known as ANSI C, to ensure consistency across debugging.
compilers. This version included several improvements
and extensions. There are three main types of programming errors in C:
1. Syntax Errors:
Thus, C became one of the most influential o These occur when the rules of the C
programming languages, laying the foundation for many language are violated.
modern languages such as C++, C#, Java, and others. o Detected by the compiler at compile
Q2. Explain the steps to create, compile, link, and time.
execute a C program using Turbo C++. (8) o Examples:
Ans: ▪ Missing semicolon (;)
To develop a C program using Turbo C++, several steps ▪ Misspelled keywords
are followed: ▪ Mismatched braces { }
1. Creating the Program: o Syntax errors prevent compilation until
o Launch Turbo C++ IDE. fixed.
o Select File > New to open a new edit 2. Runtime Errors:
window. o These occur during the execution of the
o Type your C program using appropriate program.
syntax. o They cause the program to crash or halt
2. Saving the Program: unexpectedly.
o Press F2 or go to File > Save. o Examples:
o A dialog box appears to enter the file ▪ Dividing by zero
name and location. ▪ Opening a non-existing file
o The program is saved with a .c ▪ Using uninitialized variables
extension. 3. Logical Errors:
3. Compiling the Program: o The most difficult to detect.
o Press Alt + F9 or select Compile > o The program runs and compiles
Compile. successfully but produces incorrect
o The compiler checks for syntax errors results.
and translates the source code into o Caused by mistakes in the program’s
object code with a .obj extension. logic or algorithm.
4. Linking the Program: o Examples:
o Linking is automatically performed after ▪ Incorrect formula used for
successful compilation. calculation
o It combines object code with library ▪ Using wrong loop conditions
files to produce an executable file
(.exe). Each of these errors requires a different approach for
o The linker does this task. detection and fixing. Logical errors are especially hard
5. Executing the Program: to find because they are not flagged by the compiler or
o Press Ctrl + F9 or select Run > Run to during execution but lead to incorrect output.
execute the program.
o This invokes the loader, which loads the Q4. What are programming languages? Explain low-
.exe file into memory. level and high-level languages with examples. (8)
o To see the output, press Alt + F5 or Ans:
select Window > User Screen. Programming languages are formal languages used to
Each of these steps is essential to prepare a program for communicate instructions to a computer. These
execution, turning human-readable code into machine- languages are used to develop programs, websites,
understandable instructions. applications, and more. There are two main categories:
1. Low-Level Languages:
Q3. What is a bug? Explain the three main types of o Closer to machine language.
Punjab Board-Part 2-Computer Science by Sir Taha

o Difficult to write and understand. 2. Interpreter:


o Provide faster execution and greater o Translates and executes one line at a
control over hardware. time.
o Two types: o Slower than a compiler.
▪ Machine Language: Uses binary o Doesn’t create an executable file.
(0s and 1s). Example: 1001101 o Used for scripting languages like
1010010 Python, Visual Basic.
▪ Assembly Language: Uses o Example: Python interpreter
mnemonics like MOV, ADD.
Requires an assembler. 3. Assembler:
o Example: o Converts assembly language into
▪ Assembly: MOV A, 5 machine language.
2. High-Level Languages: o Uses mnemonics (e.g., MOV, ADD) and
o Closer to human languages. translates them into binary.
o Easier to write, read, and debug. o Needed for low-level system
o Must be translated into machine code programming.
using a compiler or interpreter. o Example: MASM (Microsoft Assembler)
o Examples:
▪ C: Used for system software Comparison:
▪ C++: Supports object-oriented
programming Output Example
Type Translates Speed
▪ FORTRAN: Mathematical File Languages
applications
▪ COBOL: Business applications Whole
▪ Java: Strong in network
Compiler Fast .exe C, C++
code
programming
Line-by-
Advantages of High-Level Languages: Interpreter Slow None Python, VB
line
• Machine independent
• Easy to learn
• Provide portability
Machine
Assembler Assembly Fast Assembly
• Easier to debug and maintain
code

High-level languages have revolutionized software Language translators are essential to bridge the gap
development by making it more accessible and efficient. between human-readable code and machine-
executable instructions.
Q5. What are language processors or translators?
Explain types of translators with examples. (8)
Ans:
Language processors, also called translators, are Chapter 9: Elements of C
software tools that convert programs written in high-
level or assembly language into machine language Important Multiple-Choice
(object code) that a computer can understand. Questions (MCQs):
There are three main types of language processors: Q1. What are the names used to represent variables,
1. Compiler: constants, types, functions, and labels in a C program
o Translates the entire source code at called?
once into machine code. (a) Procedure
o Generates an object file (.obj) and (b) Identifier
executable file (.exe) after linking. (c) Operator
o Detects syntax errors during (d) Keyword
compilation.
o Used by languages like C, C++, COBOL. Q2. Which identifiers have predefined meanings in C?
o Example: Turbo C++ compiler (a) User-defined identifiers
Punjab Board-Part 2-Computer Science by Sir Taha

(b) Function identifiers (a) float


(c) Standard identifiers (b) char
(d) None of these (c) double
(d) int
Q3. Which of the following is a standard identifier in C?
(a) rollno Q12. C language is considered a strongly typed
(b) marks language because:
(c) printf (a) Every program must be compiled before execution
(d) none (b) Each variable must be declared before use
(c) It has only a few data types
Q4. The number of keywords in C language is: (d) It supports operator overloading
(a) 32
(b) 31 Q13. Comments in C language are used to:
(c) 62 (a) Increase speed
(d) 45 (b) Increase readability
(c) Decrease memory usage
Q5. The value of a variable of type int ranges from: (d) Execute logic
(a) 0 to 32767
(b) -215 to 215-1 Q14. Multi-line comments in C begin with:
(c) -32768 to 32767 (a) //
(d) 0 to 65535 (b) /**
(c) /*
Q6. Which of the following is a valid character (d) #
constant?
(a) “a” Q15. What is the output of printf("%d", 9 % 4);?
(b) ‘6’ (a) 1
(c) “c” (b) 2
(d) 8 (c) 4
(d) 0
Q7. The symbol used for modulus operation in C is:
(a) / Q16. The assignment operator in C is:
(b) % (a) ==
(c) \ (b) :=
(d) # (c) =
(d) =>
Q8. What does the logical NOT operator (!) do?
(a) Assigns a value Q17. Which of the following is NOT a valid identifier?
(b) Compares values (a) _temp
(c) Reverses the result of condition (b) total_1
(d) None of these (c) double
(d) marks2
Q9. Which data type in C has the highest precision?
(a) float Q18. The statement a += 5; is an example of:
(b) double (a) Arithmetic assignment
(c) long double (b) Compound assignment
(d) char (c) Conditional assignment
(d) Chained assignment
Q10. Which of the following is a valid variable name?
(a) 1score Q19. The float data type in C occupies how many bytes
(b) @marks of memory?
(c) my_Marks (a) 2
(d) total% (b) 4
(c) 8
Q11. Which data type is used to store a single (d) 1
character?
Punjab Board-Part 2-Computer Science by Sir Taha

Q20. The maximum length of a character constant is: in single quotes. Example: 'A', '5'.
(a) 1 character
(b) 2 characters Q7. What are comments in C language? Name its
(c) 4 characters types. (2)
(d) 8 characters Ans: Comments increase readability and are ignored by
the compiler. Types: Single-line (//) and Multi-line
(/*...*/).

Q8. What is the purpose of logical operators? (2)


Ans: Logical operators are used to create compound
conditions. Examples: && (AND), || (OR), ! (NOT).

ANSWER KEY FOR MCQs Q9. What is meant by increment and decrement
operators? (2)
Q# Ans Q# Ans Q# Ans Q# Ans Q# Ans Ans: ++ increases a value by one, -- decreases it by one.
Used as prefix or postfix (e.g., ++x, x--).
1 b 2 c 3 c 4 a 5 c
Q10. Why is C called a strongly typed language? (2)
Ans: Because C requires all variables to be declared
6 b 7 b 8 c 9 c 10 c
before use, making it type-safe and structured.

11 b 12 b 13 b 14 c 15 a

16 c 17 c 18 b 19 b 20 a Important Long Questions (8


marks each):
Important Short Questions (2 Q1. Explain different data types used in C language. (8)
marks each): Ans:
Q1. What is an identifier? (2) In C programming, data types define the nature of data
Ans: An identifier is the name used to represent that can be stored in a variable. C provides a wide range
variables, functions, constants, and arrays in a C of built-in (standard) data types to accommodate
program. For example, marks, sum, and area. different kinds of values including integers, real
numbers, characters, etc. Choosing the correct data
Q2. What is a keyword in C? Give two examples. (2) type is essential for efficient memory usage and
Ans: Keywords are reserved words in C that have special accurate computations.
meanings. They cannot be used as variable names. 1. Integer Data Types
Examples: int, float. Used to store whole numbers (positive or negative)
without any fractional part.
Q3. What is a variable declaration? (2) • int:
Ans: Declaring a variable means telling the compiler its o Occupies 2 bytes (16 bits) in memory on
name and data type. Example: int marks; declares an most systems.
integer variable named marks. o Range: –32,768 to 32,767.
o Example: int age = 25;
Q4. What is the difference between = and == in C? (2) • short int:
Ans: = is the assignment operator and is used to assign o Also occupies 2 bytes; range is similar to
values. == is the equality operator and is used to int.
compare two values. o Mostly used when memory
conservation is important.
Q5. Define a constant with the help of define directive. • long int:
(2) o Occupies 4 bytes (32 bits).
Ans: #define PI 3.142857 defines a constant PI. The o Range: –2,147,483,648 to
value of PI will not change throughout the program. 2,147,483,647.
o Example: long salary = 500000;
Q6. What is a character constant? Give example. (2) • unsigned int:
Ans: A character constant is a single character enclosed o Only stores positive values.
Punjab Board-Part 2-Computer Science by Sir Taha

o Range: 0 to 65,535 (2 bytes). • C is case-sensitive, so Total and total are


2. Floating Point Data Types considered different identifiers
Used to represent real numbers (numbers with Types of Identifiers:
fractional parts). 1. Standard Identifiers:
• float: o These are predefined in the C library
o Occupies 4 bytes. and have specific meanings.
o Precision up to 6 decimal places. o Example: printf, scanf, main
o Example: float price = 56.78; o Usage: printf("Hello"); is used for
• double: output.
o Occupies 8 bytes. 2. User-defined Identifiers:
o Precision up to 15 decimal places. o These are defined by the programmer
o Example: double weight = to store data or logic.
70.123456789123456; o Examples: sum, marks, totalPrice,
• long double: rollNumber
o Occupies 10 bytes. o Usage: int marks = 85;
o Precision up to 19 decimal places. Example:
o Example: long double pi = int totalMarks = 95;
3.1415926535897932384; float averageScore;
3. Character Data Type char grade = 'A';
• char: Here, totalMarks, averageScore, and grade are user-
o Stores a single character like ‘A’, ‘9’, ‘$’. defined identifiers.
o Occupies 1 byte. Rules for Valid Identifiers:
o Internally stored as ASCII values. • Valid: marks, _temp, student1
o Example: char grade = 'A'; • Invalid: 2score, @name, float (reserved
Summary Table: keyword)
Size Identifiers improve program readability and make the
Data Type Range/Precision code easier to understand and maintain.
(Bytes)
Q3. What are arithmetic and relational operators in C?
int 2 -32,768 to 32,767
Explain with examples. (8)
Precision up to 6 decimal Ans:
float 4
places In C, operators are symbols that perform operations on
Precision up to 15 decimal variables and values. The two most commonly used
double 8 types are arithmetic operators and relational
places
long Precision up to 19 decimal operators.
10 1. Arithmetic Operators
double places
Used for mathematical operations.
char 1 Stores single ASCII character
Operator Description Example Result
These data types help the compiler determine how
+ Addition a+b 10 + 2 = 12
much memory to allocate and which operations can be
performed on variables. - Subtraction a-b 10 - 2 = 8
Q2. What are identifiers? Explain their types with * Multiplication a * b 10 * 2 = 20
examples. (8)
/ Division a/b 10 / 2 = 5
Ans:
In C programming, identifiers are the names used to % Modulus a%b 10 % 3 = 1
identify variables, functions, arrays, structures, etc. They Example Program:
are user-defined names used to uniquely represent int a = 10, b = 3;
elements in a program. printf("Sum: %d\n", a + b); // Output: 13
Characteristics of Identifiers: 2. Relational Operators
• They must begin with a letter (A-Z or a-z) or an Used to compare two values or expressions. Returns
underscore (_) either 1 (true) or 0 (false).
• The rest of the identifier can consist of letters, Operator Description Example Result
digits (0-9), and underscores == Equal to a == b false
• Cannot use keywords (e.g., int, float) as
identifiers != Not equal to a != b true
Punjab Board-Part 2-Computer Science by Sir Taha

Operator Description Example Result Assignment Operator in C


• The assignment operator (=) is used to store a
< Less than a<b false
value or a result in a variable.
> Greater than a>b true Syntax:
<= Less than or equal a <= b true variable = expression;
>= Greater than or equal a >= b false Example:
int x;
Usage in Conditions:
x = 10; // assigns 10 to x
if (age >= 18) {
printf("Eligible to vote.");
Compound Assignment Operators
}
• Used to combine arithmetic and assignment in
These operators are essential for implementing control
one step:
structures like if, while, and for.
o +=, -=, *=, /=, %=
Q4. Differentiate between declaring and defining a
Example:
variable. Write naming rules. (8)
int a = 5;
Ans:
a += 3; // same as a = a + 3
Declaration:
printf("%d", a); // Output: 8
• A variable is declared when its type and name
Comments in C
are specified to the compiler.
Purpose:
• It informs the compiler about the variable.
• To increase code readability
• Example: int marks; → Here, marks is declared.
• Helps programmers understand logic
Definition:
• Ignored by compiler
• Definition of a variable means allocating
1. Single-line Comments
memory for it.
• Begin with //
• In most C programs, declaration and definition
• Used for short explanations
occur together.
Example:
• Example: int marks = 90; is both declaration and
// This is a single-line comment
definition.
int a = 10; // declare variable a
Key Differences:
2. Multi-line Comments
Declaration Definition • Enclosed within /* ... */
Allocates memory to store • Used for block explanations
Introduces variable name
value Example:
May not assign value Often assigns initial value /* This program calculates
the area of a rectangle */
Can be multiple int area = length * width;
Only one definition allowed
declarations
Conclusion:
Naming Rules for Variables (Identifiers): Using assignment operators simplifies code logic, and
1. Must begin with a letter or underscore (_) comments make the program easier to understand and
2. Can contain letters, digits, and underscores maintain, especially in large projects.
3. No special symbols (e.g., @, #, %)
4. Cannot be a keyword (e.g., int, void)
5. Case-sensitive (Total ≠ total) Chapter 10: Input / Output
6. No white spaces

Examples:
• Valid: marks, _avg, rollNo, total1 Important Multiple-Choice
• Invalid: 1num, float, student name, #value
Correct naming ensures the program is readable, error- Questions (MCQs):
free, and easy to maintain. Q1. The function printf and scanf can be accessed by
including library __________.
Q5. Explain assignment operator and types of (a) conio.h
comments with examples. (8) (b) stdio.h
Ans: (c) math.h
Punjab Board-Part 2-Computer Science by Sir Taha

(d) string.h character?


(a) %s
Q2. Which of the following function is used to input (b) %c
data in the program? (c) %f
(a) printf (d) %i
(b) scanf
(c) clrscr Q11. The width specifier %6.2f will display how many
(d) putc digits in total (including decimals)?
(a) 2
Q3. Which format specifier is used for integer data (b) 6
type? (c) 4
(a) %f (d) 8
(b) %c
(c) %d Q12. Which symbol is used to start a format specifier?
(d) %x (a) &
(b) %
Q4. The escape sequence \n is used for __________. (c) /
(a) new line (d) #
(b) tab
(c) carriage return Q13. What is the ASCII code for Escape key?
(d) beep (a) 32
(b) 27
Q5. The function getch() is defined in which header (c) 8
file? (d) 65
(a) stdio.h
(b) string.h Q14. Which escape sequence is used to delete the
(c) math.h previous character?
(d) conio.h (a) \n
(b) \r
Q6. Which symbol is used before a variable in scanf()? (c) \f
(a) % (d) \b
(b) #
(c) & Q15. Which of the following functions does not require
(d) $ pressing the ENTER key?
(a) scanf()
Q7. Which of the following is the correct format (b) gets()
specifier for float? (c) getch()
(a) %d (d) puts()
(b) %f
(c) %c Q16. The output screen contains how many columns?
(d) %s (a) 100
(b) 40
Q8. The escape sequence \t represents a __________. (c) 80
(a) space (d) 120
(b) newline
(c) tab Q17. Which format specifier is used for strings?
(d) beep (a) %d
(b) %c
Q9. What does getche() do? (c) %s
(a) Takes character input and echoes (d) %f
(b) Takes string input
(c) Reads integer input Q18. Escape sequences always start with __________.
(d) Clears the screen (a) /
(b) #
Q10. Which format specifier is used to display a (c) \
Punjab Board-Part 2-Computer Science by Sir Taha

(d) % Q3. What is a format specifier? (2)


Ans: Format specifiers tell the compiler how to interpret
Q19. Which function is used for formatted output? and display input or output data. Example: %d for
(a) getch() integers, %f for floats.
(b) scanf()
(c) printf() Q4. What is field width in C? (2)
(d) puts() Ans: Field width specifies how many columns (spaces)
to use when displaying a value using a format specifier
Q20. The general syntax of scanf() includes in printf().
__________.
(a) Format string only Q5. What does the \n escape sequence do? (2)
(b) Only variable name Ans: \n moves the cursor to a new line in the output
(c) Format string and variable with & display.
(d) Keyword only
Q6. What is the difference between getch() and
ANSWER KEY: getche()? (2)
1. b Ans: getch() reads a character without displaying it.
getche() reads and displays the character immediately.
2. b
3. c Q7. Why is & used in scanf()? (2)
4. a Ans: & is the address operator. It gives the address of
5. d the variable where the user input will be stored.
6. c
Q8. List any four format specifiers in C. (2)
7. b Ans: %d for int, %f for float, %c for char, %s for string.
8. c
9. a Q9. What is an escape sequence in C? (2)
10. b Ans: Escape sequences are special character codes
starting with \ that change the behavior of output.
11. b
Example: \n, \t.
12. b
13. b Q10. Write the output: printf("Hello\tWorld\n"); (2)
14. d Ans:
15. c Hello World
(The output appears on a new line after \n.)
16. c
17. c
18. c
19. c IMPORTANT LONG QUESTIONS
20. c
WITH ANSWERS (8 marks each)
Q1. Explain printf() function and its usage with
IMPORTANT SHORT QUESTIONS examples. (8)
Ans:
WITH ANSWERS (2 marks each) printf() is a built-in function defined in stdio.h used to
output data to the screen.
Q1. What is the purpose of printf() function? (2)
It uses format specifiers (e.g., %d, %f, %c) and allows
Ans: printf() is used to display formatted output to the
combining text with variable output.
screen. It is defined in stdio.h and uses format specifiers
to control output format. Syntax:
Q2. What is scanf() used for in C? (2) printf("format string", variable1, variable2, ...);
Ans: scanf() is used to accept input from the user and
store it in specified variables using format specifiers and Example:
address operators (&).
Punjab Board-Part 2-Computer Science by Sir Taha

int a = 5, b = 10; Common Specifiers:


• %d → integer
printf("Sum is %d", a + b); • %f → float
• %c → char
Output: • %s → string
Sum is 15 • %u → unsigned int
Q4. What are escape sequences? Explain five types
Key Features: with examples. (8)
Ans:
• Supports various data types via specifiers
Escape sequences are special characters used with a
backslash to perform specific formatting in output.
• Enables formatted alignment (field width)
Examples:
• Allows escape sequences (\n, \t, etc.) 1. \n – New line
printf("Line1\nLine2");
• Can output multiple values in one line 2. \t – Tab space
printf("Name\tMarks");
Q2. What is scanf() function? Explain its syntax and 3. \\ – Prints backslash
role of &. (8) printf("C:\\Program Files");
Ans: 4. \" – Double quote
scanf() is used to receive input from the user in C. It printf("\"Hello\"");
reads values from the keyboard and stores them in 5. \b – Backspace
variables. printf("AB\bC"); // prints AC
Q5. Differentiate between getch() and getche() with
Syntax: example. (8)
Ans:
scanf("format string", &var1, &var2, ...); Both are character input functions from <conio.h> that
do not require pressing ENTER after input.
Why use &? Feature getch() getche()
The ampersand & provides the memory address of the
variable so scanf() knows where to store the input. Input Does not display Displays typed
Display character character
Example: For secure input (e.g., For visible input
Usage
passwords) without newline
int age;
Return Returns a character Returns a character
scanf("%d", &age); Type (char) (char)
Example:
Input: char c1 = getch(); // user types 'A', nothing shows
18 char c2 = getche(); // user types 'B', B is displayed
Output: Output:
age will now contain 18. Only 'B' is visible.

Q3. Explain format specifiers and field width with


examples. (8)
Ans:
Format specifiers define the type and format of data.
Examples: %d (int), %f (float), %c (char)
Field Width:
Specifies the minimum space for displaying output.
Example: Chapter 11: Decision
int num = 45;
printf("%5d", num); // Output: □□□45 Constructs
Floating-point format:
float pi = 3.14159;
printf("%7.2f", pi); // Output: □□3.14
Punjab Board-Part 2-Computer Science by Sir Taha

Q9. The conditional operator is also called:


Important Multiple-Choice (a) Unary
Questions (MCQs): (b) Binary
Q1. __________ structures control the flow of (c) Ternary
execution in a program. (d) Compound
(a) Loop
(b) Sequence Q10. If condition in if statement is false, it evaluates to:
(c) Selection (a) 1
(d) Control (b) 0
Q2. Which of the following is not a control structure? (c) -1
(a) Loop (d) NULL
(b) Sequence
(c) Array Q11. In switch, each case ends with the __________
(d) Selection keyword.
(a) stop
Q3. In __________ structure, instructions are executed (b) finish
in the same order as they appear. (c) break
(a) Selection (d) end
(b) Sequence
(c) Loop Q12. Conditional operator takes __________ operands.
(d) Condition (a) 1
(b) 2
Q4. A compound statement is enclosed in __________. (c) 3
(a) Parentheses (d) 4
(b) Quotes
(c) Semicolon Q13. Which of the following is an alternative to switch?
(d) Braces (a) if-else
(b) loop
Q5. In C, there are __________ basic selection (c) sequence
statements. (d) goto
(a) 2
(b) 3 Q14. Which statement is useful when checking many
(c) 4 alternatives?
(d) 5 (a) Nested loop
(b) if-else
Q6. Which statement allows two-way decision making (c) if-else if
in C? (d) do-while
(a) Switch
(b) Loop Q15. Which of the following is a correct syntax of
(c) if-else conditional operator?
(d) Goto (a) ? condition : action
(b) condition ? true : false
Q7. Nested if means: (c) if ? then : else
(a) if inside else (d) condition : ? true false
(b) else inside if
(c) if inside if Q16. A condition that always evaluates to false will
(d) if outside loop result in value:
(a) 1
Q8. The switch statement evaluates: (b) 0
(a) Condition (c) NULL
(b) Expression (d) Undefined
(c) Loop
(d) Variable only Q17. The default label in switch is used when:
(a) No case matches
Punjab Board-Part 2-Computer Science by Sir Taha

(b) All cases match Q6. Write the syntax of the conditional operator. (2)
(c) Condition is false Ans: Syntax: condition ? true-case-statement : false-
(d) Break is not needed case-statement;

Q18. The logical operators in C include: Q7. What is a compound statement? (2)
(a) ++, -- Ans: A compound statement is a group of statements
(b) >, < enclosed in braces {} that are executed together.
(c) &&, ||, !
(d) ==, != Q8. How does the switch statement differ from if-else?
(2)
Q19. The keyword used to test multiple conditions Ans: switch is used for comparing a single variable
sequentially is: against many constant values, while if-else can use
(a) if ranges and conditions.
(b) switch
(c) else Q9. What are the three logical operators in C? (2)
(d) else if Ans: Logical AND (&&), OR (||), and NOT (!).

Q10. What happens if break is omitted in a switch? (2)


Q20. A condition is an expression that is either:
Ans: Without break, control falls through to the next
(a) true or wrong
case, executing all subsequent case statements.
(b) yes or no
(c) true or false
(d) correct or incorrect Most Important Long Questions
with Answers (8 marks each)
Answer Key for MCQs
Q1. Explain different types of control structures in C.
1-d 2-c 3-b 4-d 5-a 6-c 7-c 8-b 9-c 10-b
(8)
11-c 12-c 13-a 14-c 15-b 16-b 17-a 18-c 19-
Ans:
d 20-c
C programming supports three main control structures:
1. Sequence Structure:
Most Important Short Questions Instructions are executed one after another in
the order in which they are written.
with Answers (2 marks each) Example:
int x = 5;
Q1. What is a control structure in C? (2)
x = x + 2;
Ans: A control structure in C is used to control the flow
printf("%d", x);
of execution in a program. It includes sequence,
Output: 7
selection, and repetition (loop) structures.
2. Selection Structure:
Q2. What is an if-else statement? (2) Allows branching based on conditions. Includes:
Ans: It is a two-way decision-making statement. If the o if
condition is true, the 'if' block executes; otherwise, the o if-else
'else' block executes. o if-else-if
o switch
Q3. Define nested if statement. (2) o conditional operator (?:)
Ans: A nested if is an if statement inside another if. It 3. Repetition (Looping) Structure:
allows multiple conditions to be checked in a Repeats a block of code. Includes:
hierarchical manner. o for loop
o while loop
Q4. What is the use of break in switch statement? (2) o do-while loop
Ans: The break statement terminates a case in switch These structures allow flexible and efficient control over
and prevents fall-through to the next case. program execution flow.
Q2. Explain the switch statement in detail with syntax
Q5. What is the default case in switch? (2) and example. (8)
Ans: The default case executes when no other case in Ans:
the switch matches the expression. The switch statement is used when a variable or
Punjab Board-Part 2-Computer Science by Sir Taha

expression needs to be compared with multiple The conditional operator is a shorthand for if-else. It
constant values. It avoids complex nested if-else uses ? : and requires three operands.
statements. Syntax:
Syntax: condition ? true_expression : false_expression;
switch(expression) { Example using conditional operator:
case value1: int a = 10, b = 20;
statements; printf("%d is greater", (a > b) ? a : b);
break; Output: 20 is greater
case value2: Comparison with if-else:
statements; if(a > b)
break; printf("%d is greater", a);
... else
default: printf("%d is greater", b);
statements; • Both achieve the same result.
} • The conditional operator is more concise but
Example: less readable for complex logic.
int day = 2;
switch(day) { Q5. Write a program using if-else if ladder to display
case 1: printf("Monday"); break; grade based on percentage. (8)
case 2: printf("Tuesday"); break; Ans:
default: printf("Invalid day"); #include <stdio.h>
} void main() {
Output: Tuesday float marks, percent;
• Note: Without break, control will fall through to printf("Enter obtained marks (out of 1100): ");
the next case. scanf("%f", &marks);
• default is optional but useful for unmatched percent = (marks / 1100) * 100;
cases.
if(percent >= 80)
Q3. Describe nested if statement with example and printf("Grade: A+");
explain its use. (8) else if(percent >= 70)
Ans: printf("Grade: A");
A nested if is an if statement placed inside another if. It else if(percent >= 60)
is used when multiple dependent conditions need to be printf("Grade: B");
evaluated. else if(percent >= 50)
Syntax: printf("Grade: C");
if(condition1) { else if(percent >= 40)
if(condition2) { printf("Grade: D");
statements; else if(percent >= 33)
} printf("Grade: E");
} else
Example: printf("Grade: F");
int age = 18, score = 75; }
if(age >= 18) { Output (example):
if(score >= 60) { If user enters 720 → Grade: A
printf("Eligible for admission."); This example demonstrates the use of multiple if-else if
} statements to evaluate ranges.
}
Output: Eligible for admission.
Nested if is useful for layered decision making, but
overuse may reduce code readability.

Q4. What is conditional operator in C? Compare it with Chapter 12: Loop Constructs
if-else using example. (8)
Ans:
Punjab Board-Part 2-Computer Science by Sir Taha

Quick Notes: (b) Infinite loop


(c) Nested loop
(d) Continuous loop
1. Loop in C Language
A loop allows executing a block of code multiple times
Q3. Which loop always executes at least once?
depending on a condition. There are three main types:
(a) while
(b) do-while
• while loop – condition checked before
(c) for
execution.
(d) All of these
• do-while loop – condition checked after
execution.
Q4. What is one complete execution of a loop called?
• for loop – typically used when number of
(a) Cycle
iterations is known.
(b) Duration
(c) Iteration
2. while Loop
(d) Test
Executes a block repeatedly while a given condition is
true. If condition is false initially, loop body will not run
Q5. The for loop is best used when:
even once.
(a) Number of iterations is unknown
(b) Number of iterations is known
3. do-while Loop
(c) Only once execution is needed
Executes the loop body at least once and then checks
(d) None of these
the condition. Condition appears after the loop body.
Q6. Which statement is used to jump to the start of a
4. for Loop
loop body?
Used when the number of iterations is known. Has
(a) continue
three parts: initialization, condition, and
(b) break
increment/decrement.
(c) switch
(d) goto
5. Nested Loops
A loop placed inside another loop. Useful for
Q7. Which loop condition is tested after executing the
multidimensional tasks like matrix operations or
loop body?
patterns.
(a) for
(b) while
6. Sentinel-Controlled Loop
(c) do-while
Loop terminates when a specific value (sentinel) is
(d) None of these
encountered.
Q8. Which of the following is a counter controlled
7. Goto Statement
loop?
Performs unconditional jump to a labeled section of
(a) while
code. Should be avoided in modern structured
(b) do-while
programming unless necessary.
(c) for
(d) if
Important Multiple-Choice
Q9. In a for loop, which part is executed only once?
Questions (MCQs) (a) Condition
(b) Increment/Decrement
Q1. Which of the following is not a loop statement? (c) Initialization
(a) for (d) Body
(b) if
(c) while Q10. Which operator can be used to increment in a
(d) do-while loop?
(a) ++
Q2. A loop that never terminates is called: (b) ==
(a) Running loop
Punjab Board-Part 2-Computer Science by Sir Taha

(c) -- (a) for


(d) != (b) while
(c) do-while
Q11. Which of the following is a loop control variable? (d) while/do-while with sentinel
(a) Global variable
(b) Identifier Q19. A loop within another loop is called:
(c) Local variable (a) Complex loop
(d) Loop control variable (b) Nested loop
(c) Dual loop
Q12. Which loop checks the condition before executing (d) Recursive loop
the loop body?
(a) while Q20. What is the output of this code?
(b) do-while
(c) both a and b int a = 10;
(d) None of these do {
printf("%d", a + 5);
Q13. Which symbol ends the do-while loop condition? } while(a <= 12);
(a) )
(b) ; (a) 22
(c) } (b) 15
(d) : (c) 10
(d) Error
Q14. How many expressions are in a for loop?
(a) 2 Answer Key for MCQs
(b) 4
(c) 3
(d) 5 Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8 Q9 Q10

b b b c b a c c c a
Q15. What is the final value of x after executing this
loop? Q11 Q12 Q13 Q14 Q15 Q16 Q17 Q18 Q19 Q20
for(int x = 0; x < 10; x++); d a b c a c a d b b

(a) 10
(b) 9
(c) 0
(d) 1
Important Short Questions (2
Q16. What is the keyword used to terminate a loop
early? marks each)
(a) continue
(b) exit Q1. What is a loop in C language? (2)
(c) break Ans: A loop is a control structure that allows repeated
(d) stop execution of a block of code while a condition is true.

Q17. Which statement provides an unconditional Q2. What is the main difference between while and
jump? do-while loops? (2)
(a) goto Ans: While loop checks the condition before execution.
(b) switch Do-while checks condition after execution, so it runs at
(c) continue least once.
(d) return
Q3. What is an infinite loop? (2)
Q18. Which of the following is called a sentinel Ans: A loop that never terminates due to always true
controlled loop? condition is called an infinite loop.
Punjab Board-Part 2-Computer Science by Sir Taha

Q4. What is the loop control variable? (2) Example Program:


Ans: A variable used to control the number of loop
iterations, usually incremented or decremented in each #include <stdio.h>
cycle. void main() {
int n = 1;
Q5. What is the purpose of the continue statement? while(n <= 10) {
(2) printf("%d\n", n);
Ans: continue skips the current iteration of a loop and n++;
jumps to the next cycle. }
}
Q6. What is a nested loop? (2)
Ans: A loop written inside another loop is called a Explanation: This prints numbers from 1 to 10 using a
nested loop. while loop.

Q7. What is the syntax of the for loop? (2) Q2. What is a do-while loop? Write its syntax and
Ans: explain with an example. (8)
Ans:
for(initialization; condition; increment) { A do-while loop is a post-test loop that ensures the loop
// code body is executed at least once before checking the
} condition.

Q8. What is a sentinel controlled loop? (2) Syntax:


Ans: A loop that stops execution when a specific value
(sentinel) is encountered, usually used with while or do- do {
while. // code
} while(condition);
Q9. Which loop is preferred when the number of
iterations is known? (2) Example:
Ans: The for loop is preferred when the number of
iterations is known in advance. #include <stdio.h>
void main() {
Q10. What is the purpose of the goto statement? (2) int n = 1;
Ans: It allows an unconditional jump to a labeled part of do {
the program, typically used for control transfer in printf("%d\n", n);
special cases. n++;
} while(n <= 10);
}
Important Long Questions (8
marks each) Explanation: This prints numbers from 1 to 10 using a
do-while loop. Even if the condition is false initially, the
Q1. What is a while loop? Explain its working with a loop body will run once.
program. (8)
Ans:
A while loop is a pre-test loop that executes a block of
code as long as the condition is true. The condition is Q3. Explain for loop in detail with an example to find
checked before the body is executed. It is used when factorial. (8)
the number of iterations is not known in advance. Ans:
A for loop is used when the number of iterations is
Syntax: known. It includes initialization, condition, and
increment/decrement in a single line.
while(condition) {
// code Syntax:
}
Punjab Board-Part 2-Computer Science by Sir Taha

for(init; condition; inc/dec) { Example:


// code
} #include <stdio.h>
void main() {
Example to find factorial: int marks, sum = 0, count = 0;
float avg;
#include <stdio.h> do {
void main() { printf("Enter marks (-1 to stop): ");
int i, n, f = 1; scanf("%d", &marks);
printf("Enter number: "); if(marks != -1) {
scanf("%d", &n); sum += marks;
for(i = 1; i <= n; i++) { count++;
f *= i; }
} } while(marks != -1);
printf("Factorial is %d", f); if(count > 0) {
} avg = (float)sum / count;
printf("Average marks = %.2f", avg);
Explanation: This program multiplies numbers from 1 to } else {
n to compute factorial using a for loop. printf("No data entered.");
}
Q4. Write a C program to print the following pattern }
using nested loops: (8)
Explanation: The loop runs until -1 is entered. Total and
0 count are used to compute average marks of students.
01
012
0123
01234

Ans:

#include <stdio.h>
Chapter 13: Functions in C
void main() {
int i, j; Important Multiple-Choice
for(i = 0; i <= 4; i++) {
for(j = 0; j <= i; j++) {
Questions (MCQs)
printf("%d ", j);
Q1. In __________ programming the whole program is
}
divided into number of functions.
printf("\n");
(a) Structured
}
(b) Unstructured
}
(c) Object oriented
(d) None of these
Explanation: The outer loop controls the number of
rows, and the inner loop prints numbers up to the
Q2. A __________ is a self-contained piece of code
current row number.
with a specific task.
(a) Compound statement
(b) Function
(c) Library
Q5. Explain sentinel controlled loop with a program to
(d) None of these
calculate average marks of students. (8)
Ans:
Q3. Built-in functions are packaged in __________.
A sentinel controlled loop stops when a specific value
(a) Source files
(e.g. -1) is input. It is used when the number of
(b) Header files
iterations is unknown.
Punjab Board-Part 2-Computer Science by Sir Taha

(c) Libraries (c) .


(d) Disk files (d) }

Q4. The first line of a function definition is called Q12. The keyword used for defining a function that
__________. does not return anything is __________.
(a) Function prototype (a) void
(b) Function call (b) int
(c) Function header (c) null
(d) Return statement (d) none

Q5. The general form of a return statement is Q13. The function that a programmer defines to solve
__________. a problem is called __________.
(a) return (expression); (a) Built-in
(b) return value; (b) User-defined
(c) return; (c) Library
(d) return [void]; (d) Static

Q6. If a function does not return a value, the keyword Q14. Actual parameters are passed to a function in the
__________ is used. __________.
(a) return (a) Function prototype
(b) int (b) Function header
(c) main (c) Function call
(d) void (d) Return statement

Q7. The statement used to call a function is known as Q15. Parameters declared in a function header are
__________. called __________.
(a) Function call (a) Actual parameters
(b) Function prototype (b) Global variables
(c) Function header (c) Formal parameters
(d) None of these (d) Return values

Q8. The variables declared inside a function are called Q16. A function can return only __________ value(s)
__________. using the return statement.
(a) Global (a) Two
(b) External (b) One
(c) Local (c) Three
(d) Static (d) None

Q9. The variables declared outside all functions are Q17. The values passed into a function are copied into
called __________. its __________.
(a) Automatic (a) Global variables
(b) Local (b) Local variables
(c) Static (c) Dummy variables
(d) Global (d) Formal parameters

Q10. The scope of a variable refers to its __________. Q18. A local variable exists in memory from its
(a) Name declaration to the end of its __________.
(b) Lifetime (a) Function
(c) Accessibility (b) File
(d) Value (c) Block
(d) Program
Q11. A function prototype ends with a __________.
(a) : Q19. The memory for local variables is allocated when
(b) ; the function is __________.
Punjab Board-Part 2-Computer Science by Sir Taha

(a) Declared Q3. Define function header. (2)


(b) Compiled Ans: A function header is the first line in a function
(c) Called definition that includes return type, function name, and
(d) Ended parameter list, e.g., int sum(int a, int b).

Q20. Functions in C help achieve __________ Q4. What is a function prototype? (2)
programming. Ans: A function prototype tells the compiler about a
(a) Modular function's name, return type, and parameters. It ends
(b) Linear with a semicolon.
(c) Procedural
(d) Dynamic Q5. What is the purpose of return statement in a
function? (2)
Ans: It returns a value from the function to the calling
code and ends function execution.
ANSWER KEY
Q6. What are local variables? (2)
1-a Ans: Variables declared inside a function or block are
2-b local and accessible only within that block.
3-c
4-c Q7. What are global variables? (2)
5-a Ans: Variables declared outside all functions are global
6-d and accessible throughout the entire program.
7-a
8-c Q8. What are formal and actual parameters? (2)
9-d Ans: Formal parameters appear in the function
10-c definition; actual parameters are the values passed to
11-b the function during the call.
12-a
13-b Q9. Define the scope of a variable. (2)
14-c Ans: The scope of a variable is the region in the program
15-c where it can be accessed or used.
16-b
17-d Q10. What is modular programming? (2)
18-c Ans: Modular programming is a technique where a
19-c program is divided into small manageable parts
20-a (functions) to simplify design and debugging.

IMPORTANT LONG QUESTIONS


IMPORTANT SHORT QUESTIONS WITH ANSWERS (8 marks each)
WITH ANSWERS (2 marks each) Q1. What is a function? Write the importance of using
functions in C. (8)
Q1. What is a function in C? (2) Ans:
Ans: A function is a self-contained piece of code that A function in C is a block of code designed to perform a
performs a specific task. It can be reused multiple times specific task. It enhances code clarity, reusability, and
to avoid code duplication. modularity. Functions allow programmers to break a
large problem into smaller parts.
Q2. What is the difference between built-in and user- Importance includes:
defined functions? (2)
Ans: Built-in functions are predefined and provided by C • Modularity: Breaks down code into manageable
libraries (e.g., printf), while user-defined functions are sections.
created by the programmer to solve custom problems. • Reusability: Code written once can be reused
multiple times.
Punjab Board-Part 2-Computer Science by Sir Taha

• Debugging: Easier to find and fix issues. }


• Collaboration: Multiple people can work on
different functions. Local variables have block-level scope and short
• Readability: Makes code organized and easy to lifetime; global variables have file-level scope and last
follow. till program ends.

Q2. Describe function definition, prototype, and Q4. Write a program in C that calculates factorial using a
function call with examples. (8) function. Explain the function's structure. (8)
Ans: Ans:
Function Definition includes the full function body, e.g.,
#include<stdio.h>
int sum(int a, int b) {
int factorial(int n);
return a + b;
void main() {
}
int num;
Function Prototype is a declaration of the function:
printf("Enter a number: ");
int sum(int, int);
scanf("%d", &num);
Function Call is where the function is used:
printf("Factorial = %d", factorial(num));
int result = sum(5, 10);
}
This separates declaration, implementation, and usage,
improving code structure. int factorial(int n) {

int result = 1;

Q3. Explain local and global variables with examples, while(n > 0) {
including their scope and lifetime. (8)
Ans: result *= n;
Local Variables are declared inside functions/blocks.
They exist only during the function execution and are n--;
inaccessible outside it.
Example: }

void func() { return result;

int x = 10; // local }

} Explanation:

Global Variables are declared outside any function and • factorial(int n) is a user-defined function with
exist throughout the program. return type int.
Example: • It accepts one argument n, processes it, and
returns a result.
int x = 5; • Function call is made from main().

void display() { Q5. Write a function that accepts two arguments and
returns the area of a triangle. Also write the main
printf("%d", x); // accessible here
Punjab Board-Part 2-Computer Science by Sir Taha

function to call it. (8) (d) Binary


Ans:
Q3. There are __________ types of stream.
#include<stdio.h> (a) 3
(b) 4
float area_of_triangle(int base, int height); (c) 5
(d) 2
void main() {
Q4. A stream is disassociated from a file using a
int b, h; __________ operation.
(a) Open
(b) Binary
printf("Enter base and height: ");
(c) Text
(d) Close
scanf("%d %d", &b, &h);
Q5. A __________ stream is a sequence of characters.
printf("Area = %.2f", area_of_triangle(b, h)); (a) Text
(b) Binary
} (c) Both a and b
(d) None of these
float area_of_triangle(int base, int height) {
Q6. The __________ function is used to open a file and
return 0.5 * base * height; associate it with a stream.
(a) open()
} (b) fopen()
(c) fclose()
Explanation: (d) fop()

• This function demonstrates argument passing Q7. The second parameter of fopen function is
and returning a value. __________.
• It’s a modular approach using parameterized (a) File name
functions to perform specific tasks efficiently. (b) Path
(c) BOF
(d) Mode

Q8. The fopen() function returns the __________


Chapter 14: File Handling in pointer if it fails to open the file.
(a) BOF
C (b) EOF
(c) NULL
(d) CLOSE
Important Multiple-Choice
Questions (MCQs) Q9. Which of the following mode opens a text file for
append?
Q1. A __________ is a set of related records. (a) r+
(a) Stream (b) w+
(b) File (c) a
(c) Function (d) r
(d) String
Q10. The __________ function closes the file
Q2. A stream is associated to a file using an __________ associated with file pointer.
operation. (a) fgets
(a) Close (b) fclose
(b) Open (c) fexit
(c) Logical (d) fend()
Punjab Board-Part 2-Computer Science by Sir Taha

Q11. A __________ is a variable of type FILE. (b) strcpy


(a) NULL (c) str
(b) BOF (d) copy
(c) File pointer
(d) Address Q20. A string is an array of type __________.
(a) int
Q12. The function that reads the next character from (b) float
the file is __________. (c) char
(a) getch() (d) All of the above
(b) getc()
(c) putc()
(d) gete()
Answer Key
Q13. The fputs() function writes a __________ to the
associated stream. Q# Ans Q# Ans
(a) int
(b) String 1 b 11 c
(c) Character
(d) Float
2 b 12 b
Q14. An array is a group of __________ memory
locations. 3 d 13 b
(a) Different
(b) Contiguous 4 d 14 b
(c) Random
(d) None of these 5 a 15 a

Q15. Array can store data of __________ type.


6 b 16 c
(a) Same
(b) Different
(c) Any 7 d 17 c
(d) None of these
8 c 18 b
Q16. The last character of every string is __________.
(a) /0 9 c 19 b
(b) Null
(c) \0 10 b 20 c
(d) 1

Q17. Which of the following is the valid example of Important Short Questions with
string declaration?
(a) int name[10];
Answers (2 marks each)
(b) char name[10]
Q1. What is a stream? (2)
(c) char str[16];
Ans: A stream is a logical interface to a file. It links a
(d) string s;
program to the file through open and close operations.
Q18. A __________ can store text only. Streams are of two types: text and binary.
(a) Binary file
Q2. What is the purpose of the fopen() function? (2)
(b) Text file
Ans: The fopen() function is used to open a file and
(c) Document file
associate it with a stream. It takes the file name and
(d) None of these
mode as parameters.
Q19. Which of the following function is used to copy a
Q3. What is a file pointer? (2)
string?
Ans: A file pointer is a variable of type FILE* used to
(a) Str copy
Punjab Board-Part 2-Computer Science by Sir Taha

access and manage file operations in C. It is declared as • Binary Stream: A sequence of raw bytes written
FILE *fp;. to or read from a file with exact one-to-one
correspondence.
Q4. What does the fclose() function do? (2) Example: Opening a text file vs binary file in
Ans: The fclose() function closes an opened file and fopen() using "r" and "rb" respectively.
releases the associated resources. It returns 0 if
successful, EOF otherwise. Q2. Explain the syntax and modes of fopen() function.
(8)
Q5. What is the difference between text and binary Ans:
streams? (2) fopen() is used to open a file and associate it with a
Ans: Text streams handle characters with possible stream.
translations like newline, while binary streams transfer Syntax:
raw byte data with one-to-one correspondence.
FILE *fp = fopen("filename.txt", "mode");
Q6. What is the use of getc() function? (2)
Ans: The getc() function reads the next character from Parameters:
the file. It returns the character or EOF if the end is
reached or an error occurs. • "filename.txt": the name of the file

Q7. What is the purpose of the putc() function? (2) • "mode": specifies the file access mode (e.g., "r",
Ans: The putc() function writes a single character to a "w", "a", "r+", etc.)
file. It returns the written character or EOF if an error
occurs. Modes:

Q8. What is the null terminator in strings? (2) • "r" – read


Ans: The null terminator \0 is used to indicate the end
of a string in C. • "w" – write (creates new or overwrites)

Q9. What is the fgets() function used for? (2) • "a" – append
Ans: The fgets() function reads a line or string of
• "r+" – read and write (file must exist)
characters from a file into a buffer until a newline or
EOF is encountered.
• "w+" – write and read (overwrite or create)
Q10. What is the difference between fprintf() and
• "a+" – read and append
fscanf()? (2)
Ans: fprintf() writes formatted data to a file, while If the file cannot be opened, fopen() returns NULL.
fscanf() reads formatted data from a file. They work like
printf() and scanf() but for file streams. Q3. What are getc() and putc() functions? Write a
program to demonstrate their use. (8)
Important Long Questions with Ans:
Answers (8 marks each) • getc(FILE *fp): Reads the next character from
the file.
Q1. What is a stream? Explain types of streams with
examples. (8) • putc(int ch, FILE *fp): Writes a character to the
Ans: file.
A stream is a logical connection between a program and
an input/output device (like a file). C uses streams to Program Example:
handle file input and output operations. There are two
main types: #include <stdio.h>

• Text Stream: A sequence of characters that may void main() {


undergo translation (e.g., newline \n converted
to carriage return and line feed). FILE *fr, *fw;
Punjab Board-Part 2-Computer Science by Sir Taha

int ch; fw = fopen("student.txt", "w");

fr = fopen("input.txt", "r"); if (fw == NULL) {

fw = fopen("output.txt", "w"); printf("File error!");

if(fr && fw) { return;

while((ch = getc(fr)) != EOF) { }

putc(ch, fw); printf("Enter name: ");

} gets(name);

} printf("Enter address: ");

fclose(fr); gets(address);

fclose(fw);

} fputs(name, fw);

Q4. What are arrays and strings in C? Explain with fputs(" ! ", fw);
examples. (8)
Ans: fputs(address, fw);

• Array: A collection of elements of the same type fputs("\n", fw);


stored in contiguous memory.
Example: fclose(fw);

int marks[5] = {90, 85, 78, 88, 92}; // Read back

• String: An array of characters ending with a null FILE *fr = fopen("student.txt", "r");
terminator \0.
Example: char line[50];

char name[] = "Ali"; fgets(line, 50, fr);

Difference: printf("\nData from file:\n%s", line);


Arrays can be of any type, strings are specifically arrays
fclose(fr);
of char.
}
Q5. Write a program using fputs() and fgets() functions
to store and read student data. (8)
Ans:
Program:

#include <stdio.h>

#include <string.h>

void main() {

FILE *fw;

char name[20], address[30];


Punjab Board-Part 2-Computer Science by Sir Taha

Taha Sir ka Chiller Paighaam!


Agar yahan tak aagye ho iska matlab hai File
Handling clear hogyi hogi!
Agle chapters ke notes bhi ready hain —
sirf WhatsApp community mein aao aur le jao!

Kaise join karni hai community?


Bhai simple hai — koi rocket science nahi!
Bas message karo:
"Hi Sir Taha, community link chahiye!"
is number pe: 0310-4539691

Phir kya?
Notes
milenge,
topper
banoge —
party meri taraf
se!
Chalo phir, milte hain next notes
ke saath!

You might also like