0% found this document useful (0 votes)
24 views86 pages

Xii Computer Sci Notes

The document provides an overview of operating systems, detailing their functions, types, and key features. It covers various operating systems including DOS, Windows, macOS, and Linux, discussing their advantages, disadvantages, and specific characteristics. Additionally, it explains concepts such as process management, memory management, and I/O management, along with real-life applications of batch and multiprogramming operating systems.

Uploaded by

hadiyazainab23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views86 pages

Xii Computer Sci Notes

The document provides an overview of operating systems, detailing their functions, types, and key features. It covers various operating systems including DOS, Windows, macOS, and Linux, discussing their advantages, disadvantages, and specific characteristics. Additionally, it explains concepts such as process management, memory management, and I/O management, along with real-life applications of batch and multiprogramming operating systems.

Uploaded by

hadiyazainab23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 86

COMPUTER SCIENCE (XII)

Chapter#1 Operating System


1. What is an operating system, and what is its primary function?
An operating system is software that acts as an intermediary between the hardware of a
computer system and the software applications running on it. Its primary function is to manage
the hardware resources of the computer and provide a platform for software applications to run
efficiently.
2. Why is the operating system an important software?
OS is the most essential and vital part of a computer without which it is considered useless. It
enables an interface or acts like a link for interaction between computer software that is
installed on OS and users. It also helps to communicate with hardware and also maintains
balance among hardware and CPU. It also provides services to users and a platform for
programs to run on. It performs all common tasks applications require.
3. What is GUI?
GUI (Graphical User Interface) is basically a type of user interface that allows users to use
graphics to interact with OS. GUI is created because it is more user-friendly, less complex, and
easier to understand rather than a command-line interface. Its main goal is to increase
efficiency and ease of use. Instead of having to memorize commands, users can just click on a
button to simply execute the procedure. Examples of GUI include Microsoft Windows, macOS,
Apple’s iOS, etc.
4. What are some key commands used in the DOS command-line interface, and what do
they do?
Answer: Examples of key commands in the DOS command-line interface include DIR (list
directory contents), CD (change directory), COPY (copy files), DEL (delete files), and REN
(rename files).
5. Write any three limitations/Disadvantage of DOS operating System.
Lack of Multitasking Support: DOS is a single-tasking operating system, meaning it can only
execute one program at a time. Users cannot run multiple programs simultaneously.

Limited Memory Management: DOS has limited memory management capabilities,


particularly in accessing memory beyond the 1 MB.

Command-Line Interface (CLI) Dependency: DOS primarily relies on a command-line


interface (CLI) for user interaction, requiring users to input commands via text. This CLI
dependency makes DOS less user- Additionally, complex tasks may require users to
memorize and type lengthy commands.
6. What is MAC Operating System?
macOS is an operating system developed by Apple Inc. It is designed specifically for Apple's
Macintosh line of computers, including desktops and laptops. macOS is built on a Unix-based
foundation and features a graphical user interface (GUI).
7. Write advantages and disadvantages of MAC OS.
Advantages:
Mac has a simpler design and interface, which makes it easier to use for many users.
Mac is less vulnerable to viruses and malware, which increases security.

ANUM NISA 1
COMPUTER SCIENCE (XII)

Mac has better integration with other Apple products, such as iPhones and iPads. Mac
is known for its powerful hardware and fast speed.
Disadvantages:
Mac is usually more expensive than Windows computers.
There is less software and games for Mac, because Windows is the most used operating
system.
8. Write any three advantages of using Linux/Unix OS.
Multi-User, Multi-Tasking: Unix supports simultaneous access for multiple users and allows
multiple processes to run simultaneously, enhancing system efficiency.
Robust Security: Unix features robust security measures like file permissions and encryption,
providing protection against unauthorized access and malware.
Reliability: Unix is known for its stability and reliability, minimizing system crashes and
ensuring continuous operation, particularly in high-performance computing environments
requirement.
9. Describe one key feature of the Windows operating system that distinguishes it from
other operating systems.
One key feature of the Windows operating system is its support for a wide range of hardware
devices and peripherals. Windows provides built-in drivers and compatibility support for a
variety of hardware components, making it easy for users to install and use new devices with
their computer system.
10. Why window is known as GUI interface?
Windows is known as a GUI (Graphical User Interface) interface because it provides users with
visual elements such as windows, icons, menus, and pointers (WIMP) to interact with the
operating system and applications. Instead of relying solely on text-based commands, users
can perform tasks by clicking icons, selecting options from menus, and dragging objects using
a mouse or other pointing device.
11. Differentiate between DOS and Windows Operating System.

Characteristic DOS Windows

DOS operates through a Windows offers a graphical user


commandline interface (CLI), where interface (GUI), including windows,
User Interface
users interact with the system by icons, and menus for interaction with
typing text commands. the system and applications.
DOS is a single-tasking operating Windows is a multitasking operating
Multitasking system, meaning it can only run system, which allow users to run
one program at a time. multiple programs simultaneously
DOS has limited memory
Memory management capabilities. Windows provides more advanced
Management (maximum memory capacity of 640 memory management.
KB)

ANUM NISA 2
COMPUTER SCIENCE (XII)

In contrast, Windows offers extensive


DOS has limited hardware support
hardware support for a wide range of
compared to Windows, with
Hardware Support devices and peripherals, with built-in
compatibility primarily for older
drivers and compatibility for modern
hardware devices.
hardware components.

12. How does batch operating system differ from other interactive operating systems? A
batch operating system processes jobs in batches without user interaction. It collects similar
tasks or jobs, executes them sequentially, and requires minimal user involvement. In contrast,
interactive operating systems allow users to interact with the system in real-time, providing
immediate feedback and response to user input.
13. What are the advantages and disadvantages of batch processing in operating systems?
Advantages of batch processing includes:
• improved resource utilization
• reduced system idle time
• simplified management of repetitive tasks. Dis Advantages of batch processing

includes:

• It may introduce delays in job execution


• lack real-time responsiveness
• require careful job scheduling to avoid resource blockages.
14. Identify and write any three real life examples of batch operating system.
Payroll Processing:
Organizations use batch operating systems to process payroll data at the end of each pay
period, calculating salaries, generating paychecks, and producing payroll reports.
Utility Billing:
Utility companies utilize batch operating systems for billing, processing meter readings and
consumption data in batches to calculate charges, generate invoices, and update customer
accounts.
Credit Card Processing:
Financial institutions rely on batch operating systems to process credit card transactions,
batching transactions for verification, reconciliation, fee calculation, and statement generation.
15. Write any three advantages of Multiprogramming Operating system.
Increased CPU Utilization: Multiprogramming OS maximizes CPU usage by allowing multiple
programs to run simultaneously, ensuring efficient resource utilization.

Enhanced System Efficiency: These systems optimize resource usage, minimizing idle time
and improving overall system performance through simultaneous execution of multiple
programs.

ANUM NISA 3
COMPUTER SCIENCE (XII)

Better Responsiveness: Multiprogramming OS enables rapid task switching, ensuring users


experience minimal delays and a smooth computing experience even under heavy workloads.
16. Write any three advantages of Multitasking Operating system.
Improved Productivity: Multitasking OS allow users to work on multiple tasks simultaneously,
enhancing productivity by enabling efficient task switching and simultaneous execution of
applications.
Enhanced User Experience: Users can switch between apps and execute numerous tasks
without interrupting ongoing processes

Optimized Resource Utilization: Multitasking operating systems efficiently distribute system


resources such as CPU time, memory, and I/O devices across ongoing tasks, resulting in
maximum resource usage and system efficiency.
17. Differentiate between multiprogramming and multitasking.

Characteristic Multiprogramming Multitasking

In multiprogramming operating In Multitasking operating system, The


system, the operating system processor is typically used in time
simply switches to, and executes, sharing mode. Switching happens
Definition another job when current job needs when either allowed time expires or
to wait. where there is another reason for
current process needs to wait
(example process needs to do IO).
The main purpose is to reduce the The main purpose is to further extend
Purpose CPU idle time for as long as the CPU Utilization concept by
possible. increasing responsiveness.
Multi-programming increases CPU In multi-tasking it increases
Main Advantage utilization by organizing jobs. responsiveness along with increase of
CPU utilization.
Execution of process takes more Execution of process takes less time.
Execution Time
time.
18. What are some examples of real-time applications where real-time operating systems
are used?
Real-time operating systems are used in various applications such as:
• aerospace systems
• automotive control systems
• industrial automation
• medical devices and multimedia processing, where precise timing and responsiveness
are critical.
19. How multiprocessor operating system improves computing?
Performance Enhancement: Multiprocessor systems distribute tasks among multiple
processors or cores, enabling parallel execution and faster task completion, thereby enhancing
system performance.

ANUM NISA 4
COMPUTER SCIENCE (XII)

Increased reliability: Multiprocessor systems can continue to operate even if one processor
fails, as the remaining processors can continue to execute tasks.
Better scalability: Multiprocessor systems can be scaled more easily than single-processor
systems, as additional processors can be added to the system to handle increased workloads.
20. Write disadvantages of multiprocessing operating system.
Increased complexity: Multi processing systems are more complex than single-processor
systems, and they require additional hardware, software, and management resources.

Higher power consumption: It require more power to operate than single- single-processor
systems, which can increase the cost of operating and maintaining the system.
Difficult programming: Developing software that can effectively utilize multiple processors
can be challenging, and it requires specialized programming skills.

Synchronization issues: Multi processing system require synchronization between


processors to ensure that tasks are executed correctly and efficiently, which can add
complexity and overhead to the system.
21. What is the purpose of using parallel processing operating system?
Purpose of Parallel Processing Operating System is to:
• Make computers work faster and more efficiently.
• Enable computers to do multiple tasks simultaneously.
• Distribute tasks across the processing units to enhance performance, scalability, and
resource utilization.
• Ultimately improve overall system efficiency.
22. How Distributed Operating system helps to improve computing? Support wer answer
with at least three advantages.
A Distributed Operating system manages components of software on independent computers
connected to the network. Following are the advantages of Distributed Operating system: 1) It
can have the computing power of multiple computers 2) It provides fast execution and hence
improve efficiency.
3) A system failure/ crash of one site in a distributed system does not affect the others, the
remaining sites can continue operating.
23. Differentiate between single user and multi user operating system.

Characteristic Single User Operating system Multi-user operating system

Definition Designed for use by a single user at a Designed to support multiple users
time. accessing the system simultaneously.
User Interaction Typically provides a single user Provides multiple user interfaces,
interface for interaction with the allowing multiple users to log in and
system. work concurrently.
Resource Resources are dedicated to a single Resources are shared among multiple
Management user so management is easy. users, with the operating system
managing access and allocation.

ANUM NISA 5
COMPUTER SCIENCE (XII)

Examples MS-DOS Linux, Unix


24. Explain the characteristics and requirements of embedded operating systems in terms
of size, speed, and real-time capabilities.
Embedded operating systems are characterized by their small size, fast boot times, and
realtime capabilities They are designed for devices with limited resources, with a focus on
efficiency and dependability. These systems often need to operate in real-time responding to
external events with minimal delay.
25. Discuss the typical applications and industries where embedded operating systems are
commonly used.
Embedded operating systems find applications in various industries, including automotive (for
in-car entertainment systems and engine control units), consumer electronics (smartphones,
smart TVs), industrial automation (control systems, sensors), medical devices (patient
monitoring systems, medical imaging devices), and IoT (Internet of Things) devices (smart
home devices, wearable technology).
26. Why process management is an essential function of an operating system?

Process management involves creating, scheduling, executing, and terminating processes


within an operating system. Process management is responsible for allocating and managing
system resources, such as CPU time, memory, and I/O devices, among competing processes.
It is essential for managing system resources efficiently, facilitating multitasking, and ensuring
that programs can execute concurrently without interfering with each other.

27. Differentiate between process and program.

Characteristic Program Process

It is a set of instructions or code


It is created by the operating
stored in secondary storage
Definition system when a program is loaded
(such as a hard disk or flash
into memory and executed.
memory).
Passive or static entity consisting Active or dynamic entity
of code instructions which does representing the execution of a
Nature
not change until modified. program which changes
continuously during execution.
Stored as a set of instructions on
Created in memory when loaded
Storage secondary storage (e.g., hard
for execution.
disk).
Does not consume system
Resource Actively consumes CPU time,
resources until loaded into
Consumption memory, and other resources.
memory and executed.
Example An executable file, such as a An instance of a program, like a
program written in C++ or Java. web browser or word processor
running on a computer.

ANUM NISA 6
COMPUTER SCIENCE (XII)

28. Why is memory management required? Give any three reasons.


Memory management in operating systems serves several crucial functions:
Resource Allocation: By allocating and deallocating memory as per requirement, resource
wastage is minimized.
Supports multi-programming: Effective memory management enables the execution of
multiple processes simultaneously.
Enhances operational speed: Optimal memory management reduces system latency,
thereby speeding up operations.
System Stability: Proper memory management techniques help maintain system stability by
preventing memory leaks, and other memory-related errors that could lead to system crashes
or instability.
29. What is swapping in context of memory management?
Swapping is a memory management technique used by operating systems to manage memory
resources effectively by moving entire processes or parts of processes between main memory
(RAM) and secondary storage (usually a hard disk).
The swapping process involves two main operations: swap in and swap out.
Swap Out:
Swap out refers to the process of moving a process or part of a process from main memory
(RAM) to secondary storage (e.g., a hard disk).
Swap In:
Swap in refers to the process of moving a process or part of a process from secondary storage
(hard disk) into main memory (RAM).
30. Discuss some tasks performed by OS during the performance of the function of
memory management?
The following are some of the tasks performed by operating system:
• Allocate and de-allocate memory before and after process execution.
• Keep track of used memory space by processes.
• Minimize fragmentation issues.
• Proper utilize main memory by swap-in and swap-out processes from memory.
31. Briefly explain the function of file management performed by operating system.
An operating system is used to manage files and folders of computer system. A file is a
collection of specific information stored on secondary storage. File management is the process
of manipulating, creating, modifying, and deleting the files in computer system. The following
are some of the tasks performed by operating system:
• Create new files in computer system and place them at specific locations.
• Help to share files among different users.
• Store and manage the files in separate folders.
32. Briefly explain the function of I/o management performed by the operating system.
Input/output (I/O) management is an important function performed by the operating system to
facilitate communication and interaction between the computer system and its peripherals,
such as keyboards, microphone, displays, storage devices, and network interfaces.
The primary functions of I/O management by the operating system include:

ANUM NISA 7
COMPUTER SCIENCE (XII)

Device Recognition and Configuration:


The OS identifies and configures peripheral devices, loading appropriate drivers and initializing
settings.
I/O Scheduling and Error Handling:
The OS schedules and prioritizes I/O requests, implements buffering and caching for
performance optimization, and handles errors for data integrity and system reliability.
33. How secondary storage is managed by the operating system?
Secondary storage, such as hard drives, solid-state drives (SSDs), and optical discs, is
managed by the operating system through several key functions:
File System Management:
Organizes and manages data using file systems, enabling creation, deletion, and manipulation
of files and directories.
Storage Allocation and I/O Operations:
Allocates storage space, handles disk I/O operations, and optimizes storage utilization for
efficient data access.
Disk Maintenance and Recovery:
Performs disk maintenance tasks, such as error checking and data recovery, ensuring disk
health and reliability.
34. Explain the states of the process with the help of a diagram.
The states of a process in an operating system can be visualized using a state transition
diagram. Here's an explanation of the five states of a process along with a diagram:

