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

COMPUTER SCIENCE

CLASS XII
STUDY NOTES

Prepared By:

Prof. Noman Qadeer

As per the syllabus prescribed by


Federal
0
Board of IntermediateComputer
and Science
Secondary Education,
XII (By: Prof. Noman Qadeer)
Islamabad
Chapter # 1: Operating System - MCQs
1. In _______ operating system, CPU is rapidly switched between programs so that all the programs are
executed at the same time.
(a) Multi programming operating system (b) Batch processing operating system
(c) Real-time operating system (d) Time-sharing operating system
2. In which operating system, same types of jobs are grouped together and executed one by one?
(a) Multi programming operating system (b) Batch processing operating system
(c) Real-time operating system (d) Time-sharing operating system
3. _____ is the most user friendly interface.
(a) CLI (b) Menu driven (c) GUI (d) All of these
4. ____ was introduced in 1970s at Bell Laboratories.
(a) DOS (b) UNIX (c) WINDOWS (d) Mac OS
5. Which operating system runs applications with very precise timing and provides immediate response to
avoid safety hazards?
(a) Multitasking operating system (b) Multiprocessing operating system
(c) Real-time operating system (d) Distributed operating system
6. A program in execution is known as _________.
(a) Task (b) Process (c) Operation (d) Thread
7. Which operating system divides a task into many subtasks and processes them independently using many
Processors?
(a) Parallel operating system (b) Multitasking operating system
(c) Real-time operating system (d) Distributed operating system
8. Which of the followings allocates computer resources during program execution?
(a) Process management (b) Memory Management
(c) I/O Management (d) File Management
9. In which state a process is waiting to be assigned to the processor by OS scheduler?
(a) New state (b) Ready state (c) Waiting state (d) Running state
10. Which operating system is used in home appliances?
(a) Time-sharing operating system (b) Parallel operating system
(c) Embedded operating system (d) Distributed operating system
11. Which of the followings creates user groups and assigns privileges to them?
(a) File management (b) Process Management
(c) I/O Management (d) Network Management
12. Operating System is a type of ____ software.
(a) Controlling Software (b) Application Software
(c) Utility Software (d) System Software
13. DOS is an example _____ software.
(a) Single user (b) Single tasking (c) CLI (d) All
14. The folder in DOS is called_____
(a) Directory (b) Drive (c) File (d) Path
15. Multiprogramming of the computer system increases_______.
(a) I/O (b) Storage (c) CPU Utilization (d) Cost

ANSWER KEY: 1.D-2.B-3.C-4.B-5.C-6.B-7.A-8.A-9.B-10.C-11.D-12.D-13.D-14.A-15.C

1 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 1: Operating System
SHORT QUESTIONS
1. What is operating System? Name any four of its types.
Ans: An operating system is a collection of system software that control and manage the activities of a
computer system. Operating system manages the overall functioning of a computer system. Some
of its types are:
 Batch Processing Operating System ● Multitasking Operating System
 Multiprogramming Operating System ●Time sharing Opera ng System
 Real-Time Operating System ●Mul processor Opera ng System
 Parallel Processing Operating System ●Distributed Opera ng System
 Embedded Operating System (Write name of only four or as asked in question)

2. Why memory management is required in computer system?


Ans: All programs are loaded into memory for processing. Memory management is essential as it
ensures that all processes may execute efficiently without any problem and required amount of
memory may be allocated to each process so that no process may overlap with other processes.

3. What is thread?
Ans: A thread is the basic unit of CPU utilization/allocation. It is a sequence of instructions within a
process. A process is divided into multiple threads for efficient execution.

4. Differentiate between process and thread.


Process Thread
Ans: Program during execution is called process Thread is a subset of process
It has own copy of data segment of parent It has direct access to the data segment of parent
process process
Any change in process not affect other processes Any change in thread can affect other threads
These run in separate memory spaces These run in shared memory spaces
These are controlled by the operating system These can be controlled by programmer
Processes are independent Threads are dependent
5. What is the purpose of operating system in computer?
Ans: The operating is essential for the working of a computer system. Computer cannot without an
operating system. OS manages the overall functioning of its hardware and software and provides
interface to user.

6. What is Graphical User Interface (GUI)?


Ans: Graphical User Interface is the style of interaction of OS with user. It includes colorful graphics like
icons, charts, graphs, wallpapers. GUI is user friendly and efficient interface.

7. Mention three advantages of UNIX operating system.


Ans: ●UNIX is a mul tasking opera ng system.
●It provides be er processing power than Windows OS
●It provides be er security i.e. it cannot be a acked by malware.

2 Computer Science XII (By: Prof. Noman Qadeer)


8. Differentiate between multiprogramming and time-sharing operating systems.
Ans:
Multiprogramming Operating Systems Time-sharing Operating Systems
It maximizes the processor’s use It minimizes the response time
It does not support interactive mode It works on interactive mode
It does give short period of time to process It gives short period of time (slice) to process
It runs various programs at the same time It rums multiple programs but one at a time on
time sharing
The process can be executed by a single In this process two or more users can uses a
processor processor on their own terminal
Ex. Mac OS Ex. Windows NT

9. Why multiprocessing operating systems have been developed?


Ans: Multiprocessing operating systems have been developed to increase the computing power of
computer systems. It uses two or more process to process data at the same time so data can be
processed at a very high speed.
10. Differentiate between single user and multi-user operating systems.
Ans:
Single User Operating Systems Multi user Operating Systems
It allows only a single user to use computer It allows multiple users to use computer at the
same time
It is not cost effective It is cost effective
It may run on low power computers It requires computers having high computing
power
It is simple It is complex
Ex: Windows, DOS etc. Ex. UNIX, Linux etc.

11. Why protection system is required in computer?


Ans: Protection system is required for the security of computer resources. It prevents the unauthorized
use access to computer resources. It also protects a process from the activities of other process. It
maintains IDs and passwords for the users.

12. Differentiate between multiprogramming and multithreading by giving one example of each.
Ans:
Multiprogramming Multithreading
It loads multiple programs but runs one at a It divides a program into threads and executes
time multiple threads at a time
It is slower It is faster
Programs do not affect other programs Threads may affect the working of other
threads
Programs are independent of each other Threads are dependent on each other
Programs do not share common memory Threads share common memory locations
It is manage by OS It can be managed by programmer (user level
threads)

3 Computer Science XII (By: Prof. Noman Qadeer)


13. Draw a diagram showing various states of a process.
Ans:

14. Mention any THREE tasks performed by the Operating System.


Ans:
 It controls and coordinates the activities of computer system
 It manages system resources
 It provides interface between user and computer system
 It provides interface between hardware and application software
 It performs network operations
 Detects hardware failures
 Provides system security (Write name of only three or as asked in question)

15. Differentiate between CLI and GUI.


Ans:
CLI GUI
It is based on text commands It comprises of on screen graphics
It is difficult to learn It is easy to learn
It is difficult to use It is easy to use
Multiple commands are to be learnt and No command to learn and recall at the time of
memorized use
It is not user friendly i.e. it has no attraction It is user friendly and attracts user by colorful
and user gets bored graphics
e.g. DOS e.g. Windows

16. Differentiate between DOS and Windows.


Ans:
DOS WINDOWS
DOS provides CLI Windows provides GUI
It is difficult to learn It is easy to learn
It is difficult to use It is easy to use
Multiple commands are to be learnt and No command to learn and recall at the time of
memorized use
It is not user friendly i.e. it has no attraction It is user friendly and attracts user by colorful
and user gets bored graphics
It is single tasking It is multitasking

4 Computer Science XII (By: Prof. Noman Qadeer)


17. Define Batch Processing Operating System.
Ans: Batch processing Operating System is a type of OS which collects the programs and data together in a
batch before processing starts and then automatically executes them one by one.

Advantages (to write only in long Q)


 Batch processing takes much of the work of the
operator to the computer.
 Increased performance as a new job get
started as soon as the previous job is finished,
without any manual intervention.

Disadvantages (to write only in long Q)


 Difficult to debug program.
 A job could enter an infinite loop.
 Due to lack of protection scheme, one batch job can affect pending jobs.
18. Define Multiprogramming Operating System.
Ans: It is an operating system that allows sharing the processor, when two or more
programs reside in memory at the same time. Multiprogramming assumes a
single shared processor. Multiprogramming increases CPU utilization by
organizing jobs so that the CPU always has one to execute.

19. Define Multitasking Operating System.


Ans: Multitasking Operating system is a software that allows
multiple jobs to be executed by the CPU simultaneously by
switching between them. Switches occur so frequently that
the users may interact with each program while it is running.

20. Define Time-sharing Operating System.


Ans: A time sharing operating system allows many users to share the computer resources
simultaneously. In other words, time sharing refers to the allocation of computer resources in time
slots to several programs simultaneously. This short period of time is known as a time slice or a
quantum.

21. Define Real-time Operating System.


Ans: A real time operating is a software that runs real time applications that must process data as soon
as it comes and provides immediate response. It is used when response time is too short and
accuracy is required. It is used in weather forecasting, space research and oil refining etc.

22. Define Multiprocessor Operating System.


Ans: Multiprocessor Operating System refers to the use of two or more CPUs within a single computer
system. These multiple CPUs are in a close communication sharing the computer bus, memory and
other peripheral devices. This helps in simultaneous processing of programs.

5 Computer Science XII (By: Prof. Noman Qadeer)


23. Define Parallel Processing Operating System.
Ans: In computers, parallel processing is the processing of program instructions by dividing them among
multiple processors with the objective of running a program in less time. Programs are split and
are executed simultaneously on different processors attached to the same computer.
24. Define Distributed Operating System.
Ans: A distributed operating system is a software over a collection of independent, networked,
communicating, and physically separate computers. They handle jobs which are serviced by
multiple CPUs. Each individual computer holds a specific software subset of the global aggregate
operating system.
25. Define Embedded Operating System.
Ans: This is a type of software which is embedded in the hardware of the device. It is embedded in
device like microwave oven or other home appliances to control their functioning. It is stored in
firmware and starts working as soon as device is powered on.
26. Define Process Management.
Ans: Process management is the management of processes being executed and allocating the system
resources to them. It manages the allocation of resources so that all processes may execute
properly.
27. Define Memory Management.
Ans: It is the part of operating system that manages the allocation of memory space to the process. It
ensures that all processes may execute efficiently without any problem and required amount of
memory may be allocated to each process so that no process may overlap with other processes.
And free space is recovered after the completion of process.
28. Define File Management.
Ans: It is a part of an operating system that uses to organize and keep track of files and folders in
secondary storage such as Hard disk, DVD or USB Flash disk. For example, a hierarchical file system
is one that uses directories to organize files into a tree structure.
29. Define I/O Management.
Ans: It is a part of OS that controls all the input output operations during program execution. It manages
all input output operations by all IO devices or secondary storage devices.

30. Define Secondary Storage Management.


Ans: It is a part of operating system that manages the allocation of storage space to data and program
in secondary storage devices like Hard disk, DVD or USB flash disk.
31. Define Network Management.
Ans: It is a part of operating system that manages the security and resources of a network. It assigns id
and passwords to users of computer systems over a network.
32. Define Protection System.
Ans: It is a part of operating system that ensures that each resource of the computer system is used as
per the privileges assigned to each user. It creates account for each user and assigns privileges.
33. Define Command Interpreter.
Ans: Command interpreter is the part of operating system that provides interface between user and
computer system. It is a file in operating system that reads and executes user commands.

6 Computer Science XII (By: Prof. Noman Qadeer)


34. Define multithreading with example.
Ans: In computer architecture, multithreading is the ability of a CPU (or a single core in a multi-core
processor) to execute multiple processes or threads concurrently, supported by the operating
system. This approach differs from multiprocessing. In a multithreaded application, the processes
and threads share the resources of a single or multiple cores.
35. Define multitasking.
Ans: Multitasking allows multiple jobs to be executed by the CPU simultaneously by switching between
them. Switches occur so frequently that the users may interact with each program while it is
running. New tasks can interrupt already started ones before they finish, instead of waiting for
them to end.

36. Define multiprogramming.


Ans: The sharing the processor, when two or more programs reside in memory at the same time is
known as multiprogramming. Multiprogramming assumes a single shared processor.
Multiprogramming increases CPU utilization by organizing jobs so that the CPU always has one to
execute.

37. Define multiprocessing.


Ans: Multiprocessing is the use of two or more central processing units (CPUs) within a single computer
system. The term also refers to the ability of a system to support more than one processor or the
ability to allocate tasks between them.

38. Write a note on DOS.


Ans: DOS stands for Disk Operating System. It was introduced in 1970s when microcomputer was
introduced. It is known as Disk Operating System because the whole operating system is saved in
a disk (Floppy Disk). It is a single user and single tasking operating system. It has a Command Line
Interface i.e. user has to type commands to perform operations; therefore, it is not user friendly.
Its commands are divided into two basic categories i.e. Internal and External Commands. Some of
its commands are:
RENAME: for renaming a file CD: Change Directory
CLS: Clear Screen DEL: Delete a File or folder etc.
39. Write a note on Windows.
Ans: Windows is the most popular operating system for microcomputers and was introduced by
Microsoft in the mid-1980s. It provides a Graphical user interface (GUI) hence is user friendly. It is
multitasking and single user operating system. It uses menus and icons to perform operations.
Microsoft has released various versions to enhance the user interface come-up with the needs of
growing technology, e.g. Windows 95, Windows 98, Windows 2000, Windows XP. Windows 7,
Windows 8, Windows 10 etc.

40. Write a note on UNIX.


Ans: UNIX operating system was developed by Ken Thompson and Denis Ritchie at Bell Laboratories in
early 1970s. It was developed in C language and was compatible for a variety of computer systems
from microcomputers to mainframes. It uses menu driven interface. It provides greater processing
power and better security than Windows Operating System so computers running UNIX have very
rare chances of malware attack.

7 Computer Science XII (By: Prof. Noman Qadeer)


41. Write a note on Mac OS.
Ans: Mac OS is a series of operating systems introduced by Apple Inc since 2001 for various types of
Apple computers. After Windows, it is the second most widely used operating system. It targets
personal computing and is installed on Apple desktop and laptop computers. It is graphical user
interface. It is preceded by Classic Mac OS which was introduced in 1984 which was finally released
as Mac OS 9 in 1999. The first desktop version was Mac OS 10 released in 2001. It is powerful and
secure operating system.

42. Write a note on Linux.


Ans: Linux is a free and Open Source Operating system which was firstly released in 1991. Most of its
features are like UNIX. It is written in C and Assembly languages. It is installed on personal
computers, mobile devices, embedded devices, servers, mainframe and super computers. A Linux
based OS Android is dominant on all mobile devices however its other types are popular in
network routers, DVRs, embedded devices and video games. The most popular Linux distributions
are OpenSUSE and Ubuntu.

43. What are the tasks performed by an operating system?


Ans: Operating System performs the following tasks:
 Coordinates the activities of hardware components
 Loads software into memory and executes it
 Controls the operation of main memory and other storage devices
 Manages files and folders in secondary storage
 Manages operations of I/O devices
 Handles multitasking
 Manages network operations like communication and data/resource sharing
 Detects hardware failure
 Manages system security

8 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 2: System Development Life Cycle- MCQs
1. The first step in SDLC is________.
(a) Analysis (b) Design (c) Problem Identification (d) Development
2. System maintenance is performed in response to __________.
(a) Business changes (b )Hardware and software changes
(c) User request for additional features (d) all of these
3. Enhancement, up gradation and bugs fixation is are done during the ______ step in SDLC.
(a) Maintenance and Evaluation (b) Problem identification
(c) Design (d) Development and documentation
4. Which of the following is the fourth phase of SDLC?
(a)Planning (b) Analysis (c) Designing (d) Development
5. Which of the following symbol is used for decision making in a flowchart?
(a) Parallelogram (b) Rectangle (c) Diamond (d) Oval
OR
(a) (b) (c) (d)
6. In ____ implementation, the new system is initially installed for a small number of users.
(a) Direct (b) Phased (c) Pilot (d) Parallel
7. The organized process or set of steps that needs to be followed to develop an information system is known
as _______
(a) Analytical Cycle (b) Design Cycle (c) Program Specifications (d) SDLC
8. The _______ determines whether the project should go forward.
(a) Feasibility (b) Problem Identification (c) System Evaluation (d) Program specifications
9. _________ spend most of their time in the beginning stages of the SDLC, talking with end users, gathering
requirements, documenting systems and proposing solutions.
(a) Project Managers (b) System Analysts (c) Network Engineers (d) database Administrators
10. The entities having positive or negative influence in the project completion are known as _______
(a) Stakeholders (b) Stake supervisors (c) Stake owners (d) None of these
11. Which of the following is not a phase of System Development Life Cycle?
(a) Testing (b) Coding (c) Assessment (d) Maintenance
12. The symbol at the beginning and end of the flowchart is_________.
(a) Parallelogram (b) Rectangle (c) Diamond (d) Oval
13. Coding is also called________.
(a) Programming (b) Evaluation (c) Translation (d) Assigning Password
14. The person who uses the information system directly or uses information produced by system is _____
(a) System analyst (b) End-user (c) Project Manager (d) Programmer
15. An algorithm is ________.
(a) Graphical chart (b) Problem statement (c) Set of rules (d) Set of steps

