Computer PDF
Computer PDF
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
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
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
• 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:
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:
• 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.
(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
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
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
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
(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
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
(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
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
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.
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
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
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
(/*...*/).
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
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
(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 (!).
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
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
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.
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
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
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.
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: }
} 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
• 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
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:
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>
} gets(name);
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);
• String: An array of characters ending with a null FILE *fr = fopen("student.txt", "r");
terminator \0.
Example: char line[50];
#include <stdio.h>
#include <string.h>
void main() {
FILE *fw;
Phir kya?
Notes
milenge,
topper
banoge —
party meri taraf
se!
Chalo phir, milte hain next notes
ke saath!