New:
The process is being created but has not yet been admitted to the system. This state occurs
when the process is initiated by the user or another process.
Ready:
The process is ready to execute and is waiting for CPU time. It has been loaded into main
memory and is waiting in the ready queue to be dispatched by the CPU scheduler.

ANUM NISA 8
COMPUTER SCIENCE (XII)

Running:
The process is currently being executed by the CPU. It is actively performing its tasks, and its
instructions are being executed.
Waiting (Blocked):
The process is waiting for some event to occur, such as an I/O operation to complete, a signal
from another process, or a resource to become available. It is temporarily blocked and not
ready to execute.
Terminated (Exit):
The process has completed its execution or has been terminated by the operating system or
another process. It is removed from memory, and its resources are deallocated.
35. Differentiate between process and thread along with one example of each.

Process Thread

An instance of a program being executed. A lightweight unit of execution within a


process. (A subset of process)
Each process has its own memory space Threads within the same process share
and resources allocated by the operating the same memory space and resources.
system.
Processes are isolated from each other. Threads share memory space and
Changes to one process do not affect resources within the same process.
others.
Each process executed separately. Multiple threads within a process can
execute concurrently.
a computer system running multiple Within a word processor application,
applications simultaneously, such as a threads handle tasks like text input, spell
web browser, a text editor, and a media checking, and auto-saving concurrently.
player. Each of these applications
operates as a separate process.
36. Write any difference between multithreading and multitasking.

Characteristic Multithreading Multitasking

Definition The process of executing The process of executing multiple


multiple threads within a single processes simultaneously, each
process concurrently, sharing the with its own memory space and
same memory space and resources.
resources.
Memory Threads share the memory Each process has its own memory
space of the process, leading to space, resulting in higher memory
more efficient memory usage. usage.

ANUM NISA 9
COMPUTER SCIENCE (XII)

Speed (Context Typically, faster context Context switching between


switching) switching between threads due processes may be slower due to
to shared memory and the need to switch between
resources. memory spaces.
Example A web browser may use Running multiple applications
multithreading for tasks like simultaneously, such as a web
interpreting, fetching data, and browser, text editor, and media
handling UI. player.

37. Differentiate between Multiprogramming and multiprocessing.

Characteristic Multiprogramming Multiprocessing

Definition The process of loading several The process of running multiple


programs in main memory and processes or programs
executing one program at a time simultaneously, utilizing multiple
by single CPU. CPUs.
Memory Usage Utilizes memory efficiently by Requires more memory resources
switching between programs in as each process typically has its
memory. own memory space and resources.
Efficiency In this, one process can be In this, more than one process can
executed at a time so less be executed at a time so more
efficient. efficient.
Speed It takes more time to process the It takes less time for job
jobs. processing.

Chapter#2 SDLC
1. Write the importance/purpose of the system development life cycle.
The basic purpose of SDLC is to develop a system in systematic way in the perfect
manner.
• SDLC ensures quality assurance through clear requirements, design specifications,
and testing procedures.
• It facilitates risk management by identifying potential challenges early.
• Effective resource management is achieved by allocating personnel, time, and
budget efficiently.
• Communication and collaboration among stakeholders are promoted throughout the
development process.

ANUM NISA 1
0
COMPUTER SCIENCE (XII)

• It enables change management by providing a controlled framework for


implementing modifications.
Documentation at each stage ensures the collection and maintenance of relevant
information. Ultimately, SDLC aims to deliver high-quality software solutions that meet
customer expectations and maximize satisfaction.
2. Write the main objective of SDLC.
The main objectives of the System Development Life Cycle (SDLC) are:
• Deliver high-quality software solutions that meet user requirements.
• Efficiently manage resources such as personnel, time, and budget throughout the
development process.
• Identify and resolve potential risks early to minimize their impact on project success.
• Maximize the productivity
3. Write down four responsibilities of any two personnel involved in SDLC. Answer: (any
four valid points of each) 1. System Analyst Responsibilities:
i. Defines technical requirements by consulting with clients, evaluating procedures and
processes
ii. Implements computer system requirements by defining and analyzing system
problems
iii. Interacts with designers to understand software limitations
iv. Develops solution by preparing and evaluating alternative workflow solutions v.
Provides reference by writing documentation 2. Project Manager Responsibilities:
i. Ensures the development team has everything they need to get the work done.
ii.Manages meetings and communication with the client and the software development
team. iii. Distributes the tasks among the members of development team iv. Controls
the development process, and coordinates team activities. v. Responsible for time
management and risk management etc.
4. What is the role of stakeholder in SDLC? List any two responsibilities of the
stakeholder involved in Coding phase.
Role of Stakeholder:
Stakeholder in SDLC are people or groups within or outside the organization that are
actively involved in software project. They have a direct impact on software project either
by planning, developing, or using it.
Stakeholder involved in Coding phase in SDLC is a technical person called Programmer.
Following are the responsibilities of the Programmer:
• He/she writes/ develops the instructions or computer programs using programming
languages to solve problems.
• He/she modifies and manages code after testing it.
5. What is the purpose of Design phase in SDLC? Also write down the importance of
flowchart in designing of a system.

Design Phase in SDLC:

ANUM NISA 1
1
COMPUTER SCIENCE (XII)

The purpose of the Design Phase is to transform the requirements into detailed system
design specifications. The developers create the high-level design/ logical structure of
overall project that can be implemented in programming language. This phase also defines
the ways through which user can interact with the system.

Flowchart:

A flowchart is a pictorial representation of step-by-step solution of a problem. It represents


the workflow by using labelled symbols with flow lines. It is used to visualize the
execution code.
6. What is the role of Testing/ verification phase in System Development Life Cycle?

ROLE OF TESTING/ VERIFICATION PHASE (at least any three valid points)

• Testing/ verification phase in SDLC examines the system for functionality and quality
by
• discovering problems and errors.
• It evaluates the capabilities of code/programs.
• It helps to verify proper integration and interaction of each component in the system.
• It helps in reviewing of requirements, design, and code.
• It helps in identifying defects and ensuring they are addressed before system
deployment.
• It also plays important role in lowering the maintenance cost of the system.
7. Which phase of SDLC is used to find the strength and weaknesses of system being
developed?
A feasibility study is used to find the strength and weaknesses of system.
It is conducted in order to objectively uncover the strengths and weaknesses (SWOT
Analysis). A SWOT analysis is used to study the internal and external environments of a
company and is part of a company’s strategic planning process. It can help to identify and
assess the opportunities and threats present in the natural environment, the resources
required for the project, and the prospects for success.
It is conducted in order to find answers to the following questions:
Does the company possess the required resources and technology?
Will the company receive a sufficiently high return on its investment?
A feasibility report should include the following sections:
• Description of the Product/Service
• Technology Considerations
• Product/ Service
• Marketplace
• Identification of the Specific Market
• Marketing Strategy
• Organizational Structure

ANUM NISA 1
2
COMPUTER SCIENCE (XII)

• Schedule
• Financial Projections
8. What is the purpose of requirement engineering? Differentiate between the two main
types of requirements.
The purpose of requirement engineering is to systematically gather, analyze, document,
and validate the requirements of a software system to ensure that it meets the needs of
stakeholders and delivers the desired functionality and quality.

Characteristic Functional Requirements Non-Functional Requirements


Definition Specify what the system Specify how the system should
should do or the functions perform or the quality attributes
it should perform. it should possess.
Focus Focus on specific tasks, Focus on attributes such as
operations, or processes that performance, usability, reliability,
the system must accomplish. security, scalability, and
maintainability.
Use Helps we verify the Helps we to verify the performance
functionality of the software. of the software.
Examples User authentication, data Response time, user interface
validation, report design, system availability, data
generation, payment integrity, system reliability, etc.
processing, etc.
9. Differentiate between Requirement validation and verification.

Criteria Requirement Validation Requirement Verification


Definitio The process of ensuring that the The process of ensuring that
n gathered requirements accurately the implemented software
represent the needs and expectations of system meets the specified
stakeholders and are feasible for requirements and functions
implementation. as intended.
Objectiv It checks whether the software/system It checks whether the
e conforms to specifications or not. software/system meets the
requirements and
expectations of a customer
or not.
Focus Focuses on ensuring that the right Focuses on confirming that
requirements are gathered and the implemented system
documented to meet stakeholder needs. meets the documented
requirements and functions.

ANUM NISA 1
3
COMPUTER SCIENCE (XII)

Type of Verification is the static testing. Validation is the dynamic


testing testing.
Example Conducting stakeholder reviews, Conducting testing activities
prototyping, and requirements such as unit testing,
walkthroughs to validate integration testing, system
requirements. testing, and acceptance
testing to verify system
functionality.
10. What is the riskiest method of system deployment/implementation in SDLC?
Direct implementation is a type of implementation in which old system is directly replaced
by new system. It is the riskiest implementation. It may be used when time is short. It is
also called crash implementation.

11. What is the safest (cheapest) method of system deployment/implementation in


SDLC? The safest method of system deployment in SDLC is the phased method.
• This method involves deploying the system gradually in stages or phases, allowing
for complete testing at each stage and reducing the risk of failures.
• Users are involved throughout the process, providing feedback and adapting to
changes gradually, which improves user adoption and satisfaction.
• Overall, the phased approach offers reduced risk, improved quality, and better
alignment with business goals compared to other deployment methods.
12. What is the most expensive method of system deployment/implementation in
SDLC? Parallel deployment is the most expensive method of system
deployment/implementation in SDLC.
 It involves running the new system alongside the existing system, requiring
duplication of resources and efforts.
Costs include additional infrastructure, maintenance, support services, data synchronization, and training expenses.
 Parallel deployment leads to higher operational costs due to the simultaneous
maintenance of two systems
13. Differentiate between customer and clients.

Aspect Customer Client


Definition A customer is someone who A client is someone who uses the
purchases goods or services services of a professional person.
from a business.

Focus Focuses on obtaining solutions to meet specific needs or


products or services to fulfill objectives.
personal needs or desires.

ANUM NISA 1
4
COMPUTER SCIENCE (XII)

Examples Someone buying software for A big company hiring a software


personal use, like Microsoft company to make a custom system, or a
Office or a video game. government agency hiring a firm for
online services.
14. Write the responsibility of personnel involved in the testing phase of SDLC. Software
testers are responsible for:
• Planning and designing test cases based on project requirements.
• Executing test cases to verify software functionality and performance.
• Documenting test results, identifying defects, and collaborating with stakeholders for
resolution.
15. Why design phase is also known as the architectural phase?
The design phase is often referred to as the architectural phase because:
• It focuses on creating the overall structure and blueprint of the software system,
similar to architectural planning in construction.
• It involves conceptualizing the system's components, their interactions, and
dependencies, similar to designing the framework of a building.
• It highlights the selection and implementation of design patterns and principles to
ensure scalability, flexibility, and maintainability of the software, similar to the
architectural considerations in building design.
16. Briefly explain the different types of feasibility.
Technical Feasibility: Assesses if the proposed technology and infrastructure can support
the system's development and implementation.
Economic Feasibility: Assesses the project's financial viability and benefits, including
costs, returns on investment, and cost-benefit analysis.
Operational Feasibility: Determines if the proposed system aligns with organizational
goals and is acceptable to end-users, considering usability, user acceptance, and impacts
on existing processes.
Schedule Feasibility: Examining if the project can be completed within the allocated time
frame and meets predefined deadlines, considering project timelines, resource availability,
and potential risks.
Legal and Regulatory Feasibility: Ensuring that the proposed project complies with
relevant laws, regulations, and industry standards, including data protection laws,
intellectual property rights, and industry-specific regulations.

Chapter#3 Object Oriented Programming in C++


1. What is C++?
C++ is a high-level programming language developed by Bjarne Stroustrup at Bell Labs in the
early 1980s.

ANUM NISA 1
5
COMPUTER SCIENCE (XII)

Its main purpose is to provide a flexible and powerful tool for software development, combining
the efficiency of the C programming language with additional features for object-oriented
programming (OOP). C++ allows developers to write code that is both procedural and
objectoriented, enabling them to create modular, reusable software components while
maintaining control over system resources and performance.
2. Define computer program. Also differentiate between source code and object code. A
computer program is a set of instructions written in a programming language that directs a
computer to perform specific tasks or operations.

Source Code Object Code


The code written in human-readable text The code represented in machinereadable
form, containing instructions and binary form, consisted of compiled or
commands in any computer programming translated instructions.
language.
Easily understandable and modifiable by Not easily understandable by humans and
programmers. difficult to modify.
Cannot be directly executed by the Directly executable by the computer after
computer; needs to be compiled or compilation or translation from source
interpreted into object code first. code.
Examples include C++, Java, or Python Examples include executable files or
source files. machine language code generated from
source code.

3. Write the purpose of using header files.