ANSWER KEY: 1.C-2.D-3.A-4.B-5.C-6.C-7.D-8.A-9.B-10.A-11.C-12.D-13.A-14.B-15.D

9 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 2: System Development Life Cycle
SHORT QUESTIONS
1. What is a System?
Ans: The term System is a Greek work which means “place together”. In software engineering, it is a set
of hardware and software components for collecting, creating, processing and distributing
information.
2. What do you mean by SDLC? Name its phases.
Ans: System Development Life Cycle (SDLC) is the processing of creating information system. These are
the methodologies that expert use to create information systems in a systematic way and in perfect
manner. Its phases are:
● Defining Problem (Problem Defini on / Iden fica on) ●Planning
●Feasibility Study ● Analysis ● Requirement Engineering
● System Design ● Coding (Development) ● Tes ng / Verifica on
● Deployment / Implementation ● Maintenance / Support
3. What are the objectives of SDLC?
Ans: Following are the objectives of SDLC:
●To ensure that high quality systems are delivered.
●To provide strong management controls over projects.
●To maximize the productivity.
4. Give some activities of planning phases.
Ans: Planning phase determines the objectives of the project and considers the requirements to produce
the project. An estimate of resources and cost is considered along with the concept of new product.
5. Differentiate between functional and Non-functional requirements.
FUNCTIONAL REQUIREMENTS NON-FUNCTIONAL REQUIREMENTS
These specify the software functionality These specify the criteria for the judgment of the
operations of system
These define what system should do These define how system will do
These are mandatory These are not mandatory
These are the features of product These are the properties of product
These are easy to capture These are difficult to capture
These include Calculations, Technical details, Data These include Accessibility, Compliance,
manipulation etc. Documentation, privacy, efficiency etc.
6. Design phase is considered as the “Architectural” phase of SDLC. Give reasons.
Ans: Design phase is architectural phase as it specifies the most logical structure for storage and data
flow. It also specifies the user interface. Design phase includes Algorithm and Flow charts. Mock-up
screens are designed for developers to write the code for actual interface.
7. What is the purpose of Testing / verification phase of SDLC? OR What is Testing?
Ans: Testing is to check the consistency of system and evaluating its results. The main purpose of testing
phase is to verify the functionality and performance of system. It evaluates the attribute and or
capability of system whether it meets the requirements.
8. What is an algorithm?
Ans: An algorithm is the set of instructions in a non-computer language to solve a particular task. It has
no standards i.e. it is written in an informal language.

10 Computer Science XII (By: Prof. Noman Qadeer)


9. What is flowchart? Explain its symbols. (May be a long question if all symbols are explained)
Ans: The graphical representation of an algorithm is known as flow chart. Unlike algorithm, Flow chart
has standard symbols for each type of instruction. Its symbols are explained below.

Symbol Name Symbol Shape Description


Terminal (Oval) Shows start and end of flow chart
Input / Output
Shows Input / Output Operation
(Parallelogram)
Processing
Shows Arithmetic Operation / Processing
(Rectangle)
Decision
Shows some condition/Decision to be taken
(Diamond)
Flow Lines Shows the flow of program by connecting various symbols
(Arrow) of flow chart
Connector
Connects two parts of flowchart
(Circle)

10. Give main activities of implementation phase.


Ans: Implementation or deployment is the set of activities to make the software available for use. Its
main activities are:
●Installation: Installation and Activation of software and hardware.
●Training: Training of users on developed software (not necessary in all cases).
●Conversion: Conversion of old system into new system(not necessary in all cases).
11. What Direct implementation? Define with diagram.
Ans: The implementation method in which old system is no longer available, it is completely f\dropped
and new system is completely implemented.

Old System New System

12. What Parallel implementation? Define with diagram.


Ans: The implementation method in which involves implementation of both the old and new systems
for a certain period. It addresses the errors in new system without loss of data.

Old System

New System

13. What Phased implementation? Define with diagram.


Ans: The implementation method in which new system is gradually inducted and old system is gradually
discarded.

Old System New System

11 Computer Science XII (By: Prof. Noman Qadeer)


14. What Pilot implementation? Define with diagram.
Ans: The implementation method in which the new system is initially installed for a small number of
users. These users learn and evaluate the system before it is installed for all.

Old System New System

15. What is the role of management personnel/Team in SDLC?


Ans: A management personnel or team is responsible to satisfy the customer and manage the overall
process of system development. Its main roles are:
●To provide consistency of success in terms of me, cost and quality
●To ensure that customers expectations are met
●To collect historical data for future use
●To reduce the risks associated with the project

16. What is the role of Project Manager in SDLC?


Ans: Project Manager is a professional responsible for planning, execution and closing of any project.
Apart from management skills, he has a vast background of software development. His key roles
are:
●Developing project plan ●Managing the project budget
●Managing the project stakeholders ●Managing the project team
●Managing the project risk and conflicts ●Managing the project schedule
(Write any three in short question and all in long)
17. What is the role of System Analyst in SDLC?
Ans: System analyst is a professional in the field of software development who studies the problems,
plans solutions, recommends software systems and coordinates development for business and
other requirements. He is expert in various programming languages, operating systems and
hardware platforms. His key roles are:
●To plan system flow
●To interact with customers to learn and document the requirements
●To define technical requirements
●To interact with designers to understand the limitations of system
●To help programmers in development phase
●To manage system tes ng
●To prepare user and technical documents (Write any three in short question and all in long)

18. What is the role of Programmer in SDLC?


Ans: A programmer is professional who writes computer programs in programming language. He writes,
test and debugs the program to develop software. His key roles are:
●To write, test and debug the program
●To update, modify and expand existing programs
●To prepare graphs tables and analy cal data displays to show the progress of a computer program

19. What is the role of Software Tester in SDLC?


Ans: A software tester is a programmer having expertise in software testing using different testing
techniques. His key roles are:
●To understand requirements
●To test debug the program by creating test scenarios and test data
●To execute program with test data and report the defects if any.

12 Computer Science XII (By: Prof. Noman Qadeer)


20. Who is a customer, in SDLC?
Ans: Customer is a person or organization who buys or uses a software. Customer buys software from
software manufacturers. It may get a software developed on demand or buy a readymade.
Customer is the true evaluator of software who uses it and identifies its merits and demerits.
21. What do you know about stakeholders?
Ans: Stakeholders are those entities which are either within or outside of organization that sponsor,
plan, develop or use a project. They have positive or negative influence on project completion.
22. What is Problem Definition?
Ans: Defining a problem is the first phase of SDLC which clearly defines the problem to be solved. All the
requirements are documented in this phase are approved by the customer.
23. What is planning phases?
Ans: Planning is the second phase of SDLC. It determines the objectives of the project and considers the
requirements to produce the project. An estimate of resources and cost is considered along with
the concept of new product.
24. Feasibility Study?
Ans: Feasibility study is the third phase of SDLC. It assesses the strengths and weaknesses of a project
and present directions to achieve the desired results. It evaluates the project to determine whether
it is financially, technically, legally and operationally feasible. Therefore, it is divided into following
forms:
●Technical feasibility ●Financial feasibility ●Operational feasibility
●Legal feasibility ●Schedule feasibility
25. Define Analysis.
Ans: Analysis is the fourth phase of SDLC. It determines the end-user requirements by explaining the
needs and expectations of clients. In this phase, in-charge of project team decides whether the
project should go ahead with current resources or not.
26. Define Requirement Engineering and its steps.
Ans: Requirement Engineering is the fifth phase of SDLC. It is a set of activities used to identify and
communicate the purpose of a software system and the framework in which it will be used.
Requirement engineering has three steps:
●Requirement Gathering: Meetings with customer are arranged and marker demands are
analyzed. Requirements may be Functional or Non-functional.
●Requirement Validation: Examining the requirement whether they meet the demands of
customer
●Requirement Management: Ensuring that the software continues to meet the demands of user.
It needs to gather new requirements for the newly arising challenges or demands.
27. Define Design phase.
Ans: Design phase is the sixth phase of SDLC. Design phase includes Algorithm and Flow charts. It is also
known as architectural phase as it specifies the most logical structure for storage and data flow. It
also specifies the user interface. Mock-up screens are designed for developers to write the code for
actual interface.
28. Define Construction/ Coding phase.
Ans: Coding is the seventh phase of SDLC. In this phase the programmer writes programs in computer
programming language on the basis of plans laid out in design phase. Coding is also called
programming

13 Computer Science XII (By: Prof. Noman Qadeer)


29. What is Testing?
Ans: Testing is the eighth phase of SDLC. It is to check the consistency of system and evaluating its
results. The main purpose of testing phase is to verify the functionality and performance of system.
It evaluates the attribute and or capability of system whether it meets the requirements.
30. What is implementation?
Ans: Implementation or deployment is the ninth phase of SDLC. It is the set of activities to make the
software available for use. Its main activities are:
●Installation: Installation and Activation of software and hardware.
●Training: Training of users on developed software (not necessary in all cases).
●Conversion: Conversion of old system into new system (not necessary in all cases).
31. What is importance of Maintenance and Support? OR What is maintenance/Support Phase?
Ans: Maintenance and support is the last phase of SDLC and it is an ongoing process. The system is
monitored continuously for performance in accordance with user requirements. Maintenance can
be repairing or modification in the existing system.

32. Draw a diagram to show all the phases of SDLC.


Ans:.
Defining

Planning

Feasibility
Study

Analysis

Requirement
Engineering

Design

Coding

Testing

Implementation

Maintenance

33. What is SDLC? Explain it in detail (Long Question)


Ans: combine the answers of Q # 2,3, 22 to 32.

14 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 3: Object Oriented Programming in C++ - MCQs
1. Which of the following is ignored during program execution?
(a) Reserved word (b) Constants (c) Comment (d) Constant qualifier

2. What is the range of unsigned short integer?


(a) -2147483648 to +2147483647 (b) 0 to 4294967295
(c) -32768 to +32767 (d) 0 to 65535

3. In C++ the expression sum= sum + n can also be written a:


(a) sum += n (b) sum = n++ (c) sum =+ n (d) n += sum

4. Which of the following is equal to operator?


(a) += (b) = = (c) = (d) = +

5. Which of the following is an arithmetic operator?


(a) && (b) % (c) <= (d) ++

6. Which of the following operator is used to form compound condition?


(a) Arithmetic (b) Relational (c) Logical (d) Assignment

7. The number of bytes reserved for variable of data type “float” is :


(a) 2 (b) 4 (c) 6 (d) 8

8. How cursor is moved to the next tabular position for printing data?
(a) By using reserved word (b) By using manipulator
(c) By using escape sequence (d) By using header file

9. Which of the following data type occupies a space of 4 Bytes.


(a) int (b) long int (c) float (d) All of these

10. ____ generates a beep program’s output..


(a) \a (b) /a (c) \b (d) /b

11. / is printed in cout by_______.


(a) \\ (b) // (c) \ / (d) None of these

12. \\ in C program is used:


(a) to print \ (b) for comments (c) both A and B (d) None of these

13. Every instruction in C ends with:


(a) colon (b) semi-colon (c) Period (d) comma

14. The instructions that are given to the compiler before the beginning of actual program are:
(a) C statements (b) Linking instructions (c) Preprocessor Directives (d) C instructions

15. The extension of application file is


(a) .app (b) .h (c) .obj (d) .exe

15 Computer Science XII (By: Prof. Noman Qadeer)


16. The extension of C++ source program is
(a) .c++ (b) .cpp (c) .obj (d) .src

17. Which of the following escape sequence is used to erase a character left to the cursor position?
(a) \b (b) \f (c) \del (d) \c

18. Computer programs are also known as:


(a) Applications (b) Software (c) Procedures (d) Algorithm

19. Which of the following is correct precedence order?


(a) ^ / * + - (b) + - * / (c) / * + - (d) / * + - ^

20. An IDE typically consists of _____


(a) Text Editor (b) Compiler (c) Linker (d) All of these

21. The processing of converting source code into object code is called ________
(a) Debugging (b) Compiling (c) Linking (d) None of these

22. conio stands for __________.


(a) Character input output (b) Console input output
(c) Complex input output (d) Common input output

23. What happens when the result of calculation exceeds the capacity of datatype?
(a) Syntax error (b) Logical error (c) overflow (d) math error

24. Variables are created in_______


(a) RAM (b) ROM (c) Hard Disk (d) all

25. C program ends with:


(a) ; (b) getch() (c) getche() (d) }

26. _____ is not a delimiter


(a) : (b) ; (c) ? (d) ,

27. Precedence determines which operator_______.


(a) is most important (b) is used first (c) is faster (d) operates on the largest number

28. Which of the following is equal to (a>=b)?


(a) a<b (b) !(a<b) (c) a>b (d) !a<b

29. Which of the following is equal to 50 % 13 % 3?


(a) 0 (b) 1.2 (c) 2 (d) 11.54

30. What defines the rules of valid statements in programming?


(a) Compiler (b) Interpreter (c) Syntax (d) Semantics

ANSWER KEY: 1.C-2.D-3.A-4.B-5.B-6.C-7.B-8.C-9.D-10.A-11.D-12.A-13.B-14.C-15.D-16.B-17.A-18.B-19.C-


20.D-21.B-22.B-23.C-24.A-25.D-26.C-27.B-28.B-29.C-30.C

16 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 3: Object Oriented Programming in C++
SHORT QUESTIONS
1. Define reserved words and give three examples.
Ans: Reserved words are the words used in programming languages which have a special meaning.
These are defined by the language and are also known as keywords. Some of the reserved words
are int, float, break, continue, for, while etc.

2. What is the purpose of using header file in program?


Ans: Header files are used in a program for adding the definitions of built-in functions used in that
program. Header files contain the definitions of library functions and have extension of .h. These
are included by pre-processor directive #include.

3. State whether the following variable names are valid or invalid. State the reasons for invalid
variable names.
Ans:
Variable Validity Reason for invalid name
Name
a123 Valid
_abcd Valid
5hml Invalid Variable name cannot start with a number
tot.al Invalid Special character like “.” Are not allowed
f3ss1 Valid
c$avg Invalid Special character like “$” Are not allowed
net_weight Valid
cout Invalid Variable name cannot be a keyword
max marks Invalid Spaces are not allowed in a variable name.
Noman Valid
fG_456 Valid
0519280605 Invalid Variable name cannot start with a number

4. Why escape sequences are used? Give three examples with explanation.
Ans: Escape sequences are the characters used in cout statement for adding special effects in output.
The control character which cannot be typed through keyboard are expressed as escape sequence.
An escape sequence consists of two characters i.e. \ followed by any character. Some of the escape
sequences are given below
Escape Sequence Purpose
\a Alert- Produces an alert sound (beep)
\b Backspace- Move cursor one character backward (to the left)
\n New Line- Issues a new line
\r Carriage Return- Moves cursor to the beginning of line.
\t Tab- Moves cursor to the next horizontal tabular position
\\ Back Slash- Writes a \
\’ Single quote- Writes a ‘
\” Double quote- Writes a “

17 Computer Science XII (By: Prof. Noman Qadeer)


5. Differentiate between relational and logical operators.
Ans:
Relational Operators Logical Operators
Relational operators are used to compare two Logical operators are used to make compound
values and form a condition conditions
Their input may be any value but they give Their input as well as output is always 0 or 1
output as 0 or 1
They have higher priority They have lower priority
These all are binary operators These are unary as well as binary
These are <, <=, >, >=, ==, != These are !, &&, ||

6. What will be the output of the following statements?


Statement Output
cout<<”17/2 is equal to”<<17/2 17/2 is equal to 8.5
cout<<”10.0/4 is equal to”<<10.2/4 10.0/4 is equal to 2.55
cout<<”40/5%3*7 is equal to”<< 40/5%3*7 40/5%3*7 is equal to 14
cout<<”25%7 is equal to”<< 25%7 25%7 is equal to 4

7. Evaluate the following integer expressions.


Ans: a. 3+4*5 b. 4*5/10+8 c. 3*(2+7*4) d. 20-6/2+3 e. (20-2)/(6+3)
3+4*5 4*5/10+8 3*(2+7*4) 20-6/2+3 (20-2)/(6+3)
3+20 20/10+8 3*(2+28) 20-3+3 18 / 9
23 Ans 2+8 3*30 17+3 2 Ans
10 Ans 90 Ans 20 Ans

8. Evaluate the following expressions that have integer and floating-point data types.
Ans: a. 10.0+15/2+4.3 b. 10.0+15.0/2+4.3 c. 4/6*3.0+6
10.0+15/2+4.3 10.0+15.0/2+4.3 4/6*3.0+6
10.0+7.5+4.3 10.0+7.5+4.3 0.667*3.0+6
17.5+4.3 17.5+4.3 1.999+6
21.8 Ans 21.8 Ans 7.99999 Ans