Header files in C++ are the files that contain information about definitions or declarations of
functions, classes, variables, constants, and other entities used in a program. These
declarations provide the interface or blueprint for these entities, allowing other parts of the
program to use them without needing to know their implementation details.
Each header file contains information about specific entity, e.g. <math.h> contains information
or code for performing mathematical functions such as finding square root of a number.
Header files typically have a ".h" extension and are included in source files using the #include
preprocessor directive.
4. Write the purpose of using preprocessor directives.
The preprocessor directive is used to include a header file at the beginning of program. A
preprocessor directive is not a normal program instruction to be executed by the CPU. It is a
code for the compiler to include a header file.
Normally two preprocessor directives (#inculde & #define) are used in C++.
The syntax of preprocessor directive to include a header file in a program is:
# include <name of header file>
It begins with a # sign, followed by the word include and then the name of header file is written
within angled brackets.

ANUM NISA 1
6
COMPUTER SCIENCE (XII)

The #define preprocessor directive creates symbolic constants. The symbolic constant is
called a macro and the general form of the directive is – #define macro-name replacement-
text
#define PI 3.14159
5. Differentiate between header file and preprocessor directives.

Characteristic Header File Preprocessor Directive


Purpose It contains information about definitions It is used to include a header
or declarations of functions, classes, file at the beginning of
variables, constants, and other entities program.
used in a program.
Content Contains actual declarations and Contains instructions to
definitions of entities used in the control the behavior of the
program, such as functions, classes, preprocessor, such as
variables, etc. conditional compilation, file
inclusion, macro definition,
etc.
Usage Included in source files #include Used directly in source files
using directive to provide access using preprocessor directives
declarations and definitions. to like #define, #include, etc.,
to control the compilation
process.
Example iostream.h, conio.h, string.h, #define PI to define
math.h 3.14159 a
etc. macro for the
#include <iostream> to include value of pi.
declarations from the
iostream library in a
source file.
6. Why reserve words cannot be used as variable name?
Using reserved words as variable names is not allowed in programming languages due to the
following reasons:

Ambiguity and Confusion: Using reserved words as variable names creates ambiguity and
confusion in code due to their predefined meanings in the language syntax, making it unclear if
they are intended as variables or have reserved significance.

Syntax Conflicts: The use of reserved terms as variable names may cause syntax issues.
The compiler may perceive the reserved word as part of the language syntax rather than a
variable name, resulting in compilation issues or unexpected behavior.

ANUM NISA 1
7
COMPUTER SCIENCE (XII)

Readability and Convention: Variable names should reflect the goal or meaning of the data
they represent, which improves code readability. Using reserved words as variable names is
against this standard and may make the code more difficult to understand.
7. Explain the basic structure of C++ program with the help of an example.
preprocessor directives void
main()
{
body of main() function
}
A C++ program starts with preprocessor directives, followed by the line void main function and
then the body of the main () function is written within curly brackets { }. Body of main() function
consists of executable statements. These statements perform a specific task when the
program is executed by the CPU. There is no restriction on the number of statements that can
be written in the body of the main () function.
To understand the structure of program, consider the following program.
# include <iostream.h> void
main()
{
cout<<"Information Technology";
}
Explanation:
#include<iostream.h> a preprocessor directive. This program prints a message on the
screen. Therefore, iostream.h header file is included which contains the code for performing
input/output operations.
void main ()
This line identifies the main function of the C++ program. All C++ programs must have main()
function. If a program consists of more than one function, the location of main() does not
matter. In C++ program the main () function is always executed first.
cout<<"Information Technology";
This is a C++ statement. The meaning of this statement is to print the message "Information
Technology" on the screen. This statement is written within the curly brackets and is called
body of the main () function.
8. Write the purpose of using statement terminators.

The "statement terminator" in C++ is a symbol that marks the end of a statement. In C++, the
semicolon “;” serves as the statement terminator. It is placed at the end of most statements to
indicate to the compiler that the current statement has ended. cout<<"Information
Technology";
The statement ends with a semicolon to marks its end. If “;” is missing the compiler will give
syntax error number and also the message that “;” is missing. The error number and message
may vary depending on the compiler used.

ANUM NISA 1
8
COMPUTER SCIENCE (XII)

9. Why is it important to write Comments in a program? Also differentiate its two types.
Comments are notes/ explanatory remarks used to document sections of a program. They are
intended for people who may be reading the source code. The readers can easily understand
the logic of the program by documented code.

Two types of comments are:

1. Single-line comments

2. Multi-line comments

Feature Single-Line Comment s Multi-Line Comments


Definition The Comments that span a single line of The Comments that can span multiple
code. lines of code.
Syntax Begin with / . Begin with / and end with * .
/ * /
Example int x = 5; // Initializing variable /* This is a multi-line comment
x that
spans multiple lines. It can be
used
for documentation or
temporarily
disabling code.
*/
10. Differentiate between constant and variable.

Feature Constant Variable


Definition A value that does not change A name of memory location where
during program execution. data is stored, and its value may
change during program execution.
Data Can be a number, character, o r Can store values of different data
Type character string. types, like number, text etc.
Syntax Single character constant is wr itten A variable can only be defined
within single quotes, and string using the standard variable
constant within double quotes. definition syntax.
Example const int MAX_VALUE = int count =
100; 0;
#define pi 3.14

11. What are rules for specifying variable name in C++?


The following are the rules for naming a variable.

ANUM NISA 1
9
COMPUTER SCIENCE (XII)

i. The first character of a variable name must be alphabet or underscore.


ii. The characters allowed in a variable name are:
- Underscore _)
- Digits (0 to 9)
- Upper-case letters (A to Z)
- Lower-case letters (a to z)
An upper-case letter is considered different from a lower-case letter. For example, the
variable SUM is different from Sum or sum. The underscore is generally used to improve
readability. For example, the variable overtime may also be written as over_time. iii.
Special symbols such as $, @,%, #, etc. are not allowed. iv. Blank space or comma is
not allowed.
v. Reserved words of C++ are not allowed to be used as a variable name.
12. Write down the reasons of the following invalid variable names:
i. 3a ii. S$ iii. Float
Reasons of invalid variables
• 3a Variable name is started with a digit which is invalid.
• s$ No special character like $ is allowed except underscore 
float It is a reserved words which is not allowed as variable name.
13. Write different datatypes and their use in C++?

In C++, data types are used to define the type of data that a variable can hold. They specify
the size and format of the data, as well as the operations that can be performed on it.
Here are some common data types in C++:
Integer Types:
int: Integer data type that can hold whole numbers.
short: Short integer data type, typically smaller than int. long:
Long integer data type, typically larger than int. unsigned int,
unsigned short, unsigned long: Unsigned integer types that
can only hold non-negative(positive) values.
Floating-Point Types:

float: Single-precision floating-point data type. double: Double-precision floating-point


data type, providing higher precision than float.
long double: Extended-precision floating-point data type, providing even higher precision than
double.
Character Type:
char: Character data type that can hold a single character.
Boolean Type:
bool: Boolean data type that can hold either true or false values.
14. Why different datatypes are used in C++?

ANUM NISA 2
0
COMPUTER SCIENCE (XII)

Different data types require different amounts of memory to store their values. By choosing an
appropriate data type, we can optimize memory usage and avoid unnecessary memory
wastage. e.g. datatype int takes 4 bytes of memory while char takes 1 byte of memory.
15. Draw the table for int datatype along with no. of bytes it occupied range of numbers.
Number of bytes reserved may vary depending on compiler (like turbo C++ reserves 2 bytes
for each integer element and Dev C++ reserves 4 bytes, both will be considered correct)

Data Type Number of Minimum Value Maximum Value


Bytes
int 4 -2,147,483,648 (-2^31) 2,147,483,647 (2^31 - 1)
unsigned int 4 0 4,294,967,295 (2^32 - 1)
short int 2 -32,768 (-2^15) 32,767 (2^15 - 1)
unsigned short 2 0 65,535 (2^16 - 1)
int
long int 4 -2,147,483,648 (-2^31) 2,147,483,647 (2^31 - 1)
unsigned long 4 0 4,294,967,295 (2^32 - 1)
int
16. What is a named constant or const qualifier? Write statements for the following values
that create named constants: a) 3.14159 b) 1609 Named constant or constant qualifier:
A literal/ constant may be given name to represent in a program. A named constant is like a
variable, but its content is read-only and cannot be changed while the program is running. It is
defined with a qualifier const.
a) 3.14159 const float PI
= 3.14159; b) 1609
const int A = 1609;
17. Differentiate between declaration and initialization of a variable with example.

Declaration of a Variable Initialization of a Variable


1. Variable declaration specifies the name Variable is initialized when it is
and data type of a variable to a compiler. assigned a value before use.
2. Variable declaration gives details aboutThe specified initial value stored in a
the properties of a variable. variable to avoid garbage data.
3. Example: int Example: int s = 0; // initialize
char ch; s; zero to 'Y'
char ch = 'Y'; // initialize
to
18. Why is it necessary to declare a variable before use?

It is necessary to declare a variable before use in order to tell the compiler about the variable's
existence, data type, and memory allocation requirements. This allows the compiler to allocate

ANUM NISA 2
1
COMPUTER SCIENCE (XII)

memory for the variable and perform type checking to ensure that the variable is used
appropriately in the program.

Declaring variables before use helps prevent errors and ensures proper memory management
and type safety in the program.

19. Differentiate between implicit and explicit typecasting.

Feature Implicit Typecasting Explicit Typecasting


Definition It is automatically performed by It is user-defined conversion of
the compiler and converts result one data type to another and
of expression to higher data type.
requires a programmer to
It does not require any special explicitly specify the type
syntax. conversion using special operator
or syntax.
Occurrence Occurs implicitly without the need Requires explicit instruction from
for programmer intervention. the programmer.

Example int x = 10; double x =


5.0 / x; // Implicit 10.5; // Explicit
float y = from int to float. int y = (int) conversion
conversion x; from
double to int.
20. How to take input and show output in C++ program?
In C++, we can take input from the user using the cin object and display output using the cout
object.
Taking Input:
To take input from the user, we can use the >> operator with cin followed by the variable
where we want to store the input value.
Example:
int num;
cout << "Enter a number: ";
cin >> num;

Displaying Output:

To display output to the console, we can use the << operator with cout followed by the value
or variable we want to display.

Example: cout << "The number we entered is: " <<

num << endl;

ANUM NISA 2
2
COMPUTER SCIENCE (XII)

21. Write a C++ program that reads base and height of a triangle and displays its area by
using formula: area = ½ b h

#include <iostream>
using namespace std;

int main() {
// Declare variables to store base, height, and area
double base, height, area;

// Prompt the user to enter the base of the triangle


cout << "Enter the base of the triangle: "; cin >>
base;

// Prompt the user to enter the height of the triangle


cout << "Enter the height of the triangle: "; cin >>
height;

// Calculate the area of the triangle using the formula: area = 0.5 * base * height
area = 0.5 * base * height;

// Display the calculated area of the triangle


cout << "The area of the triangle with base " << base << " and height " << height << " is: " << area
<< endl;

return 0;
}

22. The following C++ code has compile time errors. The line numbers are written along the
left column. They are not part of the program code. Identify and correct errors:

ANUM NISA 2
3
COMPUTER SCIENCE (XII)

23. Differentiate between getch() and getche() function.

Feature getch() function getche() function


Functionality Reads a single character from the Reads a single character from the
keyboard without echoing(displaying) keyboard and echoes it to the
it to the console. console.
Buffer Does not wait for the user to press Does not wait for the user to press
Enter, and does not store the Enter, but stores the character in the
character in the input buffer. input buffer.
Echoing Does not echo(display) the character Echoes(display) the character to the
to the console. console immediately after it is
entered.
Usage Typically used for scenarios where Useful when we want the user to see
input is required without displaying it the character they are typing, such
on the screen, such as password as in interactive menus.
input.

ANUM NISA 2
4
COMPUTER SCIENCE (XII)

Example #include<conio.h #include<conio.h>