9. What will be the output of following program?


#include<iostream.h>
#include<conio.h>
void main (void)
{
int n1, n2, tot;
Output
n1=13;
n2=20; The total of 13 and 20 is 33
tot=n1+n2
cout<<”The total of”<<n1<<” and ”<<n2<<” is “<<tot<<endl;
getch();
}

18 Computer Science XII (By: Prof. Noman Qadeer)


10. What will be the output of following program?
#include<iostream.h>
#include<conio.h> Output
void main (void) The initial value of n is 10
{ The value of n is now 11
int n;
The value of n is now 13
n=10;
cout<<”The initial value of n is ”<<n <<endl; The value of n is now 12
n++;
cout<<”The value of n is now ”<<n <<endl;
n++; n++;
cout<<”The value of n is now ”<<n <<endl;
n--;
cout<<”The value of n is now ”<<n <<endl;
getch();
}
11. What is variable?
Ans: A variable is a memory location which can store data in program and its value can be changed as
and when required. It is identified by assigned name and can store a particular type of data as
defined by its datatype. e.g. int a, b, c; Here a, b and c are variables of type int.
12. Define the rules for naming variables.
Ans: ● A variable name may have any number of characters but only first 32 are significant.
● Variable name may consist of upper case and lower case le ers, digits and underscore “_”.
● It must start with an alphabet or underscore “_”.
● No special characters are allowed in variable name except underscore “_”.
● No spaces are allowed however underscore “_” is used to increase readability e.g. Tot_Marks
● No key words are allowed as variable name
●Upper case and Lower case le ers are considered as different. E.g. “a” and “A” are different variables.
13. What are data types? Define all.
Ans: Datatypes are declarations of variables for storing various types and ranges of data, Datatypes are
represented by respective keywords as defined in language. In C++, data types are as following:

No of
Data Type Range Description
Bytes
1 character out of 255 of ASCII
Char 1 Stores character data
table
Int 4 -2147483648 to +2147483648 Stores numeric data of integer type
unsigned int 4 0 to 4294967295 Stores numeric data of integer type without sign
short int 2 -3276 to +32767 Stores numeric data of integer type
unsigned short int 2 0 to 65535 Stores numeric data of integer type without sign
long int 4 -2147483648 to +2147483648 Stores numeric data of integer type
unsigned long int 4 0 to 4294967295 Stores numeric data of integer type without sign
Stores numeric data of decimal type with 6 digits of
Float 4 -3.4-38 to 3.4-38
precision
Stores numeric data of decimal type with 15 digits
Double 8 -1.7-308 to 1.7-308
of precision

19 Computer Science XII (By: Prof. Noman Qadeer)


14. Why type casting is used? Name its types.
Ans: Type casting is used to convert data of one type to another type. It is the process which converts
the type of data during program execution. There are two types of type casting i.e. Implicit Type
Casting (done automatically by system) and Explicit Type Casting (done by using an operator by
user).
15. Define implicit type casting with example.
Ans: Implicit typecasting automatically converts a data type to another without using any operator. It is
done by system.
For example, a =7/2 will be 3 in integer but it will automatically performs division as 7.0/2.0 and
answer will be 3.5.

16. Define explicit type casting with example.


Ans: Explicit typecasting converts a data type to another by using any operator. It is done by
programmer.
For example, int a=9, b=2 and c=a/b. The result will be of int type to perform typecasting we need
to specify the new data type i.e. c=(float) a/b. Now the floating point result 4.5 will be stored in c.

17. What is delimiter?


Ans: The symbols used in C++ statements which define the boundaries of some statement or structures
are called delimiters. These are { } [ ] ( ) < > , . ; : ‘ “ etc. These may be compared with the punctuation
marks in other languages.

18. Define endl and setw manipulators with example of each.


Ans: endl: endl stands for End Line. It is used with cout to move cursor to the beginning of next line. It
works same as \n. It is defined in iostream.h.
setw: setw stands for Set Width. It is used set the width of numeric or string fields, If the value to
be printed is less than the specified width than remaining columns are left blank on left side. Setw
can be used by including iomanip.h. Let, a=92, b=6, c=102
Without setw Output With setw Output

cout<<a 92 cout<<setw(4)<<a 92
cout<<b 6 cout<<setw(4)<<b 6
cout<<c 102 cout<<setw(4)<<c 102

19. What do you mean by precedence of operators? Show the precedence of all operators used in
C++.
Ans: Precedence of operator means the order in which operators are used. It determines which
operator will be used first. Following is the order of precedence of all operators.
Precedence Operator Description
1 * , / ,% Arithmetic Operator (High priority)
2 +,- Arithmetic Operator (Low priority)
3 < , <= , > , >= Relational Operator of Less than and Greater than etc.
4 == , != Relational Operator of Equal to and Not Equal to
5 ! Logical Operator NOT
6 && Logical Operator AND
7 || Logical Operator OR
8 =, *=, /=, %=, +=, -= Assignment operators

20 Computer Science XII (By: Prof. Noman Qadeer)


20. What is Program?
Ans: A well-defined set of instructions given to computer system in a computer-based language to
perform a specific task that tells computer what to do and how to do, is known as computer
program.

21. What are comments? Define their types. (Types to be defined if it is a part of long question)
Ans: Comments are the non-executable statements which are ignored by the compiler during
translation. These are used by the programmer for enhancing the readability of code however
computer does not use these statements. There are two types of comments as given below.
Single Line Comments ( // ): These comments convert the text into comments up to the end of line.
E.g. cout<<”\n I LOVE PAKISTAN”; // prints a message
In this line the text after // is a comment.
Multiple Line Comments ( /* ….. */ ): These comments convert the text into comments which is
between /* and */. This text may be a part of line or may be multiple lines.
E.g. cout<<”\n I LOVE PAKISTAN”; /* prints a message
And is an example of multiple line comments*/
In this line the text between /* and */ is a comment.

22. What are constants? Name their types.


Ans: The values which cannot be changed during the program execution are called constants. These
may be defined by programmer in memory by using #define or the values by default. By default,
there are three types of constants,
○ Character Constants (e.g. ‘a’, ‘n’)
○ String Constants (e.g. “NOMAN”, “PAKISTAN”)
○ Numeric Constants (e.g. 3, 7.5).
23. Define Character constants.
Ans: The characters which are written in single quotation mark are called character constants. These
are written as ‘a’, ‘n’, ‘8’, ‘*’ etc. The character constant may be any of the 255 characters of ASCII
table.
24. Define Constant qualifier.
Ans: Constant qualifier in C++ is const, it defines a variable whose value cannot be changed during
program execution. When const is used with a variable, it will no longer remain a variable. Its syntax
is:
const datatype variable name = constant
e.g. const int pi=3.142;
25. Define cout and cin statements.
Ans: cout: cout is an output statement used to display a message on screen. It uses escape sequences
for screen formation and can display string constants and variables.
e.g. cout<<”The number is “<<n.
Here first part is string constant and will be displayed as it is while second part (n) is variable whose
value will be displayed
cin: cin is an input statement used to read values from keyboard.
Its syntax is: cin>>variable
e.g. cin>>a >>b; It will read two values from keyboard and will save in variables a and b.

21 Computer Science XII (By: Prof. Noman Qadeer)


26. Define the following functions: getch() getche() gets() puts()
Ans: getch(): getch stands for Get Character. It reads a single character from keyboard without
displaying on screen. Its syntax is ch = getch() where ch is a variable of type char.
getche(): getche stands for Get Character with Echo. It reads a single character from keyboard as
well as displays on screen. Its syntax is ch = getche() where ch is a variable of type char.
gets(): gets stands for Get String. It reads a string from keyboard. Its syntax is gets(str) where str is
a string variable.
puts(): puts stands for Put String. It displays a string on screen. Its syntax is puts(str) where str is a
string variable.

27. What are operators? Name their types in C++.


Ans: Operators are the symbols which tell the computer to perform a specific computing task. Following
are the types of operators:
● Arithme c Operators ● Rela onal Operators ● Logical Operators
● Assignment Operators ● Increment / Decrement Operators ● Ternary Operator

28. What are relational operators?


Ans: The operators used to compare two values are known as relational operators. These are used to
make conditions. They return 0 if comparison is false or 1 otherwise. These are <, <=, >, >=, ==, !=.

29. What are logical operators?


Ans: The operators used to make compound conditions are known as logical operators. These use the
0 or 1 returned by relational operators and return 0 if result is false or 1 otherwise. !, &&, ||

! (NOT) && (AND) || (OR)


Input Output Inputs Output Inputs Output
0 1 0 0 0 0 0 0
1 0 0 1 0 0 1 1
1 0 0 1 0 1
1 1 1 1 1 1

30. Define pre increment/decrement and post increment / decrement with the help of example.
Ans: Increment / Decrement operators are unary operators used to increase / decrease the value of an
integer variable by 1. These may be used in two forms i.e. Prefix or Postfix.
Prefix Increment: The ++ operator is written before variable. Let n is a variable. And n=5. If we use
a = ++n, then it will first apply ++ then will use the new value of n, hence 6 will be moved to a.
Postfix Increment: The ++ operator is written after the variable. Let n is a variable. And n=5. If we
use a = n++, then it will first move the current value to a then will apply ++ to n, hence 5 will be
moved to a and new value of n will be 6.

31. What are assignment operators?


Ans: Assignments operators are used to assign the value of RHS to LHS. The quantity on LHS must be a
variable while on RHS it may be a variable, constant or an expression. There are categories of
assignment operators i.e. Simple assignment (=) and arithmetic assignment(+=, -=, *=, /=). = will
move the value to LHS while arithmetic assignment operator will perform arithmetic operation
between LHS and RHS and will store the result in LHS i.e. a+=b means a=a+b.

22 Computer Science XII (By: Prof. Noman Qadeer)


32. What is ternary / conditional operator?
Ans: A conditional operator is used to make a decision. It is also known as ternary operator because it
is operated on more than one operands. Its syntax is: (condition) ? <if exp is true> : <if exp is false>
e.g. (X>Y)? cout<<X : cout<<Y; (it will compare X and Y and prints X if it is greater or Y otherwise)
33. What are identifiers? Name their types.
Ans: Identifiers are the names of any item in a program, it may be a function name, variable name,
header file’s name or datatype name etc. There are two types of identifiers:
●Standard Iden fiers: Defined by language i.e. keywords
● User defined iden fiers: Defined by user i.e. variable names, UDF names etc.
34. Write a program that inputs two numbers and print their sum, average and product.
#include<iostream.h>
#include<conio.h>
void main (void)
{
int a, b, sum, prod;
float avg;
cout<<”\n Enter two numbers”;
cin >>a >>b;
sum = a+b;
prod = a * b;
avg = sum / 2;
cout<<”The sum of “<<a <<” and ”<<b << “is “<<sum <<endl;
cout<<”The product of “<<a <<” and ”<<b << “is “<<prod <<endl;
cout<<”The average of “<<a <<” and ”<<b << “is “<<avg <<endl;
getch();
}
35. Write a program that inputs length and breadth of a rectangle and prints its area.
#include<iostream.h>
#include<conio.h>
void main (void)
{
int l, b, area;
cout<<”\n Enter length and breadth of rectangle”;
cin >>l >>b;
area = l * b;
cout<<”\n The Area of given rectangle is “<<area;
getch();
}
36. Write a program that prints a message “I LOVE PAKISTAN”.
#include<iostream.h>
#include<conio.h>
void main (void)
{
clrscr();
cout<<”\n I LOVE PAKISTAN”;
getch();
}

23 Computer Science XII (By: Prof. Noman Qadeer)


37. Write a program that reads temperature in Fahrenheit and prints its equivalent temperature in
Celsius. Using the formula C=5/9 (f-32)
#include<iostream.h>
#include<conio.h>
void main (void)
{
float C, F;
clrscr();
cout<<”\n Enter temperature in Fahrenheit…”;
cin >>F;
C=5/9 * (F-32);
cout<<”\n”<<F <<”Fahrenheit = ” <<C <<” Celsius”;
getch();
}

38. Write a program that reads temperature in Fahrenheit and prints its equivalent temperature in
Celsius. Using the formula F=9/5 C+32
#include<iostream.h>
#include<conio.h>
void main (void)
{
float C, F;
clrscr();
cout<<”\n Enter temperature in Celsius…”;
cin >>C;
F=9/5 * C+32;
cout<<”\n”<<C <<”Celsius = ” <<F <<”Fahrenheit”;
getch();
}

39. Write a program that inputs maximum and obtained marks of a student and find his percentage.
#include<iostream.h>
#include<conio.h>
void main (void)
{
int obt_mrx, max_mrx;
float per;
clrscr();
cout<<”\n Enter Obtained Marks…”;
cin >>obt_mrx;
cout<<”\n Enter Maximum Marks…”;
cin >>max_mrx;
per = obt_mrx / max_mrx * 100;
cout<<”\n Your Percentage is ”<<per <<”%”;
getch();
}

24 Computer Science XII (By: Prof. Noman Qadeer)


40. Write a program that inputs basic pay of an employee and find his net pay by adding following
allowances:
House Rent 40% of basic pay, Medical Allowance 15% of basic pay, Conveyance allowance
FIX at Rs. 5000/-

#include<iostream.h>
#include<conio.h>
void main (void)
{
int b_pay, ca;
float hr, med, net;
clrscr();
cout<<”\n Enter Basic Pay…”;
cin >>b_pay;
hr = b_pay * 40 / 100;
med = b_pay * 15 / 100;
ca = 5000;
net = b_pay + hr + med + ca;
cout<<”\n Net Pay = Rs. ” <<net;
getch();
}

41. Write a program to print given output.


#include<iostream.h> OUTPUT
#include<conio.h> 1
void main (void) 2
{ 3
clrscr(); 4
cout<<”1 \n\t 2 \n\t\t 3 \n\t 4\n 5”; 5
getch();
}

42. Write a program to print given output.


#include<iostream.h> OUTPUT
#include<conio.h> Name: ABC
void main (void) Class: XI-ICS
{
clrscr();
cout<<”Name:\t ABC”;
cout<<”\n Class:\t XI-ICS”;
getch();
}
43. Define Pre-Processor Directive.
Ans: Preprocessor directive is an instruction for compiler. It is written before actual program. Before
translating a program into machine equivalent code, C-compiler carries out preprocessor
directive. It is represented by # sign. Most commonly used preprocessor directives are #include
and #define.

25 Computer Science XII (By: Prof. Noman Qadeer)


44. Write a program to input radius of a circle and calculate its area.
#include<iostream.h>
#include<conio.h>
void main (void)
{
int r;
float area;
clrscr();
cout<<”Enter radius of circle…”;
cin>>r;
area = 22 / 7 * r * r;
cout<<”Area of given circle is ”<<area;
getch();
}

45. Write a program to input distance in miles and convert into km (where 1mile = 1.6km).
#include<iostream.h>
#include<conio.h>
void main (void)
{
int m;
float km;
clrscr();
cout<<”Enter distance in miles….”;
cin>>m;
km = m * 1.6;
cout<<”\n “<<m <<” Miles = “ <<km <<” Kilometers”;
getch();
}

46. Write a program to input measurement of side of a cuboid and find its volume.
#include<iostream.h>
#include<conio.h>
void main (void)
{
int s, v;
clrscr();
cout<<”Enter measurement of a side of cuboid….”;
cin>>s;
v = s * s * s;
cout<<”\n Volume of given cuboid is “<<v;
getch();
}
47. Define main() function.
Ans: main() function is the building block of C-program which makes it executable. It is the first section
to be executed. Every executable code of C language must have main() function. Its definition is
surrounded by braces, { and }.
Practice all the programs given in book as examples and in practical notebook)

26 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 4: Control Structures- MCQs
1. How is single statement for loop terminated?
(a) with semi colon (b) with colon (c) with right brace (d) with a right bracket
2. Which is the best structure when there is one condition and multiple choices.
(a) if (b) if else (c) else if (d) switch case
3. How is multiple statement for loop terminated?
(a) with semi colon (b) with colon (c) with right brace (d) with a right bracket
4. What will be the output of following code?
int a=3, b=6;
if (a + b < 9)
cout<<a;
else
cout<<b;
cout<<a+b;
(a) 36 (b) 39 (c) 66 (d) 69
5. A case can be defined as _____
(a) An individual condition to test (b) A set of conditions to test
(c) A statement that includes break (d) All of these
6. Which programming structure skips some program statements?
(a) Serial (b) Conditional (c) Iterative d) None
7. If x=5 and y = 15, what will be the output of the expression x>y ? x*y : x+y?
(a) 5 (b) 15 (c) 20 (d) 75
8. Which of the following transfers control to the beginning of loop skipping the remaining statements?
(a) begin (b) reset (c) break (d) continue
9. How many control structures are there?
(a) 2 (b) 3 (c) 4 (d) 6
10. Which structure can be replaced by ternary operator? OR
Which of the following can be used to replace ternary operator?
(a) if (b) if else (c) else if (d) switch case
11. Which of the following can be used to replace switch statement?
(a) if-else (b) break (c) else if (d) while
12. A while loop is more appropriate to use than for loop when____.
(a) The loop body is to be executed at least once (b) When the number of iterations is known
(c) The program executes at least once (d) Termination condition occurs unexpectedly
13. A do-while loop is more appropriate to use when____.
(a) The loop body is to be executed at least once (b) When the number of iterations is known
(c) The program executes at least once (d) Termination condition occurs unexpectedly
14. A for loop is more appropriate to use when____.
(a) The loop body is to be executed at least once (b) When the number of iterations is known
(c) The program executes at least once (d) Termination condition occurs unexpectedly
15. What will be the output of x=(a>b)? a+b : a*b; if a = 5 and b = 10.
(a) 5 (b) 10 (c) 15 (d) 50

ANSWER KEY: 1.A-2.B-3.C-4.D-5.A-6.B-7.C-8.D-9.A-10.B-11.C-12.D-13.A-14.B-15.D

27 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 4: Control Structures
SHORT QUESTIONS
1. What are control structures?
Ans: Control structures are the programming constructs which control the flow of program. Following
are the types of program flow and corresponding control structure.
Type of Program Flow Type of Control Structure Structures in C++
No control structure is required
Sequential / Serial / Simple Flow, ---
as it is default flow of control
Conditional / Selective / Decisive If, if-else, else if, switch-
Condition Control Structures
Flow, case
for loop, while loop, do-
Iterative / Repetitive / Cyclic Flow Loops
while loop
2. Why control statements are used in a C++ programs?
Ans: Control statements are used to control the flow of program. i.e to repeat or skip one or more
statements. Control structure change the order of normal execution and transfer the control to the
desired statement out of sequence.
3. Define if statement.
Ans: if statement is a conditional control structure which has one condition and one choice i.e. it skips
one or more statements on the basis of condition. Its syntax is as follow
if (condition)
{
Block of statements to run if condition is true
}
4. Define if-else statement.
Ans: if statement is a conditional control structure which has one condition and two choices i.e. if
condition is true a block is executed and if condition is false another block is executed. Its syntax is
as follow
if (condition)
Block of statements to run if condition is true
else
Block of statements to run if condition is false
5. Define else if structure.
Ans: else if is s multiple choice structure which has multiple conditions for multiple choice. It checks more
than one logical condition and executes the corresponding block of statement or runs the else block
if all conditions are false. Its syntax is:
if (condition 1)
Block of statement-1
else if (condition 2)
Block of statement-2
:
:
else if condition n)
Block of statement-n
else
Block of statements-default

28 Computer Science XII (By: Prof. Noman Qadeer)


6. Write the syntax of else if structure.
Ans: if (condition 1)
Block of statement-1
else if (condition 2)
Block of statement-2
:
else if (condition n)
Block of statement-n
else
Block of statements-default
7. Define switch-case statement.
Ans: switch statement (or switch-case structure) is a multiple choice statement like else-if structure but
it is more flexible and faster. It inputs a value and matches with various cases having constant
values, if no case matches, it executes default block. Its syntax is:
switch (variable)
{
case constant value 1: Block of statements
break;
case constant value 2: Block of statements
break;
:
case constant value n: Block of statements
break;
default: Block of statements
}
8. Differentiate between if and if-else statements.
If statement if - else statement
It has one condition and one choice It has one condition and two choices
It does not run any statement if condition is false It runs else block if condition is false
It has only one KEY WORD i.e. if It has two KEY WORDS i.e. if and else
Its syntax is Its syntax is: if (condition)
if (condition) Block of statements-1
Block of statements to run if condition is true else
Block of statements-2
9. Differentiate between else if and switch structures.
else-if structure switch – case structure
It uses multiple decision expressions for It uses single decision expression for multiple
multiple choices choices
It tests for equality as well as for logical It tests only for equality expression
expression
It evaluates integer, character or logical type It evaluates only integer or character type
expressions expressions
It runs only one block following one expression It runs one case after another until break
statement is run
It uses three key words i.e. if, else, else if It uses four key words i.e. switch, case, break,
default
If all the conditions are false then last else block If all cases fail, it runs default block
is executed

29 Computer Science XII (By: Prof. Noman Qadeer)


10. What is the use of break in switch case structure?
Ans: break statement terminates the execution of case in switch statement. It runs one case after
another if break statement is not used.
11. What is the use of default in switch case structure?
Ans: default is used in switch structure after all cases, if no case matches, it default block is run. It is at
the end of structure therefore it does not require break statement to be used after it.
12. Explain the purpose of switch statement with syntax and one example. (Long Question).
Ans: switch statement (or switch-case structure) is a multiple choice statement like else-if structure but
it is more flexible and faster. It inputs a value and matches with various cases having constant
values, if no case matches, it executes default block. It uses single decision expression for multiple
choices and tests only for equality expression.
Its syntax is:
switch (vaiable)
{
case constant value 1: Block of statements
break;
case constant value 2: Block of statements
break;
:
case constant value n: Block of statements
break;
default: Block of statements
}
Example:
int d;
cout<<”\n Enter Day Number of Week”;
cin>> d;
switch (d)
{
case 1: cout<<”\n MONDAY”;
break;
case 2: cout<<”\n TUESDAY”;
break;
case 3: cout<<”\n WEDNESDAY”;
break;
case 4: cout<<”\n THURSDAY”;
break;
case 5: cout<<”\n FRIDAY”;
break;
case 6: cout<<”\n SATURDAY”;
break;
case 7: cout<<”\n SUNDAY”;
break;
default: cout<<”\n INVALID INPUT”;
}

30 Computer Science XII (By: Prof. Noman Qadeer)


13. Define conditional operator
Ans: Conditional operator is also known as ternary operator as it has more than two operands. It is used
to check conditions and run one of two choices on the basis of condition. It is similar to if-else
structure. It can not only execute a choice but can return its value as well.
Its syntax is: (condition) ? Choice for TRUE : Choice for False
OR var = (condition) ? expression for TRUE : Expression for False
Example: x= (a > b)? a+b : a*b; (if condition is true x will store a+b, otherwise a*b)
14. What is loop?
Ans: Loop is a repetitive control structure it repeats one or more statements for a finite number of times.
In C++, there are three looping structures i.e. for, while and do-while.
15. Define “for” loop
Ans: for loop is a counter loop which is used when number of iterations are known in advance. It is
controlled by a integer variable which is also known as loop counter.
Its syntax is: for(initialization; condition; increment/ decrement)
Body of loop
16. Define working of “for” loop
Ans: Syntax: for(initialization; condition; increment/ decrement)
Body of loop
Firstly the expression at initialization step is executed to move starting value to counter variable.
Then expression for condition is evaluated and if it is true, loop body is executed, after loop body
counter variable is incremented or decremented. After inc/dec value in variable is again tested and
loop body is executed. This process continues till condition is true. Loop terminates if condition is
false.
17. Define while loop.
Ans: while loop is a pre-test conditional loop which repeats zero or more time, as long as the condition is
true. It is used when number of iterations is not known in advance.
Its syntax is: while (condition)
Loop body
18. Differentiate between for and while statements.
Ans:
for loop while loop
It is a counter loop It is a conditional loop
It is used when number of iteration is known at It is used when number of iteration is not
the time of programming known at the time of programming
It is controlled by a int type variable It may be controlled by any type of variable
Its syntax is: Its syntax is:
for(initialization; condition; inc/ dec) while (condition)
Body of loop Loop body

19. Define do-while loop.


Ans: do-while is a post-test conditional loop which runs one or more times. Even if the condition is false,
it runs at least once. Its syntax is: do
{
Loop body;
} while (condition);

31 Computer Science XII (By: Prof. Noman Qadeer)


20. Differentiate between while and do while loops
Ans:
while loop do-while loop
It is a pre-test loop It is a post-test loop
It runs ZERO or more times It runs ONE or more times
Semicolon is not placed after while condition Semicolon is placed after while condition
It uses only on keyword i.e. while It uses two keywords i.e. do and while
Its syntax is: Its syntax is: do
while (condition) {
Loop body Loop body;
} while (condition);
21. Define break statement? OR What is the use of break statement in C++ programs.
Ans: break statement is used to break any structure in a program unexpectedly before its normal
completion. It is usually used inside a conditional structure to break loops or in switch statement to
terminate the case.
22. Define continue statement? OR What is the use of break statement in C++ programs.
Ans: continue is used to transfer control to the beginning of loop skipping the remaining statements. It
is usually used inside a conditional structure.

23. Define exit() function. OR What is the use of exit() function in C++ programs.
Ans: exit() is used to terminate a C++ program before its normal termination and exit to operating
system. It is defined in stdlib.h header file. Its syntax is: exit(value);
Value may be 0 or 1. 0 is used to exit the program without error and 1 to exit with error.
24. What do you mean by nested loop? Give one example.
Ans: Loop inside another loop is called nested loop. For every iteration of outer loop, inner loop runs its
all iterations.
Example: for(int i = 1; i <= 5; i++) OUTPUT
{
1 2 3 4 5
for(int j = 1; j <= 5; j++)
1 2 3 4 5
cout<<j;
1 2 3 4 5
cout<<”\n”;
1 2 3 4 5
}
1 2 3 4 5
25. Write the following code using while loop:
sum=0;
for(k=20; k<100; k=k+2)
sum = sum + k;
cout<<”\n Sum = “<<sum;
Ans: sum=0;
k=20;
while(k<100)
{
sum = sum + k;
k=k+2;
}
cout<<”\n Sum = “<<sum;

32 Computer Science XII (By: Prof. Noman Qadeer)


26. Write the following code using switch statement to produce the same output:
if(choice= = 1)
cout<<”\n Sum = “<<x+y;
else if(choice = = 2)
cout<<”\n Product = “<<x*y;
else
cout<<”\n Average = “<<(x+y)/2;
Ans:
switch(choice)
{
case 1: cout<<”\n Sum = “<<x+y;
break;
case 2: cout<<”\n Product = “<<x*y;
break;
default:
cout<<”\n Average = “<<(x+y)/2;
}

27. What will be the output of following code?


int k, sum;
k=1; sum=0;
while(k<10)
{
sum = sum + k;
cout<”\n” <<k <<”\t” <<sum;
k=k+2;
}

Ans: The output will be:


1 1
3 4
5 9
7 16
9 25

28. What will be the output of following code?


int a,b,c;
a=0; b=1; c=2;
a = b+c;
b = ++a;
c = b++;
cout<”\n a =” <<a <<” , b = ” <<b <<” , c = ” <<c;

Ans: The output will be:


a = 4, b = 5, c = 4

33 Computer Science XII (By: Prof. Noman Qadeer)


29. Write the nested loops that will print the following patterns
12345 for(in i = 5; i >= 1; i--)
1234 {
123 for(int j=1; j <= i; j++)
12 cout<<j;
1 cout<<”\n”;
}
__________________________________________________________________________________
12345 for(in i = 1; i <= 5; i++)
2345 {
345 for(int j=i; j <= 5; j++)
45 cout<<j;
5 cout<<”\n”;
}
__________________________________________________________________________________
1 for(in i = 1; i <= 5; i++)
12 {
123 for(int j=1; j <= i; j++)
1234 cout<<j;
12345 cout<<”\n”;
}
__________________________________________________________________________________
54321 for(in i = 5; i >= 1; i--)
4321 {
321 for(int j=i; j >= 1; j--)
21 cout<<j;
1 cout<<”\n”;
}
__________________________________________________________________________________
54321 for(in i = 1; i <= 5; i++)
5432 {
543 for(int j=5; j >= i; j--)
54 cout<<j;
5 cout<<”\n”;
}
__________________________________________________________________________________
5 for(in i = 5; i >= 1; i--)
54 {
543 for(int j=5; j >= i; j--)
5432 cout<<j;
54321 cout<<”\n”;
}
__________________________________________________________________________________
1 for(in i = 1; i <= 5; i++)
21 {
321 for(int j=i; j >= 1; j--)
4321 cout<<j;
54321 cout<<”\n”;
}

34 Computer Science XII (By: Prof. Noman Qadeer)


* for(in i = 1; i <= 5; i++)
** {
*** for(int j=1; j <= i; j++)
**** cout<<” * ”;
***** cout<<”\n”;
}
__________________________________________________________________________________
***** for(in i = 5; i >= 1; i--)
**** {
*** for(int j=1; j <= i; j++)
** cout<<” * “;
* cout<<”\n”;
}
30. Write a program to input a number and print its table using while loop.
#include<iostream.h>
#include<conio.h>
int main ( )
{
int n, i;
clrscr();
cout<<”Enter a number….”;
cin>>n;
i =1;
while(i <= 10)
{
cout<<”\n “<<n <<” x “ <<i <<” = “ << n*i;
i++;
}
getch();
return 0;
}

31. Write a program to input a number and print its table using for loop.
#include<iostream.h>
#include<conio.h>
int main ( )
{
int n, i;
clrscr();
cout<<”Enter a number….”;
cin>>n;
for(i =1; i <= 10; i++)
cout<<”\n “<<n <<” x “ <<i <<” = “ << n*i;
getch();
return 0;
}

35 Computer Science XII (By: Prof. Noman Qadeer)


32. Write a program to input a number and find whether it is prime or composite.?
#include<iostream.h>
#include<conio.h>
int main ( )
{
int n, i;
clrscr();
cout<<”Enter a number….”;
cin>>n;
for (i =2;i < n; i++)
{
if(n % i = = 0)
{
cout<<”\n It is a COMPOSITE number”;
break;
}
}
if( n = = i)
cout<<”\n It is a PRIME number”;
getch();
return 0;
}

33. Write a program to input a character and find whether it is upper-case or lower-case.
#include<iostream.h>
#include<conio.h>
int main ( )
{
char ch;
clrscr();
cout<<”Enter an alphabet….”;
ch=getche();
if(ch >= ‘a’ && ch <= ‘z’)
cout<<”\n it is a LOWER CASE letter”;
else if(ch >= ‘A’ && ch <= ‘Z’)
cout<<”\n it is an UPPER CASE letter”;
else
cout<<”\n It is not an alphabet”;
getch();
return 0;
}

36 Computer Science XII (By: Prof. Noman Qadeer)


34. Write a program to input marks of a student and determine whether he is pass or fail.
#include<iostream.h>
#include<conio.h>
int main ( )
{
Int m;
clrscr();
cout<<”Enter marks….”;
cin>>m;
if(m >= 33)
cout<<”\n PASS”;
else
cout<<”\n FAIL”;
getch();
return 0;
}
35. Write a program to input a number and show whether it is negative, positive or zero.
#include<iostream.h>
#include<conio.h>
int main ( )
{
int n;
clrscr();
cout<<”Enter a number….”;
cin>>n;
if(n > 0)
cout<<”\n it is POSITIVE”;
else if(n < 0)
cout<<”\n it is NEGATIVE”;
else
cout<<”\n It is ZERO”;
getch();
return 0;
}
36. Write a program to input a phrase and calculate total number of character typed.
#include<iostream.h>
#include<conio.h>
int main ( )
{
char ch; int n = 0;
clrscr();
cout<<”Enter aphrase….\n\n\n”;
while(ch = getche( ) != ‘\r’)
n++;
cout<<”\n You typed ”<<n <<”letters”;
getch();
return 0;
}

37 Computer Science XII (By: Prof. Noman Qadeer)


37. Write a program to input a phrase and calculate total number of lower-case letters typed.
#include<iostream.h>
#include<conio.h>
int main ( )
{
char ch; int lc = 0;
clrscr();
cout<<”Enter aphrase….\n\n\n”;
while(ch = getche( ) != ‘\r’)
if(ch >= ‘a’ && ch <= ‘z’)
lc++;
cout<<”\n You typed ”<<lc <<”lower case letters”;
getch();
return 0;
}
38. Write a program to input a phrase and calculate total number of upper-case letters typed.
#include<iostream.h>
#include<conio.h>
int main ( )
{
char ch;
int uc = 0;
clrscr();
cout<<”Enter aphrase….\n\n\n”;
while(ch = getche( ) != ‘\r’)
if(ch >= ‘A’ && ch <= ‘Z’)
uc++;
cout<<”\n You typed ”<<uc <<”upper case letters”;
getch();
return 0;
}
39. Write a program that reads a number and prints its square if number is greater than 10 or its
cube if number otherwise.
#include<iostream.h>
#include<conio.h>
int main ( )
{
int n;
clrscr();
cout<<”Enter a number….”;
cin>>n;
if(n > 10)
cout<<”\n Square of” <<n <<”is” <<n*n;
else
cout<<”\n Cube of” <<n <<”is” <<n*n*n;
getch();
return 0;
}

38 Computer Science XII (By: Prof. Noman Qadeer)