>
#include<iostream #include<iostream>
>
void void main()
main()
{ {
char char ch;
ch;
cout<<"Enter a cout<<"Enter a character:";
character:";
ch=getch() ch=getch()
; ;
cout<<The character we typed cout<<The character we typed
is
<<ch; is <<ch; }
}
The execution of the program is The execution of the program is
shown
below with the input character shown below with the input
a.
Enter a character a.
character: typed is a
The character we Enter a character: a is
Note that, when is read The character we typed ch
and
this function is Note that, when this is a
but it is
used, the input not function is used, the characte
character a stored input read and stored r a
in variable ch in variable and
displayed on the displayed on the
screen. screen.
24. Write the purpose of using escape sequence in C++.
Escape sequences are special characters used to control the output look on output devices.
These characters are usually not printed. These are used inside the output statement. The
main purpose of the escape sequence is to represent the characters that cannot be used
normally using the keyboard.
Additionally, escape sequences enable the inclusion of quotes (\" and \') and other special
characters within strings without causing syntax errors. Overall, escape sequences improve
code readability, formatting, and functionality by standardizing the representation of special
characters and controlling their behavior within strings and character literals.

ANUM NISA 2
5
COMPUTER SCIENCE (XII)

25. Write the purpose of any three commonly used escape sequences in C++.

escape Function
Sequence
\ It moves the cursor to the start of the next line.
n
\t It moves the cursor to the next horizontal tabular position.
\\ Inserts a backslash character.
\ Inserts a double quote character.
"
\' Inserts a single quote character.
\ Moves the cursor back one position, effectively erasing the
b previous character.

\r Moves the cursor to the beginning of the current line.


26. Write the purpose of using manipulators in C++?
The purpose of using manipulators in C++ is to control the formatting of output streams, such
as cout and cin. Manipulators are functions or objects that can be used to modify the behavior
of output streams, including setting precision, controlling the width of output fields, formatting
numbers etc.
They allow programmers to achieve specific formatting requirements and improve the
readability and presentation of output data in their C++ programs.
Manipulators provide a convenient and flexible way to customize the appearance of output
without modifying the underlying data or code structure.

27. Write the purpose of following manipulators along with an example:


a. endl b. setw()

a. endl:
Purpose: The use of the endl C++ manipulator is to move the cursor to the beginning of the
next line. Moreover, its working is similar to the '\n' escape sequence.
Example:
cout << "Hello, ";
cout << "world!" << endl; // Inserts a newline character and flushes the buffer cout <<
"Goodbye." << endl; Output:
Hello, world!
Goodbye.

b. setw():

ANUM NISA 2
6
COMPUTER SCIENCE (XII)

Purpose: The setw() manipulator is used to set the width of the next output field. It allows
formatting output by specifying the minimum width that the output should occupy, with
additional spaces added as padding if necessary.
Example:
#include <iostream>
#include <iomanip> // Needed for setw()
using namespace std; int main() {
cout << setw(10) << "Name:" << setw(20) << "ABC XYZ" << endl;
cout << setw(10) << "Age:" << setw(20) << 25 << endl; return 0;
}

Output:
Name: ABC XYZ
Age: 25
28. Write the purpose of commonly used header files.

Header File Purpose


iostream.h Provides basic input/output operations such as ci and cou .
n t
conio.h Stands for console input/output. It manages input/output on console-
based applications.
math.h Provides basic mathematical operations such as sqrt( , pow() , etc.
)
string.h Provides several functions to manipulate strings such as strcmp()
(compare string), strcpy() (copy string), etc.
iomanip.h Provides manipulator functions such as setw( , end ,
setprecision(), etc. ) l

time.h Provides date and time operations.


29. Differentiate between assignment operator and equal to operator.

Feature Assignment Operator (=) Equal to Operator (= )


=
Purpose It assigns the value on the It compares two values for equality.
righthand side to the variable on And always return true or false on the
the left-hand side. basis of evaluation result.
Syntax Used to assign values. Used to compare values.
Example int x = if (x ==
10; 10)

ANUM NISA 2
7
COMPUTER SCIENCE (XII)

Meaning Assigns the value 1 to the Checks if the value of x is equal to 1 .


0 0
variable x.
Usage Used in variable initialization Used in conditional statements and
and assignment statements. expressions to compare values.
30. What are the assignment arithmetic assignment operators?
he assignment arithmetic operators in C++ combine arithmetic operations with assignment.
They are shorthand notations for performing an arithmetic operation on a variable and then
assigning the result back to the same variable.

Operator Description Example Equivalent


+ Adds the right operand to the left operand and x += x = x +
= assigns the result to the left operand. y; y;

-= Subtracts the right operand from the left x -= y; x = x - y;


operand and assigns the result to the left
operand.
*= Multiplies the left operand by the right operand x *= y; x = x * y;
and assigns the result to the left operand.
/= Divides the left operand by the right operand x /= y; x = x / y;
and assigns the result to the left operand.
%= Calculates the remainder of dividing the left x %= x = x %
operand by the right operand and assigns the y; y;
result to the left operand.

31. Differentiate between pre-test increment and post-test increment operator.

Feature Pre-test Increment Operator Post-test Increment Operator


( + ) ( i+ )
+i +
Timing of Increments the value of the Increments the value of the
Operation variable before using it in the variable i after using it in the
current expression. current expression.
Effect on The value of i is The value of i is
Value 1 incremented by 1 after t incremented by
evaluated. before the evaluated. he expression is
expression is
Example int i = int i =
5; 5;
int j = + int j = i+

ANUM NISA 2
8
COMPUTER SCIENCE (XII)

+i; +;
Value of j j is assigned the value 6 . j is assigned the value 5 .
after
executio n
Value of i i is incremented 6 . i is incremented 6 .
after to to
executio n

Note: same can be used for decrement operators just by changing the context of
increase by one to decrease by 1.
32. Differentiate between relational and logical operators.

Feature Relational Operators Logical Operators


Purpose It is used to compare two values. It is used to perform logical
operations such as AND, OR, and
NOT.
Examples == (equal != (not equal & (logical AND), `
to), > (greater &
to) < less
, ( less than or
than), equal
to) than),
greater
<= (
, than or
>= (
to) equal
Result Relational operators return a Logical operators also return a
boolean value (true or false) boolean value based on the
based on the comparison of the evaluation of the operands, but
operands. they perform logical operations on
Boolean expressions(T/F).
Usage Typically used in conditional Used to combine and manipulate
statements and expressions to boolean expressions to control the
make decisions based on flow of execution in a program.
comparisons of values.
Evaluation Relational operators evaluate the Logical operators evaluate boolean
relationship between two values expressions and return a result
and return a result based on the based on the logical operations
comparison. performed on the operands.
33. The following statement should determine if count is outside the range of 0 through 100.
What is wrong with it? if (count < 0 && count > 100)

ANUM NISA 2
9
COMPUTER SCIENCE (XII)

if (count < 0 | | count > 100)

Logical OR ( | | ) operator is required to determine, if count is outside the range of 0 through 100.

34. What will be the output of the following program segment?

int x = 3, y = 17;
cout << x / y << y / x << (y / x) + (x % y);

Output:
058
35. Write down the output of the following statements.
i. (x > 0) && (y < 10) where x = 5, y = 5
ii. 13 + 21 % 4 – 2
iii. int m = 2, n = 4; m *= 2; n += m;
ANSWER
i. true/1 (5>0 && 5<10) -> (T && T) -> T
ii. 12 (13 + 1 – 2) -> (14-2) -> 12 iii.
m=4n=8
36. Compare unary, binary, and ternary operators with one example of each. Unary
Operator:
Unary operator takes single operand in an expression or statement and calculate the result.
Example: Increment operator (++), n++ Binary Operator:
Binary operator takes two operands in an expression or statement and calculate the result.
Example: Relational operator (>), a > b; Ternary Operator:
Ternary operator takes three operands in an expression or statement and calculate the result.
Example: Conditional operator (?:), (a < b) ? s = a : s=b;
37. Determine the output of the following code segment:
int i=2; cout
<<i; cout<<i++; cout <<+
+i; Output:
224
38. Write an expression to test each of the following relationships: (any three) a. age is from
18 to 25
b. temperature is less than 40.0 and greater than 25.0
c. year is divisible by 4 (Hint: use%)
d. speed is not greater than 80
e. y is greater than x and less than z
f. w is either equal to 6 or not greater than 3

ANUM NISA 3
0
COMPUTER SCIENCE (XII)

a. Age is from 18 to 25:


age >= 18 && age <= 25
b. Temperature is less
than 40.0 and greater
than 25.0:
temperature < 40.0 && temperature > 25.0 c.
Year is divisible by 4:
year % 4 == 0
d. Speed is not greater than 80:
speed <= 80
e. y is greater than x and less than z:
y > x && y < z
f. w is either equal to 6 or not greater than 3: w == 6 || w <= 3
39. Write a C++ program to read a character and check whether the entered character is a
lowercase or upper case? #include <iostream>
using namespace std;

int main() {
char ch;

// Prompt the user to enter a character


cout << "Enter a character: ";
cin >> ch;

// Check if the entered character is a lowercase letter


if (ch >= 'a' && ch <= 'z') {
cout << "The entered character '" << ch << "' is a lowercase letter." << endl;
}
// Check if the entered character is an uppercase letter
else if (ch >= 'A' && ch <= 'Z') {
cout << "The entered character '" << ch << "' is an uppercase letter." << endl;
}
// If the entered character is not a letter
else {
cout << "The entered character '" << ch << "' is not a letter." << endl;
}

return 0; }
40. What will be the output of the following C++ program?

ANUM NISA 3
1
COMPUTER SCIENCE (XII)

void main ()
{ int a = 15, b;
b = a%9;
a = ++a-a(--b);
cout<<"a="<<a<<"b<<b<<endl; cout<<"a
now ="<<a++<<"b="<<b++<<endl;
cout<<"value of a="<<++a<<"value of
b="<<b<<endl; } OUTPUT:
1. b = a % 9;: The remainder of a divided by 9 is calculated and stored in
b. So, b becomes 6 (15 % 9 = 6).
2. a = ++a - a * (--b);  --b decrements b to 5.
• ++a increments a to 16.
• a * (--b) multiplies the current value of a (16) by the decremented value of b (5), resulting in 80.
 ++a - 80 performs the subtraction (16 - 80), resulting in -64.
So, a becomes -64.
3. cout << "a=" << a << " b=" << b << endl;: Outputs: a=-64 b=5.
4. cout << "a now =" << a++ << " b=" << b++ << endl; Outputs the current
value of a (-64) and then increments a (-63).
Outputs the current value of b (5) and then increments b (6).
So, outputs: a now =-64 b=5.
5. cout << "value of a=" << ++a << " value of b=" << b << endl;
Increments a and outputs the incremented value (from -63 +1 to -62).
Outputs the current value of b (6).
So, outputs: value of a=-62 value of b=6
Therefore, the output of the given C++ program will be;
a=-64 b=5 a now =-64 b=5
value of a=-62 value of b=6

41. Answer the following questions:


a. Write a C++ statement that gets a numerical value from the keyboard and
places it in the variable temp.
b. What header file must be included in C++ program to use setw()?

a. To get a numerical value from the keyboard and place it in the variable temp in C+
+, we can use the cin statement: int main() {
int temp; // Assuming temp is an integer variable
cout << "Enter a numerical value: "; cin >> temp;
return 0;
}

ANUM NISA 3
2
COMPUTER SCIENCE (XII)

b. To use setw() in a C++ program, we need to include the <iomanip> header file. So,
the header file required is <iomanip>:

42. Define the following and also give an example of each:


a. Expression b. Compound expression c. Relational expressions
a. Expression:
An expression is a combination of constants, variables and operators. Constants and variables
are operands and operators tell the computer what types of action to perform on the operands.
Expressions can include arithmetic operations, logical operations, relational operations, and
more. Example:
int result = a + b * 2; // Expression: a + b * 2
b. Compound Expression:
An expression that combines two or more conditions using logical operators, && or lI is called
compound expression. It can consist of multiple subexpressions combined together to form a
single expression. Example:
((ch>=’a')&&(ch<=’z'))lI((ch>='A')&&(ch<=’Z’)) c.
Relational Expression:
An expression that contains a relational operator to compare values of same type is called
relational expression. Relational expressions are used in programming to create conditions
based on which computer takes different path during program execution.
Example:
bool isEqual = (x == y); // Check if x is equal to y
bool isLessThan = (x < y); // Check if x is less than y
43. What will be the output of the following C++ statements?
a) cout<< "17/3 is equal to "<<17/3;
b) cout<< *10.0/4 is equal to "<<10.0/4;
c) cout<< "40/5%3*7 is equal to "<<(40/5%3*7); The outputs will be: a) 17/3 is equal to 5
b) 10.0/4 is equal to 2.5
c) 40/5%3*7 is equal to 14 (The expression 40/5 performs integer division, resulting in 8.
Then, 8%3 calculates the remainder when 8 is divided by 3, resulting in 2. Finally,
2*7 performs multiplication, resulting in 14.)
44. Evaluate the following expression that have integer and floating-point data types
according to C++ operator precedence.
a) 10.0+15/2+4.3 && 5>8
• Evaluate 10.0 + 15/2 + 4.3:
• First, perform the integer division 15/2, which results in 7 (integer division truncates
the decimal part).
• Then, add 10.0, resulting in 17.0.
• Finally, add 4.3, resulting in 21.3.
• Evaluate 5 > 8:
• This is a comparison expression that evaluates to false because 5 is not greater
than

ANUM NISA 3
3
COMPUTER SCIENCE (XII)

8.
• Evaluate the logical AND (&&) operator (Evaluate 21.3 && false)
• The expression 21.3 && false involves a logical AND operation between a non-zero
value (21.3, which is considered true in a Boolean context) and false.
• The result of a logical AND operation is false if any of the operands is false,
otherwise it is true.
• Therefore, the final result of the expression 10.0 + 15/2 + 4.3 && 5 > 8 is false.

Chapter#4 Control Structure


1. What are control structures? Define three basic structures used in C++

Control structures are a very important concept in computer programming. Control structures
allow programmers to control the flow of program execution. Three types of control structures are
used in programming, sequential, conditional and repetition structures.

Sequential structure refers to execution of instructions one by one in the sequence in which they
appear in the program from top to bottom till the last instruction.

Conditional structure, also known as decision making structure, refers to execution of


instructions based on a condition. If a condition is met a specific set of instructions are executed
otherwise control is transferred to some other part of the program. e.g. if, if else etc.

Iteration structure, also known as loop, refers to execution of same set of instructions several
times till a condition is met. E.g. for, while and do while loop.
2. Differentiate between if and if else statement.
Feature i Statement if- Statement
f else
Purpose Used when block of code Used when two codes of blocks need to
needs to be executed only if be executed, one if condition is true,
condition is true other if condition is false
Syntax if if
(condition) (condition)
{ code { code
block } block1 }
els
e
{ code
block2 }
Behavior Executes code block if Executes code block1 if condition is true,
condition is true executes code block2 if condition is false

ANUM NISA 3
4
COMPUTER SCIENCE (XII)

Example int x = 10; int x = 10;


if (x > 5) { if (x > 5) {
cout << "x is greater than cout << "x is greater than 5";
5"; } }
else
{
cout << "x is not greater than 5";
}
3. Why decision control structures are used?
Decision control structures are used in programming to alter the flow of execution based on
certain conditions. Many real-world problems require the program to handle complex logic and
make decisions based on multiple conditions.so Decision control structures allow the program
to execute different blocks of code based on specified conditions. By directing the flow of
execution based on conditions, decision control structures help in controlling the sequence of
operations within a program. This ensures that the program behaves as intended and performs
the necessary actions under different circumstances.
4. Differentiate between if-else-if and switch statement.
If- else- Statement switch Statement
if
Which statement will be executed Which statement will be executed is
depend upon the output of the decided by user.
relational expression inside if
statement.
Uses multiple else- statements for Uses single expression for multiple
multipleif choices
choices .
Tests for equality as well as logical Tests only for equality
expressions
Evaluates integer, character, or Evaluates only character or integer
logical type expressions values
Evaluates conditions sequentially Executes one case after another until
until a true condition is found, or the a break or end is reached.
else block is executed.
If the condition inside if statements is If the condition inside switch
false, then by default the else statements does not match with any
statement is executed. of cases, for that instance the default
statements is executed.

ANUM NISA 3
5
COMPUTER SCIENCE (XII)

Syntax: Syntax:
if (condition1) { // switch (expression/constant)
code block1 } else { case value1: // code block1 break;
if (condition2) { // case value2: // code block2 break;
code block2 } else default: // default code block
{ // code block3 } }

5. Write an if-else statement that assigns 1 to x if y is equal to 100, otherwise it should


assign 0 to x.
Answer:
if ( y = = 100)
x = 1; else x
= 0;
6. Rewrite the following using if-else statement cout << ( ( (num % 2) = = 0) ? "Even \ n" :
"Odd \ n"); Answer:
if ( num % 2 = = 0)
cout<< ”Even \n”;
else cout<< ”Odd \
n”;
7. Rewrite the following program segment using conditional operator. if (a > b) large = a;
else
large = b;
ANSWER
large = (a > b) ? a : b;
8. Answer the following C++ questions:
a. Write a switch code that prints Yes if a variable ch is 'y', prints No if ch is 'n', and
prints Unknown response otherwise.
b. Write a statement that uses a conditional operator to set the ticket to 1 if speed is
greater than 55, and to 0 otherwise.
c. Write an expression involving a logical operator that is true if limit is equal to 55
and speed is greater than 55.

a. Switch code:
char ch; switch (ch)
{ case 'y':
cout << "Yes";
break;
case 'n': cout
<< "No";
break;
default:

ANUM NISA 3
6
COMPUTER SCIENCE (XII)

cout << "Unknown response";


}
b. Conditional operator statement:
int ticket = (speed > 55) ? 1 : 0;
c. Logical operator expression:
bool condition = (limit == 55) && (speed > 55); Or if ((limit == 55) && (speed > 55))
9. Read the following scenario to make a C++ program for taking SALARY as an input and
print an appropriate activity accordingly:

Salary Range Allowance


Less than or equal to 6000 Allowance 5% of salary
More than 6000 and less than or equal to 8000 Allowance 10% of salary
More than 8000 and less than or equal to 9000 Allowance 15% of salary
More than 9000 and less than or equal to 10000 Allowance 20% of salary
More than 10000 Allowance 25% of salary
a. Write down a program using any selection structure.
b. Which selection structure do we think is more appropriate and state the
reason? a.
#include <iostream>
using namespace std;

int main() {
float salary, allowance;

cout << "Enter wer salary: ";


cin >> salary;

if (salary <= 6000)


{ allowance = 0.05 * salary;
cout << "Wer allowance is 5% of wer salary: " << allowance << endl;
} else if (salary > 6000 && salary <= 8000)
{ allowance = 0.10 * salary;
cout << "Wer allowance is 10% of wer salary: " << allowance << endl;
} else if (salary > 8000 && salary <= 9000)
{ allowance = 0.15 * salary;
cout << "Wer allowance is 15% of wer salary: " << allowance << endl;
} else if (salary > 9000 && salary <= 10000)
{ allowance = 0.20 * salary;
cout << "Wer allowance is 20% of wer salary: " << allowance << endl;
} else {
allowance = 0.25 * salary;

ANUM NISA 3
7
COMPUTER SCIENCE (XII)

cout << "Wer allowance is 25% of wer salary: " << allowance << endl;
}
return 0;
}
b. In this scenario, using the if-else selection structure is more appropriate because it allows us to
easily handle multiple conditions and select the appropriate activity based on the salary input.
Each condition checks a specific range of salary values and calculates the allowance
accordingly.

10. Differentiate between pretest and posttest loop.


Pretest Loop Posttest Loop
The test condition is evaluated before The test condition is evaluated after
executing any statement within the executing all statements within the
loop. loop.
If the test condition is false, the loop Even, if the test condition is false, the
statements/ body of loop never loop statements/ body of loop execute
execute. once.
It is considered as entry-controlled It is considered as exit-controlled
structure structure.
The for and while loop are pre-test The do-while loop is post-test loop.
loops.
Example: Example:
cin >> marks; cin >> marks;
while ( marks > 0) do { s = s +
{ s = s + marks; marks;
cin>>marks; cin>>marks;
} } while ( marks > 0);
11. Write down the output of the following program segments.
a) int funny = 7, serious = b)
15; funny = serious % 2; int i , j;
switch (funny) for(i = 1; i <= 4; i++)
{ {
case 1: cout << "That is funny"; for(j = 1; j <= i; j++)
break; cout << i * i << " "; cout
case 7: cout << "That is serious"; << "\n" ;
break; }
case 30: cout << "That is seriously funny";
break;
default : cout << funny << endl;
}

ANUM NISA 3
8
COMPUTER SCIENCE (XII)

Answer:
a)
Th
at
is
fu
nn
y
b)1
44
999
16 16 16 16
12. Convert the following while loop to a for loop:
count = 0;
while (count < 50)
{
cout << "count is " << count << endl;
count++;
}
Answer:
for (count = 0; count < 50; count++)
cout << "count is " << count << endl;
13. Write a do-while loop in C++ that asks the user to enter two numbers and display their
sum. The user should be asked to perform the operation again. If so, the loop should
repeat; otherwise, it should terminate.
enter two numbers: 20 50
sum = 70
Do we want to continue(Y/N))? Y
enter two numbers: 12 15 sum =
27
Do we want to continue(Y/N))? N Answer:
do
{
cout << "enter two numbers: ";
cin>>a>>b;
cout<< "sum = "<<a+b<<"\n"; cout <<
"Do we want to continue(Y/N))? ";
cin>>choice;
} while ( (choice = ='Y' ) || ( choice = =
'y' ) );
14. Write a C++ program that prints sum of squares of integers from 1 to 10.

ANUM NISA 3
9
COMPUTER SCIENCE (XII)

ANSWER
#include<iostream>
void main()
{
int i, sum=0,s;
for(i=1;i<=10;i++)
{
s=i*i;
sum+=s;
}
cout<<"\n Sum of square of integers = "<<sum;
}
15. Write a C++ code that prints sum of the following series: 1 2 + 3 2 + 5 2 + 7 2 + . . . . .
+ 992 #include <iostream> using namespace std;

int main() {
int sum = 0;

// Iterate over odd numbers from 1 to 99


for (int i = 1; i <= 99; i += 2) {
sum = sum + i * i; // Add the square of each odd number to the sum
}

cout << "Sum of the series: " << sum << endl;

return 0;
}
16. Convert the following while loop to a for loop such that the output remains same.
int i = 20; while (i > 0)
{ cout << i << “\
t”; i = i - 2;
}
Answer:
for (int i = 20; i > 0; i = i - 2) {
cout << i << "\t";
}
17. Write down the output of the following program segment: char c = ‘A’; do
{
cout << c << ”\t”;
c = c + 2;

ANUM NISA 4
0
COMPUTER SCIENCE (XII)

}
while (c <= ‘K’ );
Answer:
The output of the following program segment will be:
A C E G I K
18.
a) How many times will the following
loop display "OK"? for (int i = 1; i<20; i++)
{
cout<<"OK”;
}
b) Rewrite the while loop as do-while
loop. int i = 1; while (i<=15) { cout<<"a";
i=i+1;
}
Answer:
a. The loop will
display "OK"
19 times. It
starts with i =
1 and iterates
until i
becomes
equal to 19,
printing "OK"
each time.
b. int i = 1; do {
cout << "a";
i = i + 1;
} while (i <= 15);
19. What will be the output of the following for loop? for (int i = 0; i < 5; )
{
cout << i << " ";
i++;
}
OUTPUT:
01234
20. Predict the output of the following while loop:
int x = 5;
while (x > 0)
{

ANUM NISA 4
1
COMPUTER SCIENCE (XII)

cout << x << " ";


x -= 2;
}
OUTPUT:
531
21. Determine the output of the following do-while loop: int num = 1; do
{
cout << num << " ";
num++;
} while (num <= 5);
OUTPUT:
12345
22. What will be printed by the nested for loop?
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 2; j++)
{
cout << i * j << " ";
}
}
Output:
122436
23. Write down three differences between break statement and exit( ) function.
Break Exit
It is a keyword and does not require a ny It is a built-in function requires a
header file to include header file stdlib.h to include
It is often used to terminate from the c ontrol It is often used to terminate the
structure like loop, switch statement program from anywhere in a
program
More than one break statements can b e Can be placed anywhere in the
executed in a program program

Multiple break statements allowed Only one exit( ) function will be


executed in a program

Syntax Synta
x
break; // exits from control structure exit(0); // exits program
without

ANUM NISA 4
2
COMPUTER SCIENCE (XII)

any error
24. Write down three differences between break and continue statement.
Break Continue
When a break statement is encountered then When the continue statement is
the control is exited from the loop construct encountered then the control
immediately. automatically passed to the beginning
of the loop statement.
It is often used to terminate from the control It is not used with the switch
structure like loop, switch statement. statement, but it can be used within
the loop.
More than one break statements can be Can be placed anywhere in the
executed in a program program

Leftover iterations are not executed after the Leftover iterations can be executed
break statement. even if the continue keyword appears
in a loop.
Synta Synta
x x
break; continue
;
25. Write a C++ program that reads a number and prints whether it is prime or composite.
#include <iostream>
using namespace std;

int main() { int


num; int
isPrime = 0;

cout << "Enter a positive integer: ";


cin >> num;

if (num <= 1) {
cout << "Neither prime nor composite." << endl;
}
else
{
for (int i = 2; i <= num ; ++i) {
if (num % i == 0)
{

ANUM NISA 4
3
COMPUTER SCIENCE (XII)

isPrime = 1;
break;
}
}
if (isPrime==0)
cout << num << " is a prime number." << endl;
else
cout << num << " is a composite number." << endl;
}

return 0;
}
26. Write the following code using if else if statement, to produce the same output.
switch (choice) { case 1: cout << "InSum=" << x + y;
break;
case 2:
cout << "InProduct= " << x * y;
break; default: cout <<
"InAverage= " << (x + y) / 2; break;
}
Answer:
if(choice = = 1)
cout<<"InSum="<<x+y; else
if(choice = = 2)
cout<<"InProduct= "<<x*y;
else cout<<"InAverage=
<<(x+y)/2;
27. What is the usage of break and continue statements in a C++ programs?
Usage of break statement:
The break statement is used to immediately terminate the execution of the innermost loop in
which it appears.
When a break statement is encountered within a loop, the control exits the loop and continues
with the statement immediately following the loop.
It is often used to terminate a loop early if a certain condition is met, avoiding unnecessary
iterations.
Usage of continue statement:
The continue statement is used to skip the remaining code within a loop for the current iteration
and proceed to the next iteration of the loop.
It is typically used to skip specific iterations of a loop based on certain conditions.
When a continue statement is encountered within a loop, the control jumps to the next iteration
of the loop, bypassing any remaining code within the current iteration.

ANUM NISA 4
4
COMPUTER SCIENCE (XII)

It is often used to skip certain iterations of a loop if a certain condition is met, without exiting
the loop entirely.
28. Find the output of the following error free code if the user enters a value 3568.
#include<iostream> int main( )
{ int no, res=0, r, n; cout<<”Enter any positive
number”; cin>>n; no=n; while(no>0)
{
r=no%10; res=res*10+r; no=no/10; }
cout<<”\n The Result is [“<<n<<”] is :: [“<<res<<”] \n”; }
Ouptut:
Enter any positive number: 3568
The Result is [3568] is :: [8653]
29. Rewrite the following code using if - else statement: rent = basic_pay>50000 ?
basic_pay*0.2 : basic_pay*0.4; Answer:
if (basic_pay > 50000)
{ rent = basic_pay * 0.2;
} else {
rent = basic_pay * 0.4;
}
30. Write a program that computes and displays the charges for a patient’s hospital
stay. The program should ask if the patient was admitted as an in-patient or an out-
patient.
• If the patient was an in-patient, the following data should be entered:
• The number of days spent in the hospital
• The daily rate
• Hospital medication charges
• Charges for hospital services (lab tests, etc.)
• If the patient was an out-patient the following data should be entered:
• Charges for hospital services (lab tests, etc.)
• Hospital medication charges
The program should use two overloaded functions to calculate the total charges. One of the
functions should accept arguments for the in-patient data, while the other function accepts
arguments for out-patient information. Both functions should return the total charges to the main
function.
Answer:
#include <iostream.h>
#include <conio.h>
float patient(int days, float rate, float medcharges, float hscharges);
float patient(float medcharges, float hscharges); void main(void)
{

ANUM NISA 4
5
COMPUTER SCIENCE (XII)

char p;
int days;
float rate, medcharges, hscharges, total;
cout<<"Enter I for in-patient or O for out-patient: ";
cin>>p;
if(p == 'I' || p == 'i')
{
cout<<"enter Number of days spent in the hospital: ";
cin>>days;
cout<<"enter Daily rate: ";
cin>>rate;
cout<<"enter Hospital medication charges: ";
cin>>medcharges;
cout<<"Charges for hospital services: ";
cin>>hscharges;
total = patient(days, rate, medcharges, hscharges);
cout<<"Patient total charges: "<<total;
}
else
if(ans == 'O' || ans == 'o')
{
cout<<"enter Hospital medication charges: ";
cin>>medcharges;
cout<<endl;
cout<<"enter Charges for hospital services: ";
cin>>hscharges; total = patient(medcharges,
hscharges);
cout<<"Patient total charges: "<<total;
}
getche();
}
float patient(int days, float rate, float medcharges, float hscharges)
{
float totalcharges;
totalcharges = (days * rate) + medcharges + hscharges;
return totalcharges;
}
float patient(float medcharges, float hscharges)
{
float totalcharges;

ANUM NISA 4
6
COMPUTER SCIENCE (XII)

totalcharges = medcharges + HScharges;


return totalcharges;
}
31. Write a C++ program that displays the following menu:
Geometry Calculator
1. Display Area of Circle
2. Display Area of Rectangle
3. Display Area of Triangle
4. Quit Enter choice (1-4):
• If user enters 1, the program should ask for the radius of the circle and then display its
area. Use formula: area = πr2
• If user enters 2, the program should ask for the length and width of the rectangle and then
displays its area. Use formula: area = length x width
• If user enters 3, the program should ask for the length of the triangle’s base and its
height, and then display its area. Use formula: area = base * height * .5
• If user enters 4, the program should end
Display an error message if the user enters a number outside the range of 1 through 4.
Answer:
#include <iostream> #include
<math.h>
using namespace std; int
main( )
{
const float PI = 3.14159;
float area, radius, width, length, height, base;
int choice;
cout << "\nGeometry Calculator\n" <<
" 1. Display Area of Cricle\n"
<< " 2. Display Area of Rectangle\n"
<< " 3. Display Area of Triangle\n"
<< " 4. Quit\n"
<< "\n Enter wer choice (1-4): ";
cin >> choice;
switch (choice)
{
case 1: cout << "Enter the radius: ";
cin >> radius;
area = PI * radius * radius;
cout << "The area of circle = " << area;
break;

ANUM NISA 4
7
COMPUTER SCIENCE (XII)

case 2: cout << "Enter the length: ";


cin >> length;
cout << "Enter the width: " ;
cin >> width; area = length
* width;
cout << "The area of rectangle = " << area;
break;
case 3: cout << "Enter the base: ";
cin >> base;
cout << "Enter the height: ";
cin >> height;
area = (base * height) * 0.5; cout <<
"Area of triangle = " << area; break;
case 4: cout << "Program ends.\n";
break;
default: cout << "Wer choice must between 1 and 4.\n";
cout << "Run Program again." ;
}
return 0;
}

Chapter#5 Arrays and strings


1. What is an array? Write down uses of any two uses of arrays in daily life.
An array is a data structure that stores a collection of elements of the same data type in
contiguous memory locations. Each element in an array is accessed by its index.
Two uses of arrays in daily life:
Shopping Lists: A shopping list is a common example of using an array in daily life. Each item to
be purchased can be considered as an element in the array, and the array allows for easy
management and organization of the items.
Gradebook: In education, teachers often use arrays to store and manage student grades. Each
student's grade can be stored as an element in the array, and the array allows for easy
calculations, sorting, and analysis of grades.
2. Write advantages of using arrays.
Advantages of using arrays include:
Efficient Storage: Arrays provide a contiguous block of memory, allowing efficient storage of
elements of the same data type.

Random Access: Elements in an array can be accessed directly using their index, making it
easy to retrieve and manipulate data quickly.

ANUM NISA 4
8
COMPUTER SCIENCE (XII)

Simplified Code: Arrays simplify the code by allowing the use of loops for repetitive
operations, reducing the need for repetitive variable declarations and assignments.

Improved Performance: Array operations often have better performance compared to other
data structures for tasks like sorting, searching, and accessing elements due to their direct
memory access.

Versatility: Arrays can store a fixed-size collection of elements, making them suitable for a
wide range of applications from simple data storage to complex mathematical computations.
3. How to declare and initialize an array in C++.
In C++, we can declare and initialize an array using the following syntax:
data_type array_name[array_size] = {value1, value2, ..., valueN};
int numbers[5] = {10, 20, 30, 40, 50}; In this example:
• int is the data type of the array elements.
• “numbers” is the name of the array.
• [5] indicates the size of the array, which is 5 in this case.
• {10, 20, 30, 40, 50} is the list of initial values assigned to the array elements.
4. Rewrite the program segment after removing errors:
int a{10}, i; cout >> ” enter
ten numbers ; for (i = 0; i <
10; i--)
cin << a{i};
Answer:
The error free code is:
int a[10], i;
cout << "Enter ten numbers: ";
for (i = 0; i < 10; i++)
cin >> a[i];
• Replaced { } with [ ] to declare an array a.
• Changed >> to << for the output stream (cout).
• “ were missing at the end of cout string to display.
• Changed << to >> for the input stream (cin).
• Changed the loop condition from i-- to i++ to increment the loop variable i. 
Removed the curly braces { } around a[i] inside the cin statement.
5. What is the difference between array size and index? Illustrate with example.
Feature Array Size Array Index
Definition It refers to total number of It refers to position of element within
elements array can hold array
Determination It is set when the array is It starts from 0 for first element,
created and does not increments by 1 for each subsequent

ANUM NISA 4
9
COMPUTER SCIENCE (XII)

change. element
Usage It specifies maximum It helps to get or change specific
capacity of array elements in an array.
Example int declares an arr[0 refers to first arr[1
arr[5]; array ] element, refers to ]
of size 5 second element,
and so on
6. Write down the purpose of sizeof() function. Give an example that finds the size of an
array.
The sizeof() function in C++ is used to determine the size in bytes of a data type or variable.
Its purpose includes:
Determining Size: It helps to find out the memory occupied by a data type or variable.
Memory Allocation: It assists in memory allocation calculations, especially in dynamic
memory allocation scenarios.

Example:
int main() {
int arr[5];
cout << "Size of int data type: " << sizeof(int) << " bytes" << endl;
cout << "Size of array arr: " << sizeof(arr) << " bytes" << endl;
return 0;
}
Output:
Size of int data type: 4 bytes
Size of array arr: 20 bytes
In this example, sizeof(int) returns the size of the integer data type (typically 4 bytes on most
systems), and sizeof(arr) returns the total size occupied by the array arr, which consists of 5
integers (hence 20 bytes).
7. Complete the following table to show the values of variables used in the
program during each iteration.
int i, s=0, count=5, v=0 ;
int a[5] =
{12,27,36,55,72};
for(i=0; i<=count; i++)

{ if(a[i] % 3 == 0)
{ cout<<a[i];

s += a[i];
v= s * 3 - a[i] % 7; } cout<<s<<"\t”<<v;
}

ANUM NISA 5
0
COMPUTER SCIENCE (XII)

Iteration i count a[i] s v


1 0 5 12 12 31
2 1 5 27 39 111
3 2 5 36 75 224
4 3 5 55 75 224
5 4 5 72 147 439

8. Differentiate between one dimensional and two-dimensional array.


Feature One-Dimensional Array Two-Dimensional Array
Structure A one-dimensional array A two-dimensional array contains
contains a single row of multiple rows and columns of
elements. elements.
Declaration One-dimensional arrays are Two-dimensional arrays are declared
declared with a single pair of with two pairs of square brackets [ ], [
square brackets [ ]. ].
Syntax: Syntax:
Datatype variable_name[size]; datatype variable_name[row][column];

Accessing Elements in a one-dimensional Elements in a two-dimensional array


Elements array are accessed using a are accessed using two indexes - one
single index. for the row and one for the column.
Memory One-dimensional arrays Two-dimensional arrays allocate
Allocation allocate contiguous memory in memory in a grid-like structure.
a single dimension.
Example An example of a one- An example of a two-dimensional
dimensional array: int array: int arr[3]
arr[5]; [4];

9. Complete the following table to show the values of variables used in the
program during each iteration. int i, j, sum=1, count=1 ; int a[2][2] = {20,18,16,14};
for(i=0; i<=count; i++)
{ for(j=0; j<=count;j++)
sum += a[ i ][ j ];
cout<<" "sum<<endl; }
Iteration i j count a[i][j] sum
1 0 0 1 20 21
2 0 1 1 18 39
3 1 0 1 16 55
4 1 1 1 14 69

ANUM NISA 5
1
COMPUTER SCIENCE (XII)

10. Write the syntax of the declaration and initialization of a two-dimensional array.
also give an example.
The syntax for declaring and initializing a two-dimensional array in C++ is as follows:
data_type array_name[rows][columns] =
{ {value_1_1, value_1_2, ..., value_1_columns},
{value_2_1, value_2_2, ..., value_2_columns},
...
{value_rows_1, value_rows_2, ..., value_rows_columns}
};

Example:
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
This declares and initializes a 3x3 two-dimensional array named matrix with integer
elements. Each row is enclosed in curly braces, and the rows are separated by commas.

11. Consider the array definition: float table[5][5];


a. How many elements does an array have?
b. Write statement that assigns 36.5 to the first element of array.
Answers:
a. The array table has a total of 5×5=25 elements.

b. Statement to assign 36.5 to the first element of the array:


table[0][0] = 36.5;

12. Write down the output of the following program segment:


int values [ ] = {4, 17, 20, 9, 23}; cout << values [2] << "\n";
cout << ++values [0] <<"\n";
cout << values [1]++ <<"\n";

Answer:
20 // index 2 means 3rd element of array values
5 // index 0 means first element of an array values 4 with pre increment ->4+1=5
17 // index 1 means second element of an array values 17 with post increment
which means 17 will be displayed first and then incremented.

ANUM NISA 5
2
COMPUTER SCIENCE (XII)

13. Trace the output of the following program segment: int


a[5]={10,3,5, 1,2}; for (int i=4; i>0; i --) {a[i]+=a[i-1]; cout
<<a[i]<<" "; }

Output:
3 6 8 13

14. Write a C++ program that lets the user to enter integer
numbers in a 2D array named matrix having 3 rows and 4
columns. The program should display the:
• Average of numbers stored in array.
• Minimum number in the array.
#include <iostream>
using namespace std; int
main() {

// Input values into the matrix


cout << "Enter 12 integer numbers for the matrix:\n";
for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) {
cin >> matrix[i][j];
}
}

// Calculate the average of the numbers


int total = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
total += matrix[i][j];
}
}
float average = (float) total / 12;

// Find the minimum number in the array


int min_num = matrix[0][0]; for (int i = 0; i
< 3; i++) { for (int j = 0; j < 4; j++) {
if (matrix[i][j] < min_num) {
min_num = matrix[i][j];
}
}
}

ANUM NISA 5
3
COMPUTER SCIENCE (XII)

// Display results
cout << "Average of numbers in the array: " << average << endl;
cout << "Minimum number in the array: " << min_num << endl;

return 0;
}

15. Answer the following questions:


a. Write a statement that defines a one-dimensional array called ABC of type double that
hold 100 elements.
b. Write a statement that takes element j of array PQR and writes it to cout<<
c. Write a statement that defines an array BILLS of type int and initializes it to the values of
Pakistani currency notes (10,20,50,100,500,1000,5000).
Answers:
a. double ABC[100];
b. cout << PQR[j];
c. int BILLS[] = {10, 20, 50, 100, 500, 1000, 5000};
16.How to access element of a 2D array?
To access an element of a 2D array in C++, we need to specify both the row and column
indices. Here's how we can do it:

// Define a 2D array int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

// Accessing element at row 1, column 2 int element = matrix[1][2]; //

This will access the element with value 6

// Output the accessed element

cout << "Element at row 1, column 2: " << element << endl;

17. What is a String variable? Also write down the role of null character in C++ string.

Answer:

String:

A string variable is a collection of characters in a linear sequence. It treats as a single data


having text including blank spaces. It is considered as a set of characters used to represent
name, address etc. It is declared as: char weekday [20]; // weekday is the name of string
variable

ANUM NISA 5
4
COMPUTER SCIENCE (XII)

Role of null character:

C++ automatically places the null terminator/ character at the end of string. An extra byte is
appended to the end of string when it is stored in memory. It does not print on the screen
and marks the end of the string. It is represented by ‘\0’.

18. Write down any three differences between string and array.

String Array Arrays


1. A string can hold items of only the Arrays can hold items of any numeric
character data type, hence considered data type such as set of integers, set of
as a set of characters. floating-point numbers.
2. String terminates with a null character Arrays does not terminate with a null
(\ ). character.
0
3. String size can have variable number Arrays are of fixed size.
of elements.
4. Syntax: Syntax:
char float
name[20]; marks[10];
19. What is the advantage of using cin.get() function over cin statement for reading a
string? Give an example.
Answer:
The advantage of using cin.get() function over cin statement for reading a string is that
cin.get() allows we to include spaces in the input string, whereas cin stops reading input as
soon as it encounters a space.
#include <iostream>
using namespace std;

int main() {
char str[100];

// Using cin.get() to read a string with spaces


cout << "Enter a string with spaces: ";
cin.get(str, 100);
cout << "We entered: " << str << endl;

return 0;
}

ANUM NISA 5
5
COMPUTER SCIENCE (XII)

In this example, cin.get() allows the user to input a string with spaces, while cin would stop
reading at the first space.
20. Compare strcpy( ) and strcat( ) functions with examples.
strcpy()
It is the string copy function. It copies one string into another string.
Syntax:
strcpy(string1, string2);
The two parameters to the function, string1 and string2, are strings. The function will copy the
string string2 into the string 1.
Example:
char dest[20], src[ ] = "Hello";
strcpy(dest, src);
In this example the contents of src are copied into dest.
strcat()
It is the string concatenate function. It concatenates / combines the sstrings.
Syntax:
strcat(string1, string2);
The two parameters to the function, string1 and string2 are the strings to be concatenated.
The above function will concatenate the string string2 to the end of the string string1.
Example:
char str1[20] = "Hello", str2[ ] = " World";
strcat(str1, str2);
In this example the contents of str2 are appended to str1, resulting in "Hello World".
21.Write the syntax of the declaration and initialization of a string.
In C++, a string can be declared and initialized in the following ways:
Declaration:
char str[20]; // Declares a character array named str with a capacity to hold 20 characters
Initialization: char str[ ] = "Hello"; // Initializes the string str with the content "Hello"
In the above example, the string str is initialized with the content "Hello". The size of the
array is determined automatically based on the length of the provided string.
22. Write the differences between strlen() and strcmp() functions.

Feature strlen( strcmp(


) )
Purpose Determines the length of a It compares two strings. And will return
string. the integer values based on the result of
comparison.

Return Returns the length of the Returns an integer value indicating the
Value string (number of comparison result.
characters). • return 0 if string1 and string2 are

ANUM NISA 5
6
COMPUTER SCIENCE (XII)

the same.
• return 1 if string1 is greater than
string2.
• return -1 if string1 is less than
string2.
Functionality Provides the length of a Compares two strings character by
given string. character.
Example int len = int result = strcmp("Hello", "World");
strlen("Hello");
// len will be // result will be a negative integer (-
5 1)
based on the
comparison

23. Write a C++ code that:


a. Insert strings of S1 and S2 in S3 by strcat() function and displays S3
b. displays the comparison result of S1 and S2
c. displays the lengths of S3
#include <iostream>
#include <cstring>
using namespace std;
int main() { char
S1[ ] = "Hello"; char
S2[ ] = "World"; char
S3[20];

// Part a: Concatenate S1 and S2 into S3


strcpy(S3, S1);
strcat(S3, S2);
cout << "Concatenated string: " << S3 << endl;

// Part b: Compare S1 and S2


int comparison = strcmp(S1, S2);
if (comparison == 0) {
cout << "S1 and S2 are equal." << endl;
} else if (comparison < 0) {
cout << "S1 is less than S2." << endl;
} else {
cout << "S1 is greater than S2." <<endl;
}

ANUM NISA 5
7
COMPUTER SCIENCE (XII)

// Part c: Display the length of S3


cout << "Length of concatenated string S3: " << strlen(S3) << endl;
return 0;
}
24. Answer the following questions:
a) Write C++ statements that read and store user name.
b) Write a statement that takes element i of array ABC and prints it.
Answer:
a. char userName [100];
cout << "Enter wer name: ";
cin.get(userName, 100); b.
cout << ABC[i];

Chapter#6 Functions

1. What is a function? Briefly describe different types of functions used in C++. A


function in C++ is a block of code that performs a specific task and can be called from
anywhere in the program. It helps in modularizing code by breaking it into smaller,
manageable parts. There are two main types of functions used in C++:

Standard Library Functions: These are predefined functions provided by the C++
standard library, such as printf(), scanf(), strlen(), etc.

User-defined Functions: These are functions created by the programmer to perform


specific tasks. They allow the programmer to encapsulate a piece of code and reuse it
whenever necessary.

2. Differentiate between library function and user-defined function


Criteria Library Function User-defined Function
Definition Library functions are User-defined functions are created by
predefined and provided by the programmer according to needs.
libraries
Purpose Library functions are designed User-defined functions serve specific
to perform common tasks purposes in the program

Modification Library functions cannot be User-defined functions can be


modified by the programmer modified as per program requirements
Usage Library functions are used for User-defined functions are customized
general-purpose operations to meet specific needs within the
program

ANUM NISA 5
8
COMPUTER SCIENCE (XII)

Examples Examples include printf( , Examples include functions created by


) the programmer for specific tasks
sqrt( , strlen(
) )
3. Write advantages of using functions.
Advantages of Using Functions:
Reusability: Functions allow code to be reused across the program, reducing redundancy
and promoting modular programming practices.
Modularity: Functions divide large program into small modules that are easy to understand,
making the code more organized and easier to manage.
Readability: By breaking down the program into smaller, focused functions, the code
becomes easier to read, understand, and maintain.
Debugging: Functions separate specific parts of the code, making it easier to identify and fix
errors without affecting other parts of the program.
Scalability: Functions facilitate scalability by allowing new features or modifications to be
implemented independently within the program structure.
Testing: Functions can be tested individually, enabling more efficient and targeted testing
procedures for different parts of the program.
Collaboration: Functions enable collaboration among team members by dividing the
programming tasks into smaller units, allowing parallel development and integration.
Code Organization: Functions improve code organization by grouping related operations
together, leading to a more structured and maintainable codebase.
4. Write down the syntax of function prototype for the following functions:

a. A function named table with one integer parameter by value.


b. A function named area with no parameters and returns a float.
c. A function named large with two floating point numbers by reference.
Answer:
a. void table(int x);
b. float area();
c. void large(float &x, float &y);

5. What are three main components of function? Write their purposes also. Each
function consists of three components. These are:
• Function prototype/declaration
• Function definition
• Function call
Declaring a Function:
A Function Prototype/Declaration describes the function interface that specifies function's
name, parameters and return type. It does not contain function body. It gives information to

ANUM NISA 5
9
COMPUTER SCIENCE (XII)

the compiler that the function may later be used in the program. It is not needed(optional) if
the function is defined before the main( ) function.

long int factorial (int n); // function prototype showing the name of function (factorial),
argument of type (int) and return type of the function (long int).

Defining a Function:
A Function Definition contains the block of code (set of statements) to perform a specific
task. It tells the program what the function is doing. It is used to perform certain actions. It
defined once and can be reuse many times. It has two parts: Function header and body of
function. Function header is like function prototype except semicolon (;) at the end. The body
of function is the set of statements enclosed in curly braces{}.

long int factorial (int n) // function header


{
// body of function
}

Calling a Function:
A Function Call is a statement written in calling function to execute the code of defined
function. It invokes the statements of function. When a function is called, the control of the
program will be transferred to the function definition. The statements given in the function will
be executed and the control will be transfer back to the calling function.

fact = factorial(num); // function call, that requires parameter num and result store in fac

6. What will be display after executing the following code?


int test (int x, int y)
{
return y % x ;
}
void main(void)
{
int a = 3, b = 70, c , d ;
c = test(a , b); d =
test(b , a);
cout << b << ”\t” << c << “\t” << d << endl;
}

Answer: (one mark for each value)

ANUM NISA 6
0
COMPUTER SCIENCE (XII)

70 1 3

7. Compare local and static variables in terms of scope, lifetime, and storage duration.

Feature Local Variable Static Variable


Scope A local variable has block/ local Static variables are accessible
scope, only limited to the function within the block or function where
where it is declared or defined. they are declared, but they retain
their value between function calls.
Lifetime It is created at the point of Its lifetime starts when the function
declaration / definition and is called and ends only when the
destroyed at the end of the block in program ends.
which it is defined.
Storage Local variables have automatic Its space is allocated only once in
Duration storage duration, meaning they are a function and the value of the
created when the block is entered variable gets carried from the
and destroyed when the block is previous function call to the next
exited. function call.

6. Compare local and global variables in terms of scope, lifetime, and storage duration.
Characteristic Local Variable Global Variable
Scope Local variables are accessible Global variables are accessible
only within the block or throughout the entire program,
function where they are including all functions and blocks.
declared or defined.
Lifetime It is created at the point of Its lifetime starts when the program
declaration / definition and begins and ends only when the
destroyed at the end of the program ends or terminates.
block in which it is defined.
Storage Duration Local variables have Global variables are allocated
automatic storage duration, memory when the program starts
meaning they are created and deallocated when the program
when the block is entered and ends. Therefore, they exist
destroyed when the block is throughout the entire execution of
exited. the program.

7. A program uses a function named convert( ) in addition to its main function. The function
main() declares the variable x within its body and the function convert() declares two
variables y and z within its body, variable z is made static. A fourth variable m is declared

ANUM NISA 6
1
COMPUTER SCIENCE (XII)

ahead (i.e. at the top) of both functions. State the visibility and lifetime of each of these
variables.
Answer:
Variable m, declared ahead of both functions, is a global variable. It is visible and accessible to
both the main() function and the convert() function. Its lifetime starts when the program begins
execution and ends when the program terminates.

Variable x, declared within the main() function, is a local variable. It is visible only within the
main() function and not accessible from outside. Its lifetime starts when the main() function is
called and ends when the main() function exits.

Variables y and z, declared within the convert() function, are also local variables. They are
visible only within the convert() function and not accessible from outside. Their lifetimes start
when the convert() function is called and end when the convert() function exits.
However, variable z being declared as static will retain its value across function calls, meaning
its lifetime ends only when the program ends or terminates.

8. If there is a function named "factorial" of integer type and has an integer parameter "n"
(a)Write the prototype for this function.
(b)What will be the header of its function definition?
(c)What will be the return type of this function?
Answer:
(a) int factorial(int n);
(b) int factorial(int n) { (c)
int
9. Distinguish between formal parameters and actual parameters used in functions.

Feature Formal Parameters Actual Parameters


Definition Formal parameters are placeholders Actual parameters are the actual values
for data that a function expects to or variables passed to a function when it
receive when it is called. is called.
Use They are used in the function They provide the real data that the
declaration or definition to specify function will operate on during its
the type and name of the data that execution.
the function will accept.
Example In the function declaration int In the function call result = add(5, 10),
add(int a, int b), a and b are 5 and 10 are actual parameters.
formal parameters.

10. Write the use of Inline function.

ANUM NISA 6
2
COMPUTER SCIENCE (XII)

Calling a function generally causes a certain overhead, and for small functions, it may be more
efficient to insert the code of the function where it is called, instead of calling a function.

This overhead can be overcome by use of an Inline function. In Inline function the compiler
copies the code from the function definition directly into the code of the calling function rather
than creating a separate set of instructions in memory. The function call is replaced by the
contents of function itself.

It can be achieved by placing the keyword inline in function definition. This does not change
the behavior of a function, but the code generated by the function body shall be inserted at
each point where the function is called.

Example:
inline float sum(float a, float b)
{
return a+b;
}
11. Do inline functions improve performance? Justify wer answer.
Yes, inline functions can improve performance in certain cases. Here's a justification:

Reduced Function Call Overhead: Inline functions are expanded directly at the call site,
eliminating the overhead of function call. This can lead to faster execution, especially for
small, frequently called functions.

Avoidance of Function Call Stack: Since inline functions are expanded at the call site, they
do not create a separate stack frame for each call. This can reduce memory usage and
increase speed.
Compiler Optimization Opportunities: Inline functions enable the compiler to perform
context-specific optimization on the body of the function. Such optimizations are not possible
for normal function calls.
12. Write the disadvantages of using the inline function.
Increase Code Size: Inlining functions can result in increased code size, especially if the
function is large or used in multiple places. This can lead to larger executable files and
increased memory usage.

Increased Compilation Time: Inline functions can lead to longer compilation times, especially
in large codebases, as the compiler needs to duplicate the function's code at every call site.

Limited Usefulness for Embedded Systems: It is not useful for embedded system where
large binary size is not preferred at all due to memory size constraints.

13. Write down any three differences between passing arguments by value and by reference.

ANUM NISA 6
3
COMPUTER SCIENCE (XII)

Pass by Value Pass by Reference

It passes the value of actual parameter It passes the address of actual


to formal parameter and does not use & parameter to formal parameter by using
operator & operator
Any change made by the function in Any change made by the function in
formal parameter does not affect the formal parameter affects the value of
value of actual parameter. actual parameter.
It requires more memory and less It requires less memory and more
efficient. efficient.

14. Define default arguments. Give two advantages of using default arguments.
Default arguments in C++ allow we to specify default values for function parameters. These
default values are used when the corresponding argument is not provided during function
invocation.

Advantages of Using Default Arguments:

Simplified Function Calls: Default arguments eliminate the need to specify values for all
parameters in every function call, making function calls more concise and readable.

Improved Flexibility: Default arguments provide flexibility by allowing functions to have


optional parameters. This allows the same function to be used in different contexts without
requiring overloaded versions with different parameter lists.

Improved Readability: Default arguments can enhance code readability by reducing the need
for excessive function overloads or complex conditional logic to handle different argument
combinations.
15. Write a program that reads and passes a value to a function named factorial and print
its factorial.
#include <iostream>
using namespace std;

// Function to calculate factorial


int factorial(int n) {
int fact=1;

ANUM NISA 6
4
COMPUTER SCIENCE (XII)

for(int i=1; i<=n; i++)


fact=fact*i;
cout << "Factorial of " << n << " is: " <<fact<<endl;
}

int main() {
int num; //
Reading
input from
user cout
<< "Enter a
number: ";
cin >> num;

// calling the function factorial(num)


;

return 0; }
16. Briefly describe the features of function overloading.
• Using function overloading, we can declare multiple functions with the same name that
have slightly different purposes.
• Function overloading can significantly lower complexity of programs.
• As multiple functions have same name, therefore, remembering them is easier as
compared to remembering more names.  It increases the readability of programs.
• It exhibits the behavior of polymorphism.
17. How a function can be overloaded?
Function overloading in C++ allows to define multiple functions with the same name but
different parameter lists. It allows to create functions that perform similar tasks but operate on
different types of data or accept different numbers of arguments. Function overloading can be
achieved by following these rules:

Same Function Name: All overloaded functions must have the same name.

a. Number of arguments
Functions can be overloaded if they have different numbers of parameters. More than one
functions with the same name but different number of parameters can be used in a single
program.
b. Data types of arguments
Another way to achieve function overloading is to define multiple functions with the same name
but different data types of parameters.

ANUM NISA 6
5
COMPUTER SCIENCE (XII)

c. Return Type Alone Isn't Enough: Function overloading cannot be based solely on
differences in return types. Two functions with the same parameter list but different return
types cannot be overloaded.

Here's an example demonstrating function overloading:


#include <iostream>

// Function to add two integers


int add(int a, int b) {
return a + b;
}

// Overloaded function to add two float float


add(float a, float b) {
return a + b;
}

int main() { int sum1 = add(3, 4); // Calls the first add
function float sum2 = add(3.5, 4.5); // Calls the second add
function

cout << "Sum of integers: " << sum1 << endl;


cout << "Sum of floats: " << sum2 << endl;

return 0;
}
18. Write a C++ program to overload area() function to calculate area of circle, triangle,
square and rectangle.

Answer:
#include <iostream>

// Function to calculate the area of a circle


float area(float radius) {
return 3.147 * radius * radius;
}

ANUM NISA 6
6
COMPUTER SCIENCE (XII)

// Function to calculate the area of a triangle


float area(float base, float height) {
return 0.5 * base * height;
}

// Function to calculate the area of a square


int area(int side) {
return side * side;
}

// Function to calculate the area of a rectangle


int area(int length, int breadth) {
return length * breadth;
}

int main() {
// Calculate and display the area of a circle
float circleArea = area(5.0);
cout << "Area of circle: " << circleArea << endl;

// Calculate and display the area of a triangle


float triangleArea = area(3.0, 4.0);
cout << "Area of triangle: " << triangleArea << endl;

// Calculate and display the area of a square


int squareArea = area(5);
cout << "Area of square: " << squareArea << endl;

// Calculate and display the area of a rectangle


int rectangleArea = area(4, 6);
cout << "Area of rectangle: " << rectangleArea << endl;

return 0;
}
19. Write declarations for two overloaded functions named FBISE(). Both have return type
int. The first takes one argument of type char, and the second takes two arguments of
type char. If this is impossible, justify why?

Yes, it's possible to have two overloaded functions named FBISE() with different argument
lists, as long as the parameter lists differ in number or types of parameters. Here's how the
declarations would look like: int FBISE(char c);

ANUM NISA 6
7
COMPUTER SCIENCE (XII)

int FBISE(char c1, char c2);

These declarations define two overloaded versions of the FBISE() function. The first version
takes one argument of type char, while the second version takes two arguments of type char.

It's important to note that function overloading is based on the function's parameter list, not just
its return type. As long as the parameter lists differ in some way, such as the number or types
of parameters, we can overload functions with the same name.
20. Write a C++ program with a function named rectangle that inputs the length and width of
a rectangle and finds its area. The result is returned to the main () to be displayed on the
screen. Answer:
#include <iostream>

// Function to calculate the area of a rectangle double


rectangleArea() {
// Variables to store the length and width of the rectangle
double length, width;

// Input length and width from the user


cout << "Enter the length of the rectangle: ";
cin >> length;
cout << "Enter the width of the rectangle: ";
cin >> width;
return length * width;
}

int main() {
// Calculate the area using the rectangleArea function
double area = rectangleArea();

// Display the area


cout << "The area of the rectangle is: " << area << endl;

return 0;
}
21. Write a C++ program using a function to find the quotient and remainder. The dividend
and divisor will be passed by reference to the function to calculate the quotient and
remainder.
Answer:
#include <iostream>
using namespace std;

ANUM NISA 6
8
COMPUTER SCIENCE (XII)

void findQuotientAndRemainder(int &d, int &divsr)


{ int quotient, remainder; quotient = d / divsr;
remainder = d % divsr; // Output the result cout
<< "Quotient: " << quotient << endl; cout <<
"Remainder: " << remainder << endl;
}

int main() {
int dividend, divisor;

// Input dividend and divisor


cout << "Enter the dividend: ";
cin >> dividend;
cout << "Enter the divisor: ";
cin >> divisor;

// Call function to find quotient and remainder


findQuotientAndRemainder(dividend, divisor);

return 0;
}

Chapter#7 Pointer

1. What is a pointer variable? Differentiate between reference operator (&) and dereference
operator (*).
A pointer variable in C++ is a variable that stores the memory address of another variable.
It "points to" the location of a data element in memory rather than containing the actual
data itself.
Feature Reference Operator (&) Dereference Operator (*)
Definition Reference/ Address operator The Dereference Operator operator is
provides the address of used to access the value stored at the
memory location associated memory address pointed to by a pointer.
with it.

ANUM NISA 6
9
COMPUTER SCIENCE (XII)

Symbol & *
Example int x = 10; int* int x = 10; int*
ptr = &x; ptr = &x; int
cout << "ptr = "<< ptr << endl; value = *ptr;
// prints address of X cout << "*Ptr = "<< *ptr<< endl; // prints
value of X
cout << "value = "<< value << endl; //
prints value of X

2. What is difference between simple variable and pointer variable.


Feature Simple Variable Pointer Variable
Definition Holds a single value of a Holds memory addresses as values,
specific data type pointing to other variables or data
Memory Occupies memory space Occupies memory space equal to the
equal to the size of its data size of a memory address
type
Accessing Directly accesses the Indirectly accesses the value it points to
value value it stores using dereferencing
Assignment Assigned a value directly Assigned a memory address using the
using the assignment address-of operator (&) or by assigning
operator =) another pointer
(
Usage Used to store data values Used to indirectly access and
directly manipulate data stored in memory

3. Write advantages of using pointer.


Pointer provides direct access to the memory.

Pointers save memory space.

Execution time with pointers is faster because data are manipulated with the address,
that is, direct access to memory location.
• Memory is accessed efficiently with the pointers. The pointer assigns and releases the
memory as well. Hence it can be said the Memory of pointers is dynamically allocated.
• Pointers reduces the storage space and complexity of the program.
4. how to declare and initialize a pointer?
To declare a pointer in C++, specify the data type followed by an asterisk (*) and then the
pointer variable name. Here's the basic syntax:
dataType *pointerVariableName;
For example, to declare a pointer to an integer variable: int
*ptr;

ANUM NISA 7
0
COMPUTER SCIENCE (XII)

This declares a pointer named ptr that can point to an integer variable. then the address of an
integer variable can be assigned to this pointer using the address-of operator (&). Example:
int x = 10;
int *ptr = &x; // Pointer ptr now holds the memory address of variable x
The asterisk (*) in the declaration indicates that ptr is a pointer, while the int before the asterisk
specifies the type of data the pointer can point to.
5. Write down the purpose of asterisk (*) in the following statements:
Answer:
a) distance = speed * time;
* used as the multiplication arithmetic operator. It gives the product of speed and time.
b) int *ptr = &n;
* used as the definition/ declaration of a pointer variable. It assigns address of variable n
to a pointer variable ptr. (Affecting variable ptr by storing memory address) c) *ptr = 100;
* used as the dereference operator. It assigns 100 to the memory location whose
address is stored in ptr variable (Not affecting ptr, but the value ptr points to).
6. If ptr is a pointer variable, what will be the output of the following statements? int n =
245, *ptr = &n; cout << ptr ; cout << *ptr ;
ANSWER
cout << ptr ; it will print the address of variable n.
cout << *ptr ; this pointer variable will print the value of variable n (* is used as
dereference operator here).
7. Write the purpose of the following:
i. Void pointer ii. Null pointer
Answer:
i. A void pointer or generic pointer in C++ is a pointer that has no associated data
type information. It's used to store the address of any data type, allowing for a
more flexible approach to pointer manipulation.
ii. A null pointer is a pointer that does not point to any memory address. It's typically
used to indicate that a pointer is not currently pointing to a valid memory location.
Null pointer is mostly used for dynamic memory allocation.
Chapter#8 Object and classes
1. What is the relationship between a class and an object?
Class:
A class is a template for defining objects. A class is a user-defined datatype that has its own
data members and member functions. It defines the structure, properties, behavior, and
contents of the objects that belong to it. It specifies how instances are created and how they
behave.

Object:

ANUM NISA 7
1
COMPUTER SCIENCE (XII)

An object is an instance of a class by which we can access the data members and member
functions of the class. An object exhibits the properties and behaviors defined by its class.
Multiple objects can be created from one class.

Example: Car is a class with properties and functions. Honda and Toyota are objects of Car.
2. How to declare a class in a C++ program? give an example.
In C++ a class can be declared by using the class keyword followed by the class name and a
pair of curly braces {} enclosing the data member (variables) and member functions. Here's a
simple example of how to declare a class:
#include <iostream>

// Declaration of the class


class MyClass { public:
// Member variables
int myInt; double
myDouble;

// Member functions
void display() {
cout << "Integer: " << myInt << endl;
cout << "Double: " << myDouble << endl;
}
};

int main() {
// Creating an object of MyClass
MyClass obj;

// Assigning values to member variables


obj.myInt = 10; obj.myDouble = 3.14;

// Calling member function


obj.display();

return 0;
}
In this example:
• We declare a class named MyClass.
• Inside the class, we have two member variables (myInt and myDouble) and one member
function (display()).

ANUM NISA 7
2
COMPUTER SCIENCE (XII)

• In the main() function, we create an object obj of type MyClass.


• We assign values to the member variables of obj.
• We call the display() member function of the obj object to display the values of myInt and
myDouble.
3. When will be the memory allocated to a class?

Memory for a class in C++ is typically allocated when we create an object (instance) of that
class. This process is known as instantiation. Memory allocation for a class involves
allocating memory for all its member variables and member functions.

4. Briefly explain the member of a class?


Members of a class in C++ are the data elements and member functions that are encapsulated
within the class definition. There are two main types of members in a class: data members and
member functions. Data Members:
• Data members are variables that represent the state or attributes of objects created from the
class.
• Data members are declared within the class body and can have different access specifiers like
public, private, or protected.
Example:
class MyClass { public:
int myInt; // Public data member private:
double myDouble; // Private data member
};
• In the above example, myInt and myDouble are data members of the class MyClass. myInt
is declared as public, while myDouble is declared as private.

Member Functions:
• Member functions are functions that operate on the data members of a class.
 They define the behavior of the class and encapsulate the operations that can be performed
on the class's objects.
 Member functions are also declared within the class body and can have different access
specifiers.
 Example:

class MyClass { public:


void display() { // Member function
cout << "Integer: " << myInt << endl;
cout << "Double: " << myDouble <<endl;
}
private:
int myInt;
double myDouble;

ANUM NISA 7
3
COMPUTER SCIENCE (XII)

};
• In the above example, display() is a member function of the class MyClass that prints the
values of myInt and myDouble.
8. Define a class Student that contains private and public data members including function
get( ).

ANSWER
class Student
{ private: int
age; int
rollNumber;
public:
void get(int Age, int studentRollNumber) {
age = Age;
rollNumber = studentRollNumber;
}
};
9. What are access specifiers.
Access specifiers in C++ are keywords used to define the accessibility of class members
(variables and functions) within the class and from outside the class. C++ provides three
access specifiers: public, private, and protected.

10. Define public and private access specifier.


ANSWER
Public and private are called access specifiers which define the accessibility or visibility level
of class members. By default, the class members are private.
If the class members are public, it can be accessed from outside the class. But private class
members are not accessible from outside.

11. Compare Private and Public access specifiers with respect to accessibility in:
a) Same Class b) Derived Class c) Outside the Class

Access Accessibility Within Accessibility in a Accessibility Outside


Specifier the Same Class Derived Class the Class
Private Private members are Private members of Private members of a
accessible within the a base class are not class cannot be
same class only. accessible in accessed directly from
derived classes. outside the class.
Public Public members are Public members of a Public members of a
accessible within the base class are class are accessible
same class without accessible in from outside the class

ANUM NISA 7
4
COMPUTER SCIENCE (XII)

any restrictions. derived classes. using objects or member


function calls.

12. Briefly explain the concept of data hiding in C++.


Data hiding, also known as information hiding, is a fundamental concept in object-oriented
programming (OOP) that refers to the practice of restricting access to certain parts of an
object's data or implementation details.
In C++, data hiding is achieved using access specifiers like private, protected, and public.

Here's a brief explanation of data hiding in C++:


Private Members:
In C++, we can declare class members (variables and functions) as private, which means they
are accessible only within the same class where they are declared.
Private members are hidden from code outside the class, including derived classes.

Encapsulation:
Data hiding is often achieved through encapsulation, which involves combining similar data
and functions into a single unit called a class.
By encapsulating data within a class and making it private, we can control access to that data
and prevent direct manipulation from outside the class.
13. What is a constructor? write its characteristics?
Answer:
A constructor in C++ is a special member function that is automatically called when an object
of a class is created. It is used to initialize the object's data members and perform any
necessary setup tasks before the object is used. Constructors have several characteristics:
• Constructors have the same name as that of the class
• Constructors have no return type (not even void)
• Constructor is always public
• Constructors initialize the object's data members to their initial values or perform other
initialization tasks.
14. Compare Private and protected access specifiers with respect to accessibility in:
a) Same Class b) Derived Class c) Outside the Class

Answer:

Access Accessibility Accessibility in a Accessibility Outside


Specifier Within the Same Derived Class the Class
Class
Private Private members are Private members of a Private members of a
accessible within the base class are not class cannot be
same class only. accessible in derived accessed directly from

ANUM NISA 7
5
COMPUTER SCIENCE (XII)

classes. outside the class.


Protected Protected members Protected members of Protected members of a
are accessible within a base class are class are not accessible
the same class. accessible in derived from outside the class.
classes.
15. What is a destructor? write its characteristics?
A destructor in C++ is a special member function that is automatically called when an object of
a class is destroyed or goes out of scope. It is used to release resources, perform cleanup
tasks, and deallocate any allocated memory associated with the object.
Here are the characteristics of a destructor:
• Destructor has the same name as that of the class, preceded by
a tilde symbol (~).
• Destructor cannot take arguments, (so it cannot be overloaded).
 Destructor has no return type.

16. How is constructor different from other member functions in a class? Justify your
answer with at least three reasons.

Constructor Other Member Functions

Constructor name must be same as Member function cannot have same


the class name and does not have a name as class name and has a return
return type. type
It is automatically called when we They need to be called explicitly
create the object of the class and using object of class
cannot be called explicitly.
When constructor is not defined in This is not applied to member
class, C++ compiler generates a functions.
default constructor.

17. Differentiate between default / implicit constructor and user-defined explicit


constructor?

Characteristic Default (Implicit) Constructor User-defined Explicit


Constructor
Definition The constructor automatically The constructor defined explicitly
provided by the compiler if no by the programmer within the
constructor is explicitly defined. class.
Parameters No parameters. Can have parameters to initialize
the object's data members.
Invocation Called automatically when an Called explicitly by the

ANUM NISA 7
6
COMPUTER SCIENCE (XII)

object is created without any


programmer when creating an
initialization parameters.object, providing initialization
arguments.
Example class MyClass class MyClass
{ {
public public
: :
MyClass( MyClass(int
) value)
{ // Default constructor { // Constructor
code } code }
} }
; ;
18. How a member of a class can be accessed?
Members of a class in C++ can be accessed using the object name and dot operator(.),

Syntax: object.memberName

Example: MyClass obj; obj.memberFunction(); //

Accessing member function

obj.memberVariable = 10; // Accessing member variable

19. What is constructor overloading? Briefly explain with the help of an example.
Constructor overloading in C++ refers to the ability to define multiple constructors within a
class, each with a different signature (i.e., a different number or type of parameters). This
allows objects of the class to be initialized in various ways, depending on the arguments
provided to the constructor.

Here's an example of constructor overloading:


#include <iostream>
using namespace std;

// Definition of Rectangle class


class Rectangle { private:
double length;
double width;

public:

ANUM NISA 7
7
COMPUTER SCIENCE (XII)

// Default constructor
Rectangle()
{ length = 0.0;
width = 0.0;
}

// Parameterized constructor with two parameters


Rectangle(double l, double w)
{ length = l;
width = w;
}

// Member function to calculate area


double area() { return length *
width;
}

// Member function to display dimensions


void display() { cout << "Length: " <<
length << endl;
cout << "Width: " << width << endl;
}
};

// Main function int


main() {
// Create objects using different constructors
Rectangle rectangle1; // Default constructor
Rectangle rectangle2(5.0, 3.0); // Parameterized constructor with two parameters

// Display dimensions and area of each rectangle


cout << "Rectangle 1:" << endl;
rectangle1.display();
cout << "Area: " << rectangle1.area() << endl ;

cout << "Rectangle 2:" << endl;


rectangle2.display();
cout << "Area: " << rectangle2.area() << endl ;
return 0;

ANUM NISA 7
8
COMPUTER SCIENCE (XII)

}
20. Define a class declaration named Inventory in a retail store with following members:

• Private members named item number, quantity, price, and total cost.
• Constructor to the class that initialize item number, quantity, and price to 0.
• Public member function get to accept data of item number, quantity, and price.
• Public member function display to calculate and print total cost of inventory Answer: Answer:
// Inventory class declaration class
inventory
{
private: // declarations of private members
int item_number; int quantity; float price;
float total_cost;
public: // declarations of public members
inventory ( )
{
item_number = 0;
quantity = 0;
price = 0;
}
void get (void)
{
cout<< “enter item number, quantity and price:”
cin >> item_number; cin>> quantity;
cin>> price;
}
void display (void)
{
total_cost = quantity * price; cout<< “total
cost of inventory:” << total_cost;
}
};
21. Explain the concept of inheritance and polymorphism in C++ with daily life examples.

Inheritance:
Inheritance is a fundamental concept in object-oriented programming (OOP) where a class
(known as the derived class or subclass) can inherit properties and behaviors from another
class (known as the base class or superclass). This allows for code reuse and promotes the
creation of a hierarchical relationship between classes.

ANUM NISA 7
9
COMPUTER SCIENCE (XII)

Everyday Example:

Consider the concept of vehicles. We can have a base class called Vehicle with properties
and behaviors common to all vehicles, such as speed, fuelType, and startEngine(). Now, we
can create derived classes like Car, Truck, and Motorcycle, which inherit from the Vehicle
class. Each derived class can have additional properties and behaviors specific to that type of
vehicle, such as numSeats for cars or cargoCapacity for trucks. By inheriting from the
Vehicle class, these derived classes automatically gain access to the common properties and
behaviors defined in the base class.

Polymorphism:

Polymorphism is another key concept in OOP.


The word “polymorphism” means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A real-life
example of polymorphism is a person who at the same time can have different characteristics.

Everyday Example:

Let's extend the previous example of vehicles. Suppose we have a function called drive() that
takes a Vehicle object as a parameter and calls its startEngine() method. With polymorphism,
this function can accept objects of any class derived from Vehicle, such as cars, trucks, or
motorcycles. When the drive() function is called with a specific type of vehicle object, it
automatically calls the appropriate startEngine() method defined in the derived class, thanks
to dynamic binding.
22. What is Polymorphism? Give example to achieve polymorphism in C++.

Answer:

Polymorphism means many forms. It allows to perform a single action in different ways. The same
function or object behaves differently in different situations. For example, a person at the same
time has different behaviors like a father, a son, and an employee.
Example:
C++ provides overloading of operators. An operator (‘+’) is used to add two numbers (integers or
floating point), imaginary or complex numbers or concatenation of two strings. A single operator
adds these numbers and when placed between string, concatenates them. Hence, we have
achieved polymorphism.

Chapter#9 File handling

1. Define file and what is file handling?

ANUM NISA 8
0
COMPUTER SCIENCE (XII)

A file is a collection of data or information that is stored on a computer's storage medium, such
as a hard drive, solid-state drive, or external storage device.

File handling, also known as file I/O (Input/Output), refers to the process of reading from and
writing to files in a computer system.

It involves various operations, such as opening files, reading data from files, writing data to
files, closing files, and performing other file-related operations like moving, copying, or deleting
files.

File handling allows programs to interact with external data stored in files, enabling them to
perform tasks such as, Reading, Writing, and Modifying existing files.
2. Write down the differences between a text file and a binary file?
Text File Binary File
In text file, text, character, numbers In binary file data is stored in binary format
are stored one character per byte in in memory.
memory
Text files are used to store data more Binary files are used to store data more
user friendly. compactly.
Content written in text files is human Content written in binary files is not human
readable. readable and looks like encrypted content.
In text file, a special character In binary file no such character is present.
inserted after the last character to
mark the end of file.
Widely supported across different Compatibility may vary depending on the
platforms and programming specific binary format and the applications
languages. or systems that support it.
Suitable for storing and exchanging Used for storing and exchanging
textual data, source code, and nontextual data, such as multimedia files,
human-readable documents. program executables etc.
3. Write down the purpose of any three modes of file opening.
ANSWER

a. ios::app
Append mode. All output to that file to be appended to the end.

b. ios::ate
Open a file for output and move the read/write control to the end of the file.

c.ios::in

ANUM NISA 8
1
COMPUTER SCIENCE (XII)

Open a file for reading. d.


ios::out
Open a file for writing.
4. What is stream? Write down the purpose of the following functions: a) getline( )
b) get( ) Answer:
Stream:
C++ Input Output are based on streams, which are sequence of bytes flowing in and out of the
programs. In input stream, data bytes flow from an input source (e.g., keyboard, file) into the
program. In output stream, data bytes flow from the program to an output sink (e.g. console,
file).

a. getline( ) getline( ) is a standard library function defined in <fstream.h> used to read a string
or a line from an input stream. It extracts characters from the input stream and appends it to
the string object.
For example: file1.getline(name,50); // reads a string name of 50 characters from
file linked to file1

b. get( ) get( ) is a standard library function defined in <fstream.h> used to handle a single
character. It is used to fetch or read a character from file including blank space, tab, new
line character etc. For example: file2.get(ch); // reads a character ch from file linked to
file2
5. Consider the following statements and complete the following table:
Line No. Statement Purpose
1. #include<fstream.h>
2. fstream datafile;
3. datafile.open("datafile.txt" , ios::in);
4. if (! datafile)
5. { cout << ”no such file”; }
6. datafile >> ch;
7. if (datafile . eof( ))
8. datafile.close( );
Answer:
Line No. Statement Purpose
1. #include<fstream.h> Include the fstream header file in the program to use
its classes.
2. fstream datafile; Create an object of fstream class and give it the
name datafile.
3. datafile.open("datafile.txt" Use the open( ) function to open a file name
, ios::in); datafile.txt in input mode for reading data from it
4. if (! datafile) Use an if statement to check whether the file does
not exist.

ANUM NISA 8
2
COMPUTER SCIENCE (XII)

5. { cout << ”no such file”; } Text to print on the screen if the file is not found.
6. datafile >> ch; Write/store contents of the file in the variable ch.
7. if (datafile . eof( )) Use if condition and eof( ) function to ensure the
compiler keeps on reading from the file if the end is
not reached.
8. datafile.close( ); Call the close( ) function to close the file.
6. Identify and correct the errors in the following program code, that writes data to the file.
The line numbers are written along the left column. They are not part of the program
code.
Line No. Code
1 void
main(void)
2 {
3 i fstream
myfile;
4 myfile.open(writefile.txt)
;
5 myfile >> " Writing data to the file. \n
";
6 myfile.close()
;
7 }

Answer: Correct code


Line Error Identification Error-Free Code
No.
1 void
main(void)
2 {
3 File name enclosed in double fstream
quotes myfile;

4 Wrong use of File stream object myfile.open("writefile.txt")


;
5 Wrong operator used myfile << "Writing data to the
file.
\
n";
6 myfile.close();

ANUM NISA 8
3
COMPUTER SCIENCE (XII)

7 }

17. Write down the use/role of bof() and eof() functions.


ANSWER
C++ provides a special function, eof( ), that returns nonzero (meaning TRUE) when there are
no more data to be read from an input file stream, and zero (meaning FALSE) otherwise.

The bof() property is automatically set to true when the record pointer is before the first record
in the record set. The BOF property is also true if the record set is empty.

18. Explain the steps involved in reading and writing to a file in C++ program.
Reading from and writing to a file in a C++ program involves several steps. Here's
an explanation of each step involved in both processes:
Writing to a File:
1. Include Necessary Headers: Begin by including the necessary header file(s) for file
input/output operations, such as <fstream>.
2. Declare File Stream Object: Declare an object of the appropriate file stream class
(ofstream for writing) to handle file operations.
3. Open the File: Use the open() method of the file stream object to open the file in the
desired mode (std::ios::out for writing). Provide the file name.
4. Write Data to the File: Use output stream operators (<<) or the write() method to write
data to the file. This can include text, numbers, or any other data that needs to be stored in
the file.
5. Close the File: After writing all the necessary data, close the file using the close() method
of the file stream object to ensure that the file is properly closed.

Reading from a File:


1. Include Necessary Headers: Include the necessary header file(s) for file input/output
operations, such as <fstream>.
2. Declare File Stream Object: Declare an object of the appropriate file stream class
(ifstream for reading) to handle file operations.
3. Open the File: Use the open() method of the file stream object to open the file in the
desired mode (std::ios::in for reading). Provide the file name
4. Read Data from the File: Use input stream operators (>>) or the read() method to read
data from the file. This can include text, numbers, or any other data stored in the file.
5. Check for End-of-File (EOF): Use the eof() method or check the stream object's status to
determine if the end of the file has been reached. This helps in reading data until the end of
the file is reached.
6. Close the File: After reading all the necessary data, close the file using the close() method
of the file stream object to release system resources associated with the file.

ANUM NISA 8
4
COMPUTER SCIENCE (XII)

19. Write a program to read a file.


// reading a text file
#include <iostream.h>
#include <conio.h>
#include <fstream.h>
using namespace std;
int main () char ch
[50]; ifstream flag ;
flag.open("c:\\
TestRecord.txt”); //
Opening the file //
checking that file is
successfully opened
or not if (!flag)
{ cout << "Can't open input file named"<< endl; }
cout<<"Output is"<<endl; while(!flag.eof())
{
flag>>ch;
cout<<ch<<endl;
}
flag.close();
getch();
return 0;
}
20. Write a C++ program to write text in a file.
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
int main ()
{
ofstream myfile; myfile.open ("example1.txt"); //
Opening the file // checking that file is
successfully opened or not if (!flag)
{ cout << "Can't open input file named"<< endl; }
myfile << "This is a program that tells you how to write to a file. In";
myfile.close(); getch();
return 0;
}

ANUM NISA 8
5
COMPUTER SCIENCE (XII)

ANUM NISA 8
6

You might also like