40. Write a program to read three numbers and find the largest using (a) else if (b) conditional operator.
#include<iostream.h>
#include<conio.h>
int main ( )
{
int a, b, c;
clrscr();
cout<<”Enter three different numbers….”;
cin>>a >>b >>c;
if(a>b && a>c)
cout<<”\n The largest number is ” <<a; OR using Conditional Operator
else if(b>a && b>c) cout<<”The largest number is “;
cout<<”\n The largest number is ” <<b; (a>b&&a>c)?cout<<a: (b>a&&b>c)? cout<<b: cout<<c;
else
cout<<”\n The largest number is ” <<c;
getch();
return 0;
}
41. Write a program to input a number and calculate its factorial.
#include<iostream.h>
#include<iostream.h>
#include<conio.h>
#include<conio.h>
int main ( )
int main ( )
{
{
int n, i, f=1;
int n, i, f=1; OR
clrscr();
clrscr();
cout<<”Enter a number….”;
cout<<”Enter a number….”;
cin>>n;
cin>>n;
i =1;
for(i =1; i <= n; i++)
while (i <= n)
f=f*i;
{
cout<<”\n Factorial of “ << n <<” is “ <<f;
f=f*i;
getch();
i++;
return 0;
}
}
cout<<”\n Factorial of “ << n <<” is “ <<f;
getch();
return 0;
}
42. Write a program to print all even numbers from 2 to 100
#include<iostream.h>
#include<conio.h>
int main ( )
{
int i;
clrscr();
for(i =2; i <= 100; i= i+2)
cout<<”\t” << i;
getch();
return 0;
}

39 Computer Science XII (By: Prof. Noman Qadeer)


43. Write a program to print all odd numbers from 1 to 99 skipping those which are divisible by 7.
#include<iostream.h>
#include<conio.h>
int main ( )
{
int i; clrscr();
for (i =1;i <= 99; I = i+2)
if(i % 7 ! = 0)
cout<<” “ << i;
getch(); return 0;
}
44. Write a program to find sum of first 10 natural numbers.
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
int main ( ) int main ( )
{ {
int i, sum=0; OR int i, sum=0;
clrscr(); clrscr();
for(i =1; i <= 10; i++) i =1;
sum = sum + i; while (i <= n)
cout<<”\n Sum = “ << sum; {
getch(); sum = sum + i;
return 0; i++;
} }
cout<<”\n Sum = “ << sum;
getch();
return 0;
}
45. Write a program to find product of first 10 natural numbers.
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
int main ( ) int main ( )
{ {
int i, prod=1; OR int i, prod=1;
clrscr(); clrscr();
for(i =1; i <= 10; i++) i =1;
prod = prod * i; while (i <= n)
cout<<”\n Product = “ << prod; {
getch(); prod = prod * i;
return 0; i++;
} }
cout<<”\n Product = “ << prod;
getch();
return 0;
}

40 Computer Science XII (By: Prof. Noman Qadeer)


46. Write a program to input basic pay and calculate the net pay of an employee in a firm. Net pay
can be calculated as Net Pay = Basic Pay + House Rent while house rent can be calculated as per
following table:
Basic Pay House Rent
Basic Pay < 30000 30% of Basic Pay
Basic Pay > 30000 and < 50000 35% of Basic Pay
Basic Pay > 50000 40% of Basic Pay
#include<iostream.h>
#include<conio.h>
int main ( )
{
int bp, hr, np;
clrscr();
cout<<”Enter Basic Pay….”;
cin>> bp;
if(bp<30000)
hr = bp *30/100;
else if(bp >= 30000 && bp <=50000)
hr = bp *35/100;
else if(bp > 50000)
hr = bp *40/100;
np = bp + hr;
cout<<” NET PAY = “ <<np;
getch();
return 0;
}
47. Write a program to produce table of equivalent temperature in both Fahrenheit and Celsius with
in increment of from 50 to 100 as given below ( = ( + ))
Fahrenheit Celsius
50 9.90
55 12.65
: :
: :
100 37.40
#include<iostream.h>
#include<conio.h>
int main ( )
{
int F, i; float C;
clrscr();
cout<<”Fahrenheit \t Celsius”<<endl;
for(F =50; F <= 100; F= F+5)
{
C = 5/9 * (F+32);
cout<<F <<”\t “ << C <<endl;
}
getch(); return 0;
}

41 Computer Science XII (By: Prof. Noman Qadeer)


48. Write a program to print the sum of following sequence using for loop.
Sum = 30 + 33 + 36 + 39 + . . . . . . . . . + 60
#include<iostream.h>
#include<conio.h>
int main ( )
{
int i, sum=0;
clrscr();
for(i =30; i <= 60; i= i+3)
sum = sum + i;
cout<<”\n Sum = “ << sum;
getch();
return 0;
}

49. Write a program to print the sum of following sequence using while loop.
Sum = 30 + 33 + 36 + 39 + . . . . . . . . . + 60
#include<iostream.h>
#include<conio.h>
int main ( )
{
int i, sum=0;
clrscr();
i =3;
while (i <= 60)
{
sum = sum + i;
i= i+3;
}
cout<<”\n Sum = “ << sum;
getch();
return 0;
}

50. Write a program to print all odd numbers from 1 to 99


#include<iostream.h>
#include<conio.h>
int main ( )
{
int i;
clrscr();
for(i =1; i <= 99; i= i+2)
cout<<”\t” << i;
getch();
return 0;
}

42 Computer Science XII (By: Prof. Noman Qadeer)


51. Write a program that inputs the coefficients a, b, c of a quadratic equation ax2 + bx + c = 0 and
find its solution set using the formula
±
=
Note that if − is zero then there is only one real solution, if it is greater than zero then
two real solutions and if it is less than zero then print NO REAL SOLUTIONS.

#include<iostream.h>
#include<conio.h>
#include<math.h>
int main ( )
{
int a, b, c, x1, x2;
float d;
clrscr();
cout<<\n Enter the coefficients a, b and c…….”;
cin >>a >>b >>c;
d = b*b -4*a*c;
if(d= = 0)
{
x1= -b / (2*a);
cout<<”\n x = { “ <<x1 << “ } “; // e.g. output will x= {2}
}
else if(d > 0)
{
x1= (-b + sqrt(d) ) / (2*a);
x2= (-b - sqrt(d) ) / (2*a);
cout<<”\n x = { “ <<x1 << “ , “ <<x2 <<” } “; // e.g. output will x= {2,3}
}
else
cout<<”\n NO REAL SOLUTION”;
getch();
return 0;
}
52. Write a program to print square of * using loop.

#include<iostream.h>
#include<conio.h>
int main ( ) OUTPUT
{ **********
int i; **********
clrscr(); **********
for(i =1; i <= 5; i= i++) **********
cout<<”**********\n”`; **********
getch();
return 0;
}

43 Computer Science XII (By: Prof. Noman Qadeer)


53. Write a program to input TWO numbers and calculate their GCD.
#include<iostream.h>
#include<conio.h>
int main ( )
{
int a, b, s, i;
clrscr();
cout<<\n Enter two numbers…….”;
cin >>a >>b;
if(a > b)
s = b;
else
s = a;
for (i=s; i > 1; i--)
if(a % i == 0 && b % i == 0)
{
cout<<”\n\t GCD = “<<i;
break;
}
if (i= = 1)
cout<<”\n\n\t\t THERE IS NO GCD”;
getch();
return 0;
}
54. Write a program to input TWO numbers and calculate their LCM.
#include<iostream.h>
#include<conio.h>
int main ( )
{
int a, b, g, i;
clrscr();
cout<<\n Enter two numbers…….”;
cin>>a >>b;
if(a > b)
g= a;
else
g= b;
for (i=g; i <= a*b; i++)
if(i % a == 0 && i % b == 0)
{
cout<<”\n\t LCM = “<<i;
break;
}
getch();
return 0;
}

44 Computer Science XII (By: Prof. Noman Qadeer)


55. Write a program to input marks of a student and calculate his grade as per following scheme
Marks Grade
80 to 100 A1
70 to <80 A
60 to <70 B
50 to <60 C
40 to <50 D
33 to <40 E
< 33 F
#include<iostream.h>
#include<conio.h>
int main ( )
{
int m;
clrscr();
cout<<\n Enter marks…….”;
cin>>m;
if(m >= 80 && m <= 100)
cout<<”\n A1 Grade”;
else if(m >= 70 && m < 80)
cout<<”\n A Grade”;
else if(m >= 60 && m < 70)
cout<<”\n B Grade”;
else if(m >= 50 && m <60)
cout<<”\n C Grade”;
else if(m >= 40 && m < 50)
cout<<”\n D Grade”;
else if(m >= 33 && m <40)
cout<<”\n E Grade”;
else if(m >= 0 && m <33)
cout<<”\n F Grade”;
else
cout<<”\n Invalid input i.e. Input marks must be from 0 to 100”
getch();
return 0;
}
56. Write a program to print counting from 1 to 100
#include<iostream.h>
#include<conio.h>
int main ( )
{
clrscr();
for(int i =1; i <=100; i= i++)
cout<<”\t” << i;
getch();
return 0;
}

45 Computer Science XII (By: Prof. Noman Qadeer)


57. Write a program to input a lower case letter and determine whether it is vowel or consonant.
#include<iostream.h>
#include<conio.h>
int main ( )
{
Char ch;
clrscr();
cout<<\n Enter a lower case letter…….”;
ch = getche();
if (ch >= ‘a’ && ch <= ‘z’)
switch(ch)
{
case ‘a’:
case ‘e’:
case ‘i’:
case ‘o’:
case ‘u’:
cout<<”\n VOWEL”;
break;
default:
cout<<”\n CONSONANT”;
}
else
cout<<”\n Invalid input i.e. You did not enter a lower case letter”;
getch();
return 0;
}

58. Write a program to print tables of all numbers from 2 to 20


#include<iostream.h>
#include<conio.h>
int main ( )
{
int n, i;
clrscr();
for(n=2; n <= 20; n++)
{
cout<<”\n\n TABLE OF “ <<n <<”\n\n”;
for(i =1; i <= 10; i++)
cout<<”\n “<<n <<” x “ <<i <<” = “ << n*i;
}
getch();
return 0;
}

46 Computer Science XII (By: Prof. Noman Qadeer)


59. Write a program to print first 10 natural numbers along with their factorial as following:
Number Factorial
1 1
2 2
3 6
: :
: :
10 3628800
#include<iostream.h>
#include<conio.h>
int main ( )
{
int n, i, f;
clrscr();
cout<<”\n Number \t Factorial\n”;
for(n=1; n <= 10; n++)
{
f =1;
for(i =1; i <= n; i++)
f=f*i;
cout<<”\n “ << n <<” \t “ <<f;
getch();
return 0;
}
60. Write a program to print reverse table of a number input by user.
#include<iostream.h>
#include<conio.h>
int main ( )
{
int n, i;
clrscr();
cout<<”\n Enter a number….”;
cin >> n;
for(i =10; i >= 1; i- -)
cout<<”\n “<<n <<” x “ <<i <<” = “ << n*i;
getch();
return 0;
}

(Practice all the other programs given in book as examples and in practical notebook)

LONG QUESTIONS OF EXERCISE


Q #1: Combine short Q- 3, 4, 5, 7
Q #2: as Q- 12 in short Q
Q #3: Combine short in sequence Q-14, 15, 56, 17, 30, 19 and example in book @ Page # 86

47 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 5: Arrays and Strings- MCQs
1. Which of the following is the correct declaration of array?
(a) int arr; (b) int arr(10); (c) int arr{10}; (d) int arr[10];
2. What is the index number of the last element of an array with 5 elements?
(a) 0 (b) 4 (c) 5 (d) 6
3. What is an array?
(a) An array is a series of elements
(b) An array is a series of the elements of the same type placed in noncontiguous memory location
(c) An array is a series of the elements of the same type placed in contiguous memory locations
(d) None of these

4. Which of the following identifies the first element in array named temp?
(a) temp(0) (b) temp(1) (c) temp[0] (d) temp[1]
5. Which of the following identifies the last element in array declared as int a[10][10];
(a) a[9][9] (b) a[9][10] (c) a[10][10] (d) a[11][11]
6. Given the following: int k=[3][5]= {{3,10,12,27,12),
{21,20,18,25,1},
{15,16,17,44,4}} What is in k[1][3]?
(a) 12 (b) 18 (c) 25 d) 15
7. Given the following: int arr=[3][5]= {{12,0,5,10),
{7,8,19,30},
{33,1,2,22}} Which of the following will replace 19 with 50?
(a) arr[2][3]=50 (b) arr[1][2]=50 (c) arr[2][1]=50 (d) arr[19]=50
8. Which of the following functions is used to append a string onto the end of another string.
(a) strcpy() (b) strapp() (c) strcat() (d) strcmp()
9. Which of the following functions returns a numeric value?
(a) cin.get() (b) strcat() (c) strcmp() (d) strcpy()
10. Which of the following functions inputs a string from user?
(a) cin.get() (b) getstr() (c) in.str() (d) strcpy()
11. If string1 and string2 are same than strcmp() returns____.
(a) -1 (b) 0 (c) 1 (d) “same”
12. Which of the following is used to find the number of characters in a string?
(a) cin.get() (b) strlen() (c) strcmp() (d) strcpy()
13. Which of the following is used to initialize a string?
(a) cin.get() (b) strcpy() (c) Both a and b (d) None of these
14. sizeof() function is used to find the______.
(a) number of elements of an array (b) number of bytes occupied in memory
(c) highest index of an array (d) size of program
15. For the array int a[4], sizeof(a) will return ______
(a) 3 (b) 4 (c) 8 (d) 16
ANSWER KEY: 1.D-2.B-3.C-4.C-5.A-6.C-7.B-8.C-9.C-10.A-11.B-12.B-13.C-14.B-15.D

48 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 5: Arrays and Strings
SHORT QUESTIONS
1. Define an array and give its advantages in programming.
Ans: An array is a series of the elements of the same type placed in consecutive memory locations. It is
a group of like variables having same name but are identified with unique index number.
Advantages:
●It allows to use single name for mul ple variables of same data type, making it simple and easy to
handle naming convention.
●It reduces the program size
●It provides an easy way of handling a list of numbers of characters.
2. Differentiate between ONE DIMENSIONAL and TWO DIMENSIONAL arrays?
ONE DIMENSIONAL ARRAY TWO DIMENSIONAL ARRAY
It has a single list of elements It has elements in the form or table or matrix
It has a single index number It has two index numbers one each for the row
and column
It is accessed by a simple loop It uses nested loop
e.g. int arr[10]; e.g. int arr[2][5];
3. What is use of sizeof() function? Give one example.
Ans: sizeof() function is used to find the number of bytes occupied in memory by a datatype. It is also
used for finding the number of bytes reserved for an array in memory.
Its syntax is: sizeof(array); (or sizeof datatype);
4. Declare an array named x, that has 3 rows and 5 columns and assign it values from 1 to 15 in the
declaration statement.
Ans: int x[3][5]= { {4,1,3,2,5}, {7,10,6,8, 9}, {12,15,11,13,14} };
5. Define string and explain how it is stored in computer memory.
Ans: String is the collection of characters. It is just like an array of char type. It is declared as:
char <stringname>[size] e.g., char name[20];
Storage: It is stored in memory as a single dimensional array of char type i.e. having consecutive
memory locations. It always stores a null character at the end. Thus a sting of 10 characters can
store 9 characters plus 1 null character.
6. What is the advantage of using cin.get() function over cin statement for reading a a string.
Ans: cin.get() can read any string including spaces i.e. multiword strings while cin statement can read
only the strings having no space i.e. single word strings.
7. Differentiate between strcpy() and strcmp() functions.
strcpy() strcmp()
strcpy() is used to copy the contents of one string strcmp() compares the contents of two strings
to another
It affects the first string as it is overwritten or It does not affect any string as it just compares
initialized
It cannot return a numeric value It returns a numeric value i.e. -1, 0 or 1 on the basis
of comparison
Its syntax is strcpy(str1, str2); Its syntax is int x = strcmp(str1, str2);

49 Computer Science XII (By: Prof. Noman Qadeer)


8. Differentiate between strlen() and strcat() functions.
strlen() strcat()
strlen() is used to find the number of characters strcat() is used to append the contents of one
in a string string to the end of another.
It does not affect any string as it just compares It affects the first string as second string is appended
at its end
It returns a numeric value It cannot return a numeric value
Its syntax is: int x = strlen(str); Its syntax is: strcat(str1, str2);
9. Define one dimensional array with example.
Ans: One dimension array is a collection of like variable stored in consecutive memory locations like a
list. It has only one index number to identify each element. It is declared as e.g. int a[10]. The
number 10 indicates the number of elements having index from 0 to 9.
Example: int arr[10] ={1,16,6,81,77,22,4,5,29,30}
10. Define two dimensional array with example.
Ans: Two dimension array is a collection of like variable stored in consecutive memory locations in the
form of table or matrix. It has two index numbers to identify each element. One is for row and
another is for column. It is declared as e.g. int a[2][4]; The number 2 indicates the number of rows
having index from 0 and 1 while 4 indicates number of columns having index from 0 to 3.
Example: int arr[2][4] ={ {1,16,6,81} , {77,22,4,5} }
11. Define the purpose of the following functions: strcpy(), strcat(), strlen(), strcmp(), cin.get()
Ans: strcpy(): strcpy() is used to copy one string to another. It is also used for initialization of strings.
Its syntax is: strcpy(str1, str2); // str2 will overwrite str1.
strcat(): strcat() is used to append the contents of one string to the end of another.
Its syntax is: strcat(str1, str2); //str2 will be appended at the end of str1.
strlen(): strlen() is used to find the number of characters in a string. It returns numeric value.
Its syntax is: int x = strlen(str); //length of str will be stored in variable x.
strcmp(): strcmp() compares two strings on the basis of their ASCII code. It compares the first
character of both strings and if they are sane it moves to the next. It continues comparing
characters until the characters differ or a null character is reached. It returns following output
0, if both strings ae same, 1, if str1 is greater and -1, if str2 is greater.
Its syntax is: int x = strcmp(str1, str2)
cin.get(): cin.get() is used to read a multi-word strings from keyboard i.e.which may also include spaces.
Its syntax is: cin.get(str, 20); //20 is the size of string
12. Write a program that reads ten numbers in an array and prints them.
#include<iostream.h>
#include<conio.h>
int main ( )
{
int i, arr[10]; for(i=0; i<10; i++)
clrscr(); cout<<”\n “<<arr[i];
cout<<”\n Enter 10 numbers into the array…”<<endl; getch();
for(i=0; i<10; i++) return 0;
cin>>arr[i]; }
cout<<”\n Array is as follows: \n\n”;

50 Computer Science XII (By: Prof. Noman Qadeer)


13. Write a program that reads ten numbers in an array and prints them in reverse order.
#include<iostream.h>
#include<conio.h>
int main ( )
{
int i, arr[10];
clrscr();
cout<<”\n Enter 10 numbers into the array…”<<endl;
for(i=0; i<10; i++)
cin>>arr[i];
cout<<”\n Array in reverse order is as follows: \n\n”;
for(i=9; i>=0; i--)
cout<<”\n “<<arr[i];
getch();
return 0;
}

14. Write a program that reads ten numbers in an array and prints the smallest number with index.
#include<iostream.h>
#include<conio.h>
int main ( )
{
int i, min, ind, arr[10];
clrscr();
cout<<”\n Enter 10 numbers into the array…”<<endl;
for(i=0; i<10; i++)
cin>>arr[i];
min= arr[0]; ind = 0;
for(i=0; i<10; i++)
if(arr[i] < min)
{
min = arr[i];
ind = i;
}
cout<<”\n Smallest Number is “<<c <<” at index number ”<<ind;
getch();
return 0;
}

51 Computer Science XII (By: Prof. Noman Qadeer)


15. Write a program that reads ten numbers in an array and prints the largest number with index.
#include<iostream.h>
#include<conio.h>
int main ( )
{
int i, max, ind, arr[10];
clrscr();
cout<<”\n Enter 10 numbers into the array…”<<endl;
for(i=0; i<10; i++)
cin>>arr[i];
max= arr[0]; ind = 0;
for(i=0; i<10; i++)
if(arr[i] > max)
{
max = arr[i];
ind = i;
}
cout<<”\n Largest Number is “<<max <<” at index number ”<<ind;
getch();
return 0;
}
16. For the given array int a[3][2]={{6,3},{7,8},{4,5}}; Write a program that prints the array in the
form of a matrix as given below and find its sum.
6 3
7 8
4 5
#include<iostream.h>
#include<conio.h>
int main ( )
{
int i,j, s=0, a[3][2]={{6,3},{7,8},{4,5}};
clrscr();
for(i=0; i<3; i++)
{
for (j=0; j<2; j++)
{
s=s+a[i][j];
cout<<a[i][j]<<”\t”;
}
cout<<”\n”;
}
cout<<”\n Sum of numbers in array is “<<s;
getch();
return 0;
}

52 Computer Science XII (By: Prof. Noman Qadeer)


17. For the given array: int arr[3][4]= {{4,18,-16,11},
{-5,10,-2,12},
{15,-3,17,18}};
Write a program to find the sum of positive numbers
#include<iostream.h>
#include<conio.h>
int main ( )
{
int i,j, s=0, arr[3][4]= {{4,18,-16,11}, {-5,10,-2,12},{15,-3,17,18}};
clrscr();
for(i=0; i<3; i++)
for (j=0; j<4; j++)
if(arr[i][j] >0)
s=s+arr[i][j];
cout<<”\n Sum of positive numbers in array is “<<s;
getch();
return 0;
}

18. For the given array int a[2][4]={{14,8,11,10},{15,12,20,3}}, b[2][4]={{2,3,4,7},{6,7,8,9}}; Write a


program that adds the two arrays and produces the following output on screen.
Sum of the array is:
16 11 15 17
21 19 28 12
#include<iostream.h>
#include<conio.h>
int main ( )
{
int i,j, a[2][4]={{14,8,11,10},{15,12,20,3}}, b[2][4]={{2,3,4,7},{6,7,8,9}};
clrscr();
cout<<”\n Sum of array is \n”;
for(i=0; i<2; i++)
{
for (j=0; j<4; j++)
cout<< a[i][j] + b[i][j] <<”\t”;
cout<<”\n”
}
getch();
return 0;
}

53 Computer Science XII (By: Prof. Noman Qadeer)


19. Input data from keyboard in a two dimensional array x that has r rows and c columns and print
the sum of each row in the following format:
Sum of row 1 =
Sum of row 2 =
:
Sum of row r =
#include<iostream.h>
#include<conio.h>
int main ( )
{
int r, c, x[][], i,j s;
clrscr();
cout<<”\n Enter number of rows R….”;
cin>>r;
cout<<”\n Enter number of columns C….”;
cin>>c;
for(i=0; i<r; i++)
{
cout<<”\n Enter elements of Row # “<<i;
for (j=0; j<c; j++)
cin>>x[i][j];
}
for(i=0; i<r; i++)
{
s=0;
for (j=0; j<c; j++)
s=s+x[i][j];
cout<<”\n Sum of Row # “<<i <<” is “<<s;
}
getch();
return 0;
}
20. Write a program that reads a string, copies it into another string and then prints both strings.
#include<iostream.h>
#include<conio.h>
#include<string.h>
int main ( )
{
char s1[20], s2[20];
clrscr();
cout<<”\n Enter a string….”;
cin.get(s1,20);
cout<<”\n String-1 is” <<s1;
cout<<”\n String-2 is” <<s2;
strcpy(s1,s2);
cout<<”\n After copying, String-1 is” <<s1;
getch();
return 0;
}

54 Computer Science XII (By: Prof. Noman Qadeer)


21. Write a program that reads two strings of size 20 and performs the following operations:
a. Prints both strings with their lengths
b. Concatenates the second string onto the end of first string and print it
#include<iostream.h>
#include<conio.h>
#include<string.h>
int main ( )
{
char s1[20], s2[20];
clrscr();
cout<<”\n Enter first string….”;
cin.get(s1,20);
cout<<”\n Enter second string ….”;
cin.get(s2,20);
cout<<”\n String-1 is” <<s1<<”and its length is”<<strlen(s1);
cout<<”\n String-2 is” <<s2<<”and its length is”<<strlen(s2);
strcat(s1,s2);
cout<<”\n After concatenation, String-1 is” <<s1;
getch();
return 0;
}

22. Write a program that reads 3 strings and prints the smallest.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main (void)
{
char s1[20], s2[20], s3[20;
int a,b,c;
clrscr();
cout<<”\n Enter first string….”;
cin.get(s1,20);
cout<<”\n Enter second string ….”;
cin.get(s2,20);
cout<<”\n Enter third string ….”;
cin.get(s3,20);
a=strcmp(s1,s2);
b=strcmp(s1,s3);
c=strcmp(s2,s3);
if(a<0 && b<0)
cout<<”\n Smallest String is” <<s1;
else if(a>0 && c<0)
cout<<”\n Smallest String is” <<s2;
else if(b>0 && c>0)
cout<<”\n Smallest String is” <<s3;
getch();
}

55 Computer Science XII (By: Prof. Noman Qadeer)


23. Write a program that reads Name and Address of a person and prints it.
#include<iostream.h>
#include<conio.h>
#include<string.h>
int main ( )
{
char name[20], add[50];
clrscr();
cout<<”\n Enter your name….”;
cin.get(name,20);
cout<<”\n Enter your address….”;
cin.get(add,50);
cout<<”\n Name = “<<name <<”\n Address = “<<add;
getch();
return 0;
}
24. For the given array int arr[15]={4,8,5,1,3,5,0,12,5,7,3,15,8,4,11} Write a program that prints the
number of times the number 5 appears in the array.
#include<iostream.h>
#include<conio.h>
int main ( )
{
int i,c=0, arr[15]={4,8,5,1,3,5,0,12,5,7,3,15,8,4,11};
clrscr();
for(i=0; i<15; i++)
If(arr[i] == 5)
c++;
cout<<”\n 5 appears in array “<<c <<” times”;
getch();
return 0;
}
25. Write a program store squares of first ten natural numbers in an array and then print it the
numbers with squares.
#include<iostream.h> OUTPUT
#include<conio.h>
int main ( ) 1 1
{ 2 4
int i, arr[10]; 3 9
clrscr(); 4 16
for(i=0; i<10; i++) 5 25
{ 6 36
arr[i] =i*I; 7 49
cout<<”\n “ <<i <<”\t” <<arr[i]; 8 64
} 9 81
getch(); 10 100
return 0;
}

56 Computer Science XII (By: Prof. Noman Qadeer)


26. Write a program to input a string and print it in reverse order.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main (void)
{
char str[50];
int i, ln;

clrscr();
cout<<”Enter a string…\n\n”;
cin.get(str,50);
ln=strlen(str);

cout<<”\n\t\t Here is your string in reverse order….\n\n\n”;


for(i=ln-1; i >= 0; i--)
cout<<str[i];

getch();
}

27. Write a program to input a string and print it vertically.


#include<iostream.h>
#include<conio.h>
#include<string.h>
void main (void)
{
char str[50];
int i, ln;

clrscr();
cout<<”Enter a string…\n\n”;
cin.get(str,50);
ln=strlen(str);

cout<<”\n\t\t Here is your string printed vertically….\n\n\n”;


for(i=0; i < ln; i++)
cout<<str[i]<<”\n”;

getch();
}

(Practice all the other programs given in book as examples and in practical notebook)

57 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 6: Functions- MCQs
1. The phenomenon of having two or more functions with the same name but different number and types of
parameters is known as ___________
(a) Inline Function (b) Nested Function (c) Function Overloading (d)Recursive Function

2. We declare the function with ________ if there is no return type.


(a) long (b) double (c) int (d) void

3. Arguments of a function are separated with ________


(a) Comma (b) Semicolon (c) Colon (d) None of these

4. Variables inside parenthesis of function declaration have ____ level access.


(a) Local (b) Global (c) Module (d) Universal
5. Observe the following function declaration and choose the best answer:
int divide (int a, int b =2)
(a) Variable 2 is of integer type and will always have value 2
(b) Variables a and b are of int type and initial value of both variables is 2
(c) Variable b is international scope and will have value 2
(d) Variable b will have value 2 if not specified when calling function
6. What is set of instruction called which perform the task of function?
(a) Function Declaration (b) Prototype (c) Function Call (d) Function Definition
7. Which variable has local scope and holds the value throughout the life of program?
(a) Local (b) Global (c) Static (d) Universal
8. The variables which appear in function prototype are called ______.
(a) Formal Parameters (b) Actual Parameters (c) Local Variables (d) Static Variables
9. The variables which appear in function call and hold the passing values are called ______.
(a) Formal Parameters (b) Actual Parameters (c) Local Variables (d) Static Variables
10. Every C++ program comprises of one function which starts execution, this function is called ______.
(a) main() (b) Inline Function (c) Initial Function (d) System Defined Function
11. ____ tells the compiler the name of function, number, types and order of parameters.
(a) Prototype (b) Call (c) Definition (d) Overloading

12. Built-in function is also called _______


(a) User Defined Function (b) main() (c) Library Function (d) None of these
13. Function definition may be written ______
(a) before main() (b) after main() (c) in separate file (d) All of these
14. Scope of variable means_____
(a) Name (b) accessibility (c) Data type (d) Value it holds
15. ____ symbol is used to pass value by reference.
(a) # (b) ! (c) & (d) *

ANSWER KEY: 1.C-2.D-3.A-4.A-5.D-6.D-7.C-8.A-9.B-10.A-11.A-12.C-13.D-14.B-15.C

58 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 6: Functions
SHORT QUESTIONS
1. Define function and name its types.
Ans: A function is a building block of C++ program, it is a group of statements that together perform a
task. There are two types of functions:
● Library (or built-in) Functions ●User Defined Func ons (UDF)
2. What are library functions? OR What do you mean by built-in functions?
Ans: Library functions or built-in functions are the pre-defined function which we just use and do not
need to write their codes. These are already defined by the system. e.g. clrscr(), getche() etc.
3. What do you mean by user defined function (UDF)?
Ans: The functions which are defined by the programmer in source code are known as user defined
functions. These are customized to fulfil the user’s requirements.
4. What are the advantages of using functions in a program?
Ans: Followings are the advantages of using functions:
●Func ons divides the program into logical blocks thus makes it easy and clear to understand.
● Use of func on o en avoids repe on of same code
● It is easy to update or change any code in func on.
●It makes tes ng easy as individual functions are tested.
●Programs can be modified without changing the structure of program.
5. What do you mean by Function declaration? OR What do you mean by functions prototype?
Ans: Function declaration or Prototype is the function component to tell the compiler about the
existence of function. It is used before main() function and tells the compiler about function name,
and types, number and order of parameters.
Its syntax is: return type function name (list of input parameters /variables with types);
Example: int sum (int a, int b);

6. What is function Call?


Ans: Function call is the process to transfer control to the function for its execution. It does not include
data types, rather it just uses variable as actual parameters.
Its syntax is: function name (values/variables being passed as input);
Example: sum (x,y); OR s= sum (x,y); OR sum();
7. Define function definition.
Ans: Function definition is the block of statements that performs the function’s intended task. It follows
function header which is same as prototype. It is mostly written after main body.
Its syntax is: return type function name (list of input parameters /variables with types)
{
Block of statements
}

Example: int sum (int a, int b)


{
return a+b;
}

59 Computer Science XII (By: Prof. Noman Qadeer)


8. What are parameters? Define their types.
Ans: Parameters are the special kind of variable which are used to pass information between functions.
There are two types of parameters
●Formal parameters: The parameters which appear in func on prototype or defini on.
●Actual Parameters: The parameters which appear in func on call.
9. Differentiate between Formal and Actual Parameters.
Formal Parameters Actual Parameters
These appear in prototype and function header These appear in function call
Formal parameters appear with datatype for Actual parameters appear without datatype
each variable separately e.g. sum (x , y);
e.g. void sum(int x, int y);
Formal parameters have no value Actual parameters have their own value
Formal parameters receive values from actual Actual parameters pass value to formal
parameters parameters
These are known in the function which is called These are known in the calling function
10. Define default arguments, give advantages and disadvantages of using default argument.
Ans: Default arguments are the values which appear with formal parameters as predefined value. If
calling function leaves the value blank for corresponding argument then default value is used. It is
assigned by using assignment operator in declaration e.g. int sum (int a, int b = 0). 0 is the default
value assigned to variable b.
11. What are inline functions?
Ans: These are the special function which are declared with the keyword inline and are used to minimize
the problem of function call overhead, It uses more memory than other functions but saves CPU
time wasted in passing the control between functions.
Its syntax is: inline return type function name (list of input parameters /variables with types)
{
Block of statements
}

Example: inline int sum (int a, int b)


{
return a+b;
}
12. What is Function overloading? How a function can be overloaded in a C++ program? Give
advantages.
Ans: The phenomenon of using same name for multiple functions having different parameters is called
function overloading. Mostly, the overloaded functions perform the related but slightly different
tasks. Various functions are overloaded by using different parameters in a C++ program. Following
are few advantages of function overloading
● We can use same func on name for related tasks
●It lowers the complexity of program
● Remembering the a single name is easier than remembering different names.
● It increases the program readability
●It shows the behavior of polymorphism

60 Computer Science XII (By: Prof. Noman Qadeer)


13. What is function signature? Define its various parts.
Ans: The function identity is called function signature. It comprises of
●The name of func on
●Arguments (Number, order and datatypes of arguments)
● Return type of func on
Example: int sum (int a, int b)
14. Define the scope of different type of variables used in functions.
Ans: Scope of variables means the accessibility of variables in the program. There are three types of scope
in C++
● Local Scope: Local variables are accessible only with in the func on in which they are declared.
● Global Scope: Global variables are accessible in all the functions within a program.
● Sta c Scope: Sta c variable declara on is preceded by keyword static. Static variables are local
in scope but they preserve the value once saved till the end of program even if the function is ended.
15. Differentiate between Local and Global variables.
LOCAL VARIABLES GLOBAL VARIABLES
Local variables are declared inside a function Global variables are declared outside of all the
function
These are accessible only with in the function These are accessible in all the functions within
in which these are declared a program
These are created in memory when control These are created when program starts
enters the function
These are destroyed when control leaves the These are destroyed when program ends
function
These variables have shorter lifespan These variables have longer lifespan
16. Write a program that takes two int parameters, add them and returns the sum.
#include<iostream.h>
#include<conio.h>
int sum (int a, int b);
int main ( )
{
int x, y, s;
clrscr();
cout<<”\n Enter two numbers…”;
cin>>x >>y;
s=sum(x,y);
cout<<”\n Sum of “<<x <<” and “<<y <<” is “<<s;
getch();
return 0;
}
int sum (int a, int b)
{
int c;
c = a+b;
return c;
}

61 Computer Science XII (By: Prof. Noman Qadeer)


17. Write a program with a function name “mean” to read three numbers and find their arithmetic mean.

#include<iostream.h>
#include<conio.h>
void mean (int a, int b, int c);
int main ( )
{
int x, y, z;
clrscr();
cout<<”\n Enter three numbers…”;
cin>>x >>y >>z;
mean(x,y,z);
getch();
return 0;
}
void mean (int a, int b, int c)
{
float m;
m = (a+b+c)/3;
cout<< “Arithmetic mean of these numbers is ”<<m;
}
18. Write a program to input the length and width of a rectangle and calculate its are using a UDF.
Function must return the value.

#include<iostream.h>
#include<conio.h>
int area (int l, int w);
int main ( )
{
int L, W, A;
clrscr();
cout<<”\n Enter length and width of rectangle…”;
cin>>L >>W;
A=area(L,W);
cout<<”\n Area of given rectangle is “<<A;
getch();
return 0;
}
int area (int l, int w);
{
int a;
a = l*w;
return a;
}

62 Computer Science XII (By: Prof. Noman Qadeer)


19. Write a program with two functions area and perimeter to calculate the area and perimeter of a
square.
#include<iostream.h>
#include<conio.h>
int area (int s);
int perimeter (int s);
int main ( )
{
int S, P, A;
clrscr();
cout<<”\n Enter measurement of sides of square…”;
cin>>S;
A=area(S);
P= perimeter(S);
cout<<”\n Area of given square is “<<A <<”and Perimeter is” <<P ;
getch();
return 0;
}
int area (int s);
{
int a;
a = s*s;
return a;
}
int perimeter (int s);
{
int p;
p = 4*s;
return p;
}
20. Write a program to input a number and determine whether it is prime or composite, using UDF.
#include<iostream.h>
#include<conio.h>
void prime_composite(int n)
int main ( )
{
int a; void prime_composite(int n)
clrscr(); {
cout<<”Enter a number….”; for (int i =2;i <= n; i++)
cin>>a; if(n % i = = 0)
prime_composite(n); {
getch(); cout<<”\n It is a COMPOSITE number”;
return 0; break;
} }
if( n = = i)
cout<<”\n It is a PRIME number”;
}

63 Computer Science XII (By: Prof. Noman Qadeer)


21. Write a program to input a number and print its table, using UDF
#include<iostream.h>
#include<conio.h>
void table (int n);
int main ( )
{
int n, i;
clrscr();
cout<<”\n Enter a number….”;
cin>> a;
table(a);
getch();
return 0;
}
void table (int n)
{
cout<<”\n\n TABLE OF “ <<n <<”\n\n”;
for(int i =1; i <= 10; i++)
cout<<”\n “<<n <<” x “ <<i <<” = “ << n*i;
}
22. Write a program to input two numbers and find smaller and greater, using UDF, results must be
returned to main() using global variables.
#include<iostream.h>
#include<conio.h>
void sm_gr (void);
Int a, b, s, g;
int main ( )
{
clrscr();
cout<<”\n Enter two numbers….”;
cin>> a >>b;
sm_gr();
cout<<”\n Smaller =”<<s <<”\t Greater =”<<g;
getch();
return 0;
}
void sm_gr (void);
{
if(a > b)
{
s=b;
g =a;
}
else
{
s=a;
g =b;
}
64 Computer Science XII (By: Prof. Noman Qadeer)
23. Write a program to input two numbers and find smaller and greater, using UDF, results must be
returned to main() using arguments.
#include<iostream.h>
#include<conio.h>
void sm_gr (int a, int b, int &s, int &g);
int main ( )
{ void sm_gr (int a, int b, int &s, int &g);
int x, y, S, G; {
clrscr(); if(a > b)
cout<<”\n Enter two numbers….”; {
cin>> x >>y; s=b;
sm_gr(x,y,S,G); g =a;
cout<<”\n Smaller =”<<S <<”\t Greater =”<<G; }
getch(); else
return 0; {
} s=a;
g =b;
}

(Practice all the other programs given in book as examples and in practical notebook)

Chapter # 7: Pointers- MCQs


1. If we have the statement int *ptr, then to what ptr points?
(a) Points to an integer type variable (b) Points to a character type variable
(c) Points to a floating point type variable (d) None of these
2. A pointer is:
(a)A keyword used to create variables
(b) A variable that stores the address of an instruction
(c) A variable that sores the address of another variable
(d) All of these
3. The operator used to get value at address stored in a pointer variable is____
(a) * (b) & (c) && (d) ||
4. Which of the statement is correct about the following code segment :
int i = 10;
int *j = &i
(a) j and I are pointer to an int
(b) i is a pointer to an int and stores address of j
(c) j is a pointer to an int and stores address of i
(d) i is a pointer to a pointer to an int and stores address of i
5. In pointers, dereference operator (*) is used to:
(a) Address the value of the pointer variable
(b) Points to the value stored in the variable pointed by the pointer variable
(c) Both a and b (d) None of these

ANSWER KEY: 1.D-2.C-3.A-4.C-5.D

65 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 7: Pointers- Short Questions
1. What is pointer? Describe the advantages of using pointer in C++ Program.
Ans: A pointer is a variable that points to or refers to another variable. It holds the address of variable
which it is pointing to.
Advantages: Some tasks in C++ are easier to do with pointers such as
•Accessing the addresses of variables indirectly and operating their values
•Passing values to functions by reference
•Managing files in programs etc.
2. What is the difference between dereference operator “*” and reference operator “&”? Explain
with the help of some lines of code.
Ans: Dereference Operator( * ): It is used to access the value of a variable through its pointer. It provides
the value of the variable whose address is stored in pointer.
e.g. int n= 200
int *ptr; OUTPUT
ptr = &n; Address of N is 1050
cout<<”Address of N is” <<ptr; Value of N is 200
cout<<”\n Value of N is”<<*ptr;
(Suppose the variable is stored at memory address of 1050)
Reference Operator( & ): It is also known as address operator. It is used to provide the address of
a variable through. It is used to initialize a pointer to store the address of variable which it will point
to.
e.g. int n= 200 OUTPUT
int *ptr; Address of N is 1050
ptr = &n;
cout<<”Address of N is” <<ptr;
(Suppose the variable is stored at memory address of 1050)
3. How pointer is initialized? Write a program to illustrate this concept.
Ans: Pointer is initialized to address of other variable. it is initialized by using reference operator (&).
The reference operator will store the address of variable which the pointer will point to.
e.g. #include<iostream.h>
#include<conio.h>
int main ( )
{
int *ptr, n;
ptr = &n; // This will initialize the pointer ptr with address of variable n let 1050.
cout<<”Address of N is” <<ptr;
getch(); OUTPUT
return 0; Address of N is 1050
}
4. How the declaration of pointer variable is different from declaration of simple variable.
Pointer Variable Simple Variable
Pointers need an asterisk(*) for declaration. Simple variable do not need any operator for
declaration
Pointer has the same data type as that of the Simple variable are of the type of data to be
variable it will point to. stored
Pointer may be of void type Simple variable may not be of void type

66 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 8: Classes and Objects - MCQs
1. A constructor is called when ever _______
(a) An object is destroyed (b) An object is created
(c) A class is declared (d) A class is used
2. Destructor is used for ______
(a) initializing the values of data members in an object
(b) initializing arrays
(c) Freeing memory allocated to the object of the class when it was created
(d) Creating an object
3. The name of a destructor is always preceded by the symbol ________.
(a) + (b) % (c) - (d) ~
4. Constructors are usually used for _________.
(a) Constructing programs (b) Running classes
(c) Initializing objects (d) All of these
5. Inheritance is used to ___________
(a) Increase the size of a program (b) Make the program simpler
(c) Provide the facility of code reusability (d) Provide the facility of data hiding
6. Access specifiers are used for ___________
(a) Accessing classes (b) Inheritance
(c) Polymorphism (d) Data hiding
7. Attributes of a class are also called______
(a) Data members (b) Member Functions
(c) Objects (d) Constructors
8. Which of the following member of class can be accessed in main function having the object of that class?
(a) Private (b) Public (c) Protected (d) All of these
9.Which of the following member of class can be accessed by other member functions and its inherited
class only?
(a) Private (b) Public (c) Protected (d) All of these
10. Which of the following member of class can be accessed by its other member functions only?
(a) Private (b) Public (c) Protected (d) All of these
11. Which of the followings is the default access specifier, if no specifier is used?
(a) Private (b) Public (c) Protected (d) All of these
12. An object is a _____________
(a) Practical implementation of a class (b) Instance of a class
(c) Variable of type class (d) All of these
13. Data hiding is also known as ________.
(a) Class Security (b) Inheritance
(c) Encapsulation (d) Polymorphism
14. Class is a _______
(a) User defined data type (b) Combination of data and variables
(c) Function (d) Instance of an object
15. The phenomenon of creating new class from existing class is called____
(a) Object Oriented Programming (b) Inheritance
(c) Encapsulation (d) Polymorphism
ANSWER KEY: 1.B-2.C-3.D-4.C-5.C-6.D-7.A-8.B-9.C-10.A-11.A-12.D-13.C-14.A-15.B

67 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 8: Classes and Objects
SHORT QUESTIONS
1. Define the term CLASS with example.
Ans: A class is a user defined data type having its own data and functions. It is the most important
feature of C++ which leads to object oriented programming. The data variables inside a class are
called data members and functions in it are called member functions. It is declared before main
function. Its syntax is: class ABC
{
Access Specifier 1:
Members
Access Specifier 2:
members
};
2. Define the term OBJECT with example.
Ans: Objects are the instances of class which hold the data variable and functions declared in the class
in other words the variable of type class are called objects. Objects are the practical
implementation of class. Class members can be accessed by using objects. These are declared as
Class_name object_name e.g. ABC O1; where ABC is the class name and O1 is the object name.

3. Explain the terms CLASS and OBJECT with example. OR Write a note on a. Class b. Object (Long)
Ans: Class: A class is a user defined data type having its own data and functions. It is the most important
feature of C++ which leads to object oriented programming. It is declared before main function.
The body of class contains members and access specifiers. The data variables inside a class body
are called Data Members and functions in it are called Member Functions. Members of the class
are defined with a access specifier which determine their accessibility. Access specifier may be
public (accessible in class itself, derived classes and main function), protected (accessible in class
itself and derived classes), private (accessible with in the class only)
Syntax to declare a class is: class ABC
{
Access Specifier 1:
Members
Access Specifier 2:
members
};
Example: class SUM
{
private:
int a,b;

public:
void Cal (void)
{
cout<<”\n Enter two numbers…”;
cin>>a >>b;
cout<<”\n Sum of “<<a<<” and “<<b<<” is “<<a+b;
}
};

68 Computer Science XII (By: Prof. Noman Qadeer)


Objects: Objects are the instances of class which hold the data variable and functions declared in
the class in other words the variable of type class are called objects. Objects are the practical
implementation of class. Class members can be accessed by using objects.
These are declared as: Class_name object_name
e.g. ABC O1; where ABC is the class name and O1 is the object name.
members of the class can be accessed by object as
Object_Name.Member
e.g. O1.x=5; O1.Cal();

Example: class SUM


{
private:
int a,b;

public:
void Cal (void)
{
cout<<”\n Enter two numbers…”;
cin>>a >>b;
cout<<”\n Sum of “<<a<<” and “<<b<<” is “<<a+b;
}
};
Void main (void)
{
SUM C; // Declaration of object of class SUM
C.Cal(); // Accessing Member Function of class through Object
getch();
}

4. How objects are created to access the members of a class?


Ans: Objects are created just like other variables but their type is the class for which these are declared.
The syntax to create an object is : Class_name <space> object_name
e.g. ABC O1; where ABC is the class name and O1 is the object name.
Members of the class can be accessed by object as: Object_Name.Member
e.g. O1.x=5; O1.Cal();

5. What are members of a class?


Ans: The data and instructions with in the class body are called its members. The data variables inside
a class body are called Data Members and functions in it are called Member Functions.

6. What are Data Members?


Ans: The attributes of a class are called Data Members i.e. data variables inside a class body are called
Data Members. Mostly, the data members are declared under private access specifier but they
can be public or protected. They are declared as: class ABC
{
private:
int x, y;
};

69 Computer Science XII (By: Prof. Noman Qadeer)


7. What are Member Functions?
Ans: The functions defined inside a class are called Member Functions. The members functions are
declared under public access specifier to operate on data members but they can be private or
protected.

8. What are access specifier? Define all with examples.


Ans: Access Specifiers are used to determine the accessibility of members of a class. These apply the
data hiding (Encapsulation). There are three types of access specifiers used in classes i.e.
public: Accessible in class itself, derived classes and main function
protected : Accessible in class itself and derived classes
private : Accessible with in the class only

9. What is data hiding?


Ans: Date hiding is the feature of C++ which protects the members of a class from illegal access from
outside the class. It is also known as Encapsulation. It is implemented by using access specifiers.
public: Accessible in class itself, derived classes and main function
protected : Accessible in class itself and derived classes
private : Accessible with in the class only

10. What do you mean by Encapsulation?


Ans: Encapsulation.is the feature of OOP which protects the members of a class from illegal access from
outside the class. It is also known as Data hiding. It is implemented by using access specifiers.
public: Accessible in class itself, derived classes and main function
protected : Accessible in class itself and derived classes
private : Accessible with in the class only

11. Define the levels of hiding members of a class in the form of a table.

Access Public Protected Private


Access of members (data, functions) in the same class Yes Yes Yes
Access of members (data, functions) in the derived class Yes Yes No
Access of members (data, functions) from outside the class Yes No No

12. What do you mean by Constructor?


Ans: Constructor is the special member functions of a class which initializes the objects as automatically
when it is created. It has the same name as that of the class. Compiler identifies the constructor by
its name and return type. Constructor has no return type, not even void. It is always public.

13. What are the rules/features for naming constructors?


Ans: Constructor is the special member functions of a class which initializes the objects as automatically
when it is created. It has following naming rules
●It has the same name as that of the class.
● Constructor has no return type, not even void.
●It is always public.

70 Computer Science XII (By: Prof. Noman Qadeer)


14. What do you mean by Destructor?
Ans: Destructor is a special type of member function in a class that executes when an object is
destroyed. It unloads the object from memory. It has the same name as that of class but is preceded
by tilde symbol (~). it does not accept any arguments and has no return type, not even void.

15. What are the rules/features for naming destructors?


Ans: Destructor is a special type of member function in a class that executes when an object is
destroyed. It has following naming rules
●It has the same name as that of the class but it is preceded by lde symbol (~).
● It has no return type, not even void.
●It cannot take arguments.

16. Differentiate between Constructors and Destructors.


Constructors Destructors
It has the same name as that of the class It has the same name as that of the class but it
is preceded by tilde symbol (~)
It is executed when object is initialized It is executed when object is destroyed
It can accept arguments It cannot accept arguments
It can be overloaded It cannot be overloaded as there is only single
destructor in class

17. What do you mean by constructor overloading?


Ans: Process of having more than one constructor in a class is known as constructor overloading. The
constructor may have different arguments to initialize the objects.

18. What are default constructors/ implicit constructors?


Ans: A constructor having no arguments or having default values for all arguments is called default
constructor or implicit constructor. If user doesn’t define a default constructor, compiler assumes
the class to have a default constructor with no arguments.

19. What are user defined constructors/ explicit constructors?


Ans: When users define a constructor in class for their own purpose especially for initialization of
variables, such types of constructors are called explicit or user defined constructors.

20. Define inheritance with example.


Ans: The process of creating new class from existing class is known as inheritance, It is the key feature
of OOP which applies code reusability. The class from which other classes are derived is called Base
Class or Parent Class while the new derived class is called Derived Class, Sub Class or Child Class.
Syntax for using inheritance is as following:
class A //Base Class
{
Body of class
};
class B: public A //Derived Class
{
Body of class
};

71 Computer Science XII (By: Prof. Noman Qadeer)


21. Define polymorphism with example.
Ans: Polymorphism is the use of an operator or function in different ways. It gives different meaning
and functionality to operators or functions. It can be achieved by following concepts:
●Func on Overloading ●Operator Overloading ●Virtual Func on
Example: Suppose the operator *
It is used for ● Arithme c mul plica on e.g. 3*5;
● Declara on of Pointers e.g. int *ptr;
● Dereference e.g. x = *ptr;
In the same way + is used for Arithmetic Addition as well as String Concatenation.
22. Define Function overloading.
Ans: The phenomenon of using same name for multiple functions having different parameters is called
function overloading. Mostly, the overloaded functions perform the related but slightly different
tasks. e.g. void sum (void);
int sum (int a, int b);
int sum (int a, int b, int c);
23. Define Operator overloading.
Ans: Phenomenon of using an operator for different functions is known as Operator overloading.
Example: Suppose the operator *
It is used for ● Arithme c mul plica on e.g. 3*5;
● Declaration of Pointers e.g. int *ptr;
● Dereference e.g. x = *ptr;
In the same way + is used for Arithmetic Addition as well as String Concatenation.
24. Define Virtual Function.
Ans: A function whose behavior can be overridden with in an inheriting class by a function with the same
signature is known as Virtual Function. It is a very important concept of polymorphism in OOP.
25. Write a program implementing a class with the name Circle having two functions with the names
GetRadius and CalArea. The function should get the value for radius from the user, calculate the
area of circle and display the results.
#include<iostream.h>
#include<conio.h>
class Circle
{
private:
float r;

public:
void GetRadius (void)
{
void main (void)
cout<<”\n Enter Radius of Circle…..”;
{
cin>>r;
Circle c;
}
clrscr();
void CalArea (void)
c.GetRadius();
{
c.CalArea();
cout<<”\n Area of Circle is ”<<3.142 * r * r;
getch();
}
}
};

72 Computer Science XII (By: Prof. Noman Qadeer)


26. Write a program implementing inheritance between Employee (base class) and Manager
(derived class).
#include<iostream.h>
#include<conio.h>
class Employee
{
public:
int E_ID;
};
class Manager : public Employee
{
public:
int M_ID;
};
void main (void)
{
Manager O; // Object of Derived Class
clrscr();
cout<<”\n Enter Employee ID…”;
cin>> O.E_ID;
cout<<”\n Enter Maager ID…”;
cin>> O.M_ID;
cout<<”\n Employee ID = “<<E_ID; // data member of Base Class
cout<<”\n Manager ID = “<<M_ID; // data member of Derived Class
getch();
}
27. Write a program implementing a class with the name ConstDest having constructor and destructor
functions in its body.
#include<iostream.h>
#include<conio.h>
class ConstDest
{
public:
ConstDest ()
{
cout<<”\n WELCOME…. I M CONSTRUCTOR…..”;
}
~ConstDest ()
{
cout<<”\n\n\n I M DESTRUCTOR….. GOOD BYE…..”;
}
};
void main (void)
{
ConstDest A;
getch();
}
73 Computer Science XII (By: Prof. Noman Qadeer)
28. Write a program implementing a class with the name AreaOfRectangle having constructor and
destructor functions in its body to calculate the area of rectangle on the length and width passed
from main().
#include<iostream.h>
#include<conio.h>
class AreaOfRectangle
{
public:
AreaOfRectangle (int a, int b)
{
cout<<”\n Area of rectangle is ”<<a*b;
}
~ AreaOfRectangle ()
{
cout<<”\n\n\n ….. GOOD BYE…..”;
}
};
void main (void)
{
AreaOfRectangle C(3,5);
getch();
}
29. Write a program implementing a class with the name Time. This class should have a constructor
to initialize the time, hours, minutes and seconds initially to zero. This class should have another
function name ToSecond to convert and display the time passed by object into seconds.
#include<iostream.h>
#include<conio.h>
class Time
{
public:
int h, m, s, tot_sec;

Time() void main (void)


{ {
h=0; Time t;
m=0; t.ToSecond();
s=0; getch();
cout<<”\n\n…. WELCOME …..”; }
}
void ToSecond(void)
{
Tot_sec=
cout<<”\n Enter time in hours, minutes or seconds”;
cin>>h>>m>>s;
tot_sec= h*3600+ m*60 +s;
cout<< \”\n\n Time in Seconds = “<<tot_sec;
}
}; (Practice all the other programs given in book as examples and in practical notebook)

74 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 9: File Handling - MCQs
1. eof() stands for _______
(a) Errors On File (b) End Of File (c) Exit Of File (d) A class is used
2. In the file handling, open() function is used _________
(a) to open C++ Compiler (b) to open a file
(c) both a and b (d) None of these
3. Default mode parameter for ofstream is __________
(a) ios::out (b) ios::in (c) ios::binary (d) both a and b
4. A text file has the extension _________
(a) .doc (b) .docx (c) .txt (d) .bin
5. ios::binary is used as an argument to open() function for_______
(a) opening file for input operation (b) opening file for output operation
(c) opening file in binary mode (d) None of these
6. C++ divides the files on the basis of data storage into ____ types.
(a) 2 (b) 3 (c) 4 (d) 5
7. ____ file can only be processed in one direction sequentially.
(a) Text (b) Binary (c) Serial (d) Uni
8. ____ file can be processed in any direction randomly.
(a) Text (b) Binary (c) Serial (d) direct
9. ios::in mode is used to open a file for ____________
(a) Reading (b) Writing (c) both a and b (d) None of these
10. ios::out mode is used to open a file for ____________
(a) Reading (b) Writing (c) both a and b (d) None of these
11. bof() stands for____
(a) Binary Operational FIle (b) Best Of Fiels
(c) Beginning Of File (d) None of these
12. Sequence of bytes is called_______
(a) Binary data (b) binary file (c) characters (d) stream
13. A file is created in ________
(a) RAM (b) Cache (c) Primary Storage (d) Secondary Storage
14. Classes for IO File operations are stored in ____ file
(a) iostream.h (b) fstream.h (c) ifstream.h (d) oftream.h
15. Class for processing a file for reading is ________
(a) ifstream (b) ofstream (c) read (d) stream
16. Class for processing a file for writing is ________
(a) ifstream (b) ofstream (c) read (d) stream
17. Class for processing a file for reading as well as writing is ________
(a) ifstream (b) ofstream (c) iofstream (d) fstream
18. ___ is used to read a single character from a file.
(a) get() (b) getc() (c) getch() (d) read()
19. ___ is used to write a single character into a file.
(a) put() (b) putc() (c) write() (d) put char()
20. ___ is used to read a string from a file.
(a) gets() (b) getstr() (c) getline() (d) reads()

ANSWER KEY: 1.B-2.B-3.A-4.C-5.C-6.A-7.A-8.B-9.A-10.B-11.C-12.D-13.D-14.B-15.A-16.B-17.D-18.A-19.A-20.C

75 Computer Science XII (By: Prof. Noman Qadeer)


Chapter # 9: File Handling
SHORT QUESTIONS
1. What is a File?
Ans: A file is a collection of bytes stored on a secondary storage device like hard disk. The collection of
bytes can be interpreted as characters, words, lines or paragraphs from textual files and fields and
records from database and pixels from graphical image. File is recognized by its name and
extension, both separated by a dot e.g. MyFile.txt.

2. What is File Handling? What operations are involved in it?


Ans: File handling is a concept in C++ for storing data permanently. It provides mechanism for reading
and writing data in files. The operations involved in file handling are
● Opening a file
● Reading or Wri ng data in file
● Closing a file

3. What is File Handling? Explain different types of files in C++. (Long)


Ans: File handling is a concept in C++ for storing data permanently. It provides mechanism for reading
and writing data in files. The operations involved in file handling are opening a file, reading or
writing data and closing it. In C++, there are two types of files
● Text Files ● Binary Files
Text Files: Text file can be a stream of characters that can be processed sequentially only in forward
direction hence it is also known as sequential file. It is usually opened only for one operation i.e.
reading, writing or appending. Since text files deal with character, so they can only process one
character at a time however in C++ functions are provided to process lines of text yet they process
one character at a time. Characters are converted transparently to satisfy the storage requirements
of the operating system.
Binary Files: Binary File is a collection of bytes. In C/C++, a byte and character are equivalent hence
binary files are also known as character stream, but, there are two basic differences:
1. No special processing of the data occurs while transferring to and from disk
2. No constructs are placed on file and it can be read or written in any manner as desired by the
programmer
Files can be processed using random access techniques. These file can also be processed for read
and write operations simultaneously.

4. Define Text Files.


Ans: Text file can be a stream of characters that can be processed sequentially only in forward direction
hence it is also known as sequential file. It is usually opened only for one operation i.e. reading,
writing or appending.

5. What are Binary Files?


Ans: Binary File is a collection of bytes. In C/C++, a byte and character are equivalent hence binary files
are also known as character stream. Files can be processed using random access techniques.
These file can also be processed for read and write operations simultaneously.

76 Computer Science XII (By: Prof. Noman Qadeer)


6. Differentiate between Text Files and Binary Files?
TEXT FILES BINARY FILES
Text files are the streams of characters Binary files are the streams of bytes
These can be accessed only in forward direction These can be accessed in random direction
sequentially
These are opened for one operation only These can be opened for many operations at a
time
Characters are processed before moving to and Characters are moved unprocessed
from disk
These are widely used by all types of applications These are used by specific applications only

7. Describe different types of operations performed on the file.


Ans: Following operations can be performed on file in C++ file handling:
Opening a File: Files are opened firstly, so that they may be available for operations. In C++ open()
function is used to open a file . It includes file name and mode to open it. The mode defines the
operation to be performed on file.
Reading a File: File is opened in input mode for reading, The data saved in file is read and processed
in C++ Program. There are various options to read the file, it may be read character by character or
string by string or field by field depending on the type of file.
Writing a File: File is opened in output mode for Writing, The output of the program is saved in file
permanently. There are various options to write the data into file, it may be character by character
or string by string or field by field depending on the type of file.
Closing a File: After the completion of operations, file is closed for its security. After closing, the
file is no more available for any kind of operation. In C++ programming Language, file is closed using
close() function.

8. Define eof() and bof() functions.


Ans: eof(): eof() is pointer which represents End Of File. It returns TRUE if there is no more data to be
read from an input file stream. It means the function eof() checks whether the control has reached
the end or not. It is useful when number of records or characters are not known.
bof(): bof() is pointer which represents Beginning Of File. It returns TRUE if the current position is
the beginning of input file stream i.e. it tells whether the control is at the beginning of file or not.

9. What is stream? Define input and output streams.


Ans: Stream: Stream is a sequence of bytes associated with a file. Streams assure good and secure flow
of data between application and file. The stream may be input stream or output stream.
Input Stream: It takes any stream from an input source i.e. Keyboard, File or Network.
Output Stream: It holds stream for particular data consumer i.e. Monitor, Printer or File.

10. Define Character Stream and String Stream.


Ans: Character Stream: Data can be read from or written to file in the form of character stream.
Character stream process the data character by character.
String Stream: Data can be read from or written to file in the form of string stream. String stream
process the data in the form of associated strings.

77 Computer Science XII (By: Prof. Noman Qadeer)


11. What is meant by the term Mode of file opening? Describe various modes of file opening.
Ans: To make the file available for any operation, it must be opened first. The open function describes
the file name and mode of file opening, mode describes the type of operation to be performed on
the file. Followings are the modes of file opening:
MODE DESCRIPTION
ios:: in Input: Open the file for input operations (Reading a file)
ios::out Output: Open the file for output operations (Writing a file)
ios::binary Binary: Open the file in binary mode
ios::ate At the End: Open the file for output and move the read/write control to the end of file
ios::app Append: Open the file for append mode, all the output to be appended to the end
ios::trunc Truncate: Open the file for output operation in such a way that the existing contents
are over-written by the new one

12. Define the following functions? (1 mark for each function)


open(), close(), exit(), get(), put(), getline(), eof(), bof()
Ans: open(): open() is used to open a file in C++ Program.
Its syntax is: fptr.open(“file name.ext”,mode);
Where fptr is the Object of ifstream or ofstream and mode defines the operation type for which
file is being opened.
close(): close() is used to close a file in C++ Program. After a file is closed it is unavailable for any
kind of operation. It does not take any argument.
Its syntax is: fptr.close();
Where fptr is the Object of ifstream or ofstream.
exit(): exit() is used to exit a program. It takes inputs 1 or 0.
Its syntax is: exit(0) or exit(1)
Where 0 stands for no error and 1 represents that program is exits with error.
get(): get() is used to read a single character from a file.
Its syntax is: fptr.get(ch);
Where fptr is the Object of ifstream or ofstream and ch is char type variable.
put(): put() is used to write a single character into a file.
Its syntax is: fptr.put(ch);
Where fptr is the Object of ifstream or ofstream and ch is char type variable.
getline(): getline() is used to read a string stream from a file.
Its syntax is: fptr.getline(str,20);
Where fptr is the Object of ifstream or ofstream, str is a variable to hold string and 20 is the size of
string.
eof(): eof() is pointer which represents End Of File. This function returns TRUE if there is no more
data to be read from an input file stream.
bof(): bof() is pointer which represents Beginning Of File. This function returns TRUE if the current
position is the beginning of input file stream.
13. Define the class ifstream.
Ans: ifstream is a class defined in the header file fstream.h. It deals with the functions for reading a file.
For processing a file for input, an object of ifstream is created. Default opening mode of
ifstream.open is ios::in.

78 Computer Science XII (By: Prof. Noman Qadeer)


14. Define the class ofstream.
Ans: ofstream is a class defined in the header file fstream.h. It deals with the functions for writing data
into a file. For processing a file for output, an object of ofstream is created. Default opening mode
of ofstream.open is ios::out.
15. Define the class fstream.
Ans: fstream is a class defined in the header file fstream.h. It deals with the functions for writing to or
reading from a file. For processing a file for input as well as output, an object of fstream is created.
Default opening mode of fstream.open is ios::out|ios::in.
16. Write a program to input name and marks of 30 students from user and write in file result.txt.
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main (void)
{
ofstream fptr;
int i, m;
char name[30];
fptr.open(“result.txt”, ios::out);
for(i=1; i<=30; i++)
{
cout<<”\n Enter Name of Student”;
cin.get(name, 30);
cout<<”\n Enter Marks”;
cin>>m;
fptr<< name <<m;
}
fptr.close();
getch();
}
17. Write a program to read the names and marks of 30 students stored in file result.txt and print on screen.
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main (void)
{
ifstream fptr;
int i, m; char name[30];
fptr.open(“result.txt”, ios::in);
if(!fptr)
cout<<”\n File not found….”;
else fptr.close();
{ }
for(i=1; i<=30; i++) getch();
{ }
fptr>> name >>m;
cout<<”\n Name :”<<name <<”\t Marks: “<<m;
}

79 Computer Science XII (By: Prof. Noman Qadeer)


18. Write a program to input text form user character by character, store in a file and count the total
number of characters.
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main (void)
{
ofstream fptr;
int c=0;
char ch;
fptr.open(“MyText.txt”);
cout<<”\n Enter Text…\n\n\t\t”;
while (ch=getche() != ‘\r’)
{
fptr.put(ch);
c++;
}
fptr.close();
cout<<”\n You typed “<<c <<” characters in file”;
getch();
}

19. Write a program to read text form file character by character and count total number of
characters read.
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main (void)
{
ifstream fptr;
int c=0;
char ch;
fptr.open(“MyText.txt”);
if(!fptr)
cout<”\n File not found….”;
else
{
while (!fptr.eof())
{
fptr.get(ch);
cout<<ch;
c++;
}
fptr.close();
cout<<”\n File has “<<c <<” characters”;
}
getch();
}

80 Computer Science XII (By: Prof. Noman Qadeer)


20. Write a program to read a file word by word and print on screen.
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main (void)
{
ifstream fptr;
char str[20];
fptr.open(“MyFile.txt”, ios::in);
if(!fptr)
cout<<”\n File not found”;
else
{
while(!fptr.eof())
{
fptr>> str;
cout<<str<<endl;
}
fptr.close();
}
getch();
}
21. Write a program to read string stream from a file MyFile.txt.
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main (void)
{
ifstream fptr;
char str[30];
fptr.open(“MyFile.txt”, ios::in);
if(!fptr)
cout<<”\n File not found”;
else
{
while(!fptr.eof())
{
fptr.getline(str,30); Prof. Noman Qadeer
cout<<str<<endl;
}
0300-3117901
fptr.close();
}
getch();
}
(Practice all the other programs given in book as examples and in practical notebook)

﴾﴾ ꙮ G   D L U C K ꙮ﴿﴿
81 Computer Science XII (By: Prof. Noman Qadeer)

You might also like