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

Computer Science Part-2

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

Computer Science Part-2

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

Chapter No.

1 “Introduction”

Exercise Solution

Q.1 Fill in the Blanks

i. The concept of executing multiple programs simultaneously on multiple processors is known


as Multiprocessing.

ii. Multitasking operating systems execute multiple tasks simultaneously.

iii. The central theme of modern operating systems, based on the concept of switching among
multiple programs in memory, is called Multiprogramming.

iv. A process consists of five states i.e., new, ready, running, block, and exit.

v. UNIX is a multitasking, multi-user operating system for servers, desktops, and laptops,
originally developed in 1969 at Bell Labs.

Q.2 Multiple Choice Questions

i. Operating system is a(n):

 a. Application software
 b. System software
 c. Driver
 d. Utility program
Correct Answer: b. System software

ii. DOS stands for:

 a. Doctor of system
 b. Document of system
 c. Disk operating system
 d. Disk operating schemes
Correct Answer: c. Disk operating system

iii. Which one of the following is correct for multiprocessing operating systems?

 a. Used on systems having only one processor


 b. Cannot execute more than one processes at a time
 c. Run on systems having more than one processors
 d. Run on systems having small limited memory
Correct Answer: c. Run on systems having more than one processors
iv. Multiprogramming refers to:

 a. Having several programs in RAM at the same time


 b. Multiprocessing
 c. Writing programs in multiple languages
 d. Running programs directly from hard disk
Correct Answer: a. Having several programs in RAM at the same time

v. The most recently launched operating system of Microsoft is:

 a. Windows 98
 b. Windows 11
 c. DOS
 d. Windows NT
Correct Answer: b. Windows 11

vi. Which of the following is not an operating system?

 a. Linux
 b. MS Word
 c. UNIX
 d. Windows XP Professional
Correct Answer: b. MS Word

vii. Which type of software enables you to solve specific problems or perform specific tasks?

 a. System software
 b. Operating system
 c. Utility software
 d. Application software
Correct Answer: d. Application software

viii. Which type of software controls your application software and manages how your hardware
devices work together?

 a. System software
 b. Operating system
 c. Utility software
 d. Application software
Correct Answer: b. Operating system

ix. A technique in which a process, executing an application, is divided into threads that can run
concurrently is called:

 a. Multithreading
 b. Multiprocessing
 c. Batch processing
 d. Multiprogramming
Correct Answer: a. Multithreading

Q.3 True/False Statements

i. The operating system acts as an interface between the computer hardware and the human user.

 True

ii. Multiprogramming allows the processor to make use of idle time caused by I/O wait.

 True

iii. In the early computers, the operating systems did not exist.

 True

iv. In a time-sharing system, when a process is assigned to the CPU for execution, it remains
there till its completion.

 False

v. A process is a dispatchable unit of thread.

 False

vi. A process is directly assigned to the CPU for processing from a block state when the event for
which it is waiting happens.

 True

vii. A process is said to be in the ready state if it is waiting for some external event which has not
yet occurred.

 False

viii. Batch processing does not support interactivity.

 True
Q.4 What is an Operating System? Explain different types of operating systems.

Answer: An Operating System (OS) is a software that acts as an intermediary between


computer hardware and the user. It manages hardware resources, provides a user interface, and
executes and controls software applications. The OS is essential for the functioning of any
computer system as it manages the execution of programs, allocates resources, and ensures that
different tasks do not interfere with each other.

Different Types of Operating Systems

Operating systems can be categorized based on their functionality, the way they handle tasks,
and their application. Here are the main types:

1. Batch Processing Operating System


o Explanation: In batch processing systems, tasks are grouped together and
processed in batches without user interaction. This type of OS is suitable for tasks
that require large-scale data processing.
o Example: Early mainframe computers used batch processing to handle jobs like
payroll processing or scientific calculations.
2. Multiprogramming Operating System
o Explanation: A multiprogramming OS allows multiple programs to be loaded
into memory and executed simultaneously by the CPU. It maximizes CPU
utilization by switching between programs while others are waiting for I/O
operations.
o Example: Early versions of UNIX and IBM's OS/360.
3. Multitasking Operating System
o Explanation: A multitasking OS enables multiple tasks to run concurrently by
sharing CPU time. It provides a way for users to run multiple applications
simultaneously, such as a web browser, text editor, and music player.
o Example: Modern versions of Windows, macOS, and Linux.
4. Time-Sharing Operating System
o Explanation: Time-sharing systems allow multiple users to share system
resources simultaneously. The OS allocates a small time slice to each user or task,
giving the impression that the system is dedicated to them alone.
o Example: UNIX and early versions of Linux in academic environments.
5. Real-Time Operating System (RTOS)
o Explanation: An RTOS is designed to process data as it comes in, typically
within a strict time constraint. It is used in environments where timing is critical,
such as embedded systems, medical devices, and industrial control systems.
o Example: VxWorks, QNX, and the operating systems in embedded devices like
automotive control systems.
6. Multiprocessor Operating System
o Explanation: A multiprocessor OS supports a system with multiple CPUs,
allowing them to work together to process tasks. It improves performance and
reliability by distributing the load across processors.
o Example: Windows Server and Linux distributions that support symmetric
multiprocessing (SMP).
7. Parallel Processing Operating System
o Explanation: This type of OS is used in systems where multiple processors are
used to perform multiple tasks simultaneously. It is common in high-performance
computing environments where tasks are divided among processors to reduce
processing time.
o Example: Supercomputers running parallel versions of UNIX or Linux.
8. Distributed Operating System
o Explanation: A distributed OS manages a group of independent computers and
makes them appear to the user as a single coherent system. It is used in networked
environments where tasks are distributed across multiple machines.
o Example: Google’s cluster management system, distributed versions of UNIX
and Linux.
9. Embedded Operating System
o Explanation: Embedded OSs are specialized systems designed to operate on
embedded devices, which are typically small, specialized computing devices like
routers, automotive systems, and home appliances.
o Example: Embedded Linux, Windows Embedded, and the operating system in
your smartphone.
10. Single-User Operating System
o Explanation: A single-user OS is designed for one user at a time, although it may
allow multiple profiles. It is suitable for personal computers and devices.
o Example: Windows 10, macOS.
11. Multi-User Operating System
o Explanation: A multi-user OS allows multiple users to access the computer
simultaneously. It is commonly used in server environments where multiple users
need access to shared resources.
o Example: UNIX, Linux, Windows Server.

Each type of operating system is designed to meet specific needs, from managing multiple users
to ensuring real-time performance in critical systems.

 Q.5 Explain time-sharing operating system along with an example.

Answer: A time-sharing operating system is designed to allow multiple users to interact with a
computer system simultaneously by sharing its processing time. The core idea is to provide each
user with a "slice" of the processor's time, creating the illusion that each user has their own
dedicated machine. This system is essential for improving the efficiency of computing resources
and making it possible for many users to work on the same system at the same time.

Key Features of Time-Sharing Systems:

1. Multitasking: The operating system manages multiple tasks by rapidly switching


between them. Each task gets a small time slot (or quantum) to execute, and the CPU
switches between tasks so quickly that it appears as though all tasks are running
simultaneously.
2. Resource Sharing: Time-sharing systems allow multiple users to share system resources
like CPU time, memory, and storage. This is more efficient than having a separate
machine for each user.
3. Interactive Computing: Users interact with the computer system in real-time. The
system responds to user inputs promptly, making it suitable for interactive applications.
4. Fairness: The operating system ensures that each user gets a fair share of the CPU time
and other resources.

Example:

Unix Operating System: One of the earliest and most well-known time-sharing operating
systems is Unix. In Unix, multiple users can log in to the system simultaneously from different
terminals or over a network. Each user can run processes and execute commands as if they were
the only user on the system, while the Unix kernel efficiently allocates CPU time among all
active users.

For instance, if five users are logged into a Unix-based server, each user might be running
different applications or commands. The Unix operating system allocates short time slices to
each user's processes, so everyone gets a portion of the CPU's time. This rapid switching makes
it seem as if each user’s processes are running concurrently, even though the CPU is actually
sharing its time among all active users.

 Q.6 Define distributed operating system and describe its advantages and
disadvantages.

Answer: A distributed operating system (DOS) is a type of operating system that manages a
group of separate, interconnected computers to make them appear as a single coherent system to
users and applications. Unlike traditional operating systems, which manage resources on a single
machine, a distributed operating system handles resources across multiple machines that
communicate over a network.

Key Features:

1. Resource Sharing: Computers in a distributed system share resources like files, printers,
and storage, making them available to all users on the network.
2. Transparency: The system aims to provide a seamless experience where users and
applications are unaware of the underlying distribution of resources. This includes
transparency in location, migration, replication, and concurrency.
3. Scalability: It can easily scale up by adding more machines to the network, allowing the
system to handle increasing loads and user demands.
Advantages:

1. Resource Utilization: Distributed systems can make better use of available resources by
leveraging the combined processing power and storage of multiple machines.
2. Fault Tolerance: By distributing tasks across multiple machines, the system can be more
resilient to failures. If one machine fails, others can take over its tasks, minimizing the
impact on the overall system.
3. Scalability: It is easier to scale a distributed system by adding more nodes (machines) to
handle increased load or to improve performance.
4. Improved Performance: Tasks can be parallelized and executed concurrently on
different machines, potentially leading to faster processing and response times.

Disadvantages:

1. Complexity: Managing and coordinating a distributed system is complex. Ensuring


consistency, handling failures, and managing resource allocation require sophisticated
algorithms and protocols.
2. Security: Securing a distributed system is challenging because data and resources are
spread across multiple machines and networks. Ensuring secure communication and
access control can be more difficult.
3. Network Dependency: The performance and reliability of a distributed system depend
on the underlying network. Network issues can impact communication between machines
and degrade system performance.
4. Synchronization Issues: Coordinating actions across multiple machines can lead to
synchronization problems, where different machines might have conflicting or outdated
information.

Example:

Google's Distributed System: Google uses a distributed operating system to manage its massive
infrastructure. The system spreads tasks across thousands of servers in data centers worldwide.
This distributed approach helps Google efficiently handle search queries, store vast amounts of
data, and provide services with high reliability and scalability.

 Q.7 Write short notes on the following:

a. Different States of a Process

A process in an operating system can be in one of several states during its lifecycle:

1. New: The process is being created. It is in the initial phase where it is set up in memory
but not yet executing.
2. Ready: The process is loaded into memory and waiting for CPU time. It is ready to run
but waiting for the CPU scheduler to allocate it processor time.
3. Running: The process is currently being executed by the CPU. It is actively using CPU
resources to perform tasks.
4. Waiting (Blocked): The process is waiting for some event or resource to become
available, such as input from a user or completion of an I/O operation.
5. Terminated (Exit): The process has completed execution or is terminated by the
operating system. It is cleaned up and removed from memory.

b. DOS (Disk Operating System)

Disk Operating System (DOS) refers to a family of operating systems that manage and control
disk storage and file systems. The most well-known version is MS-DOS (Microsoft Disk
Operating System). Key features include:

1. Command-Line Interface (CLI): Users interact with DOS through text-based


commands entered at a command prompt.
2. File Management: DOS provides basic file management capabilities such as creating,
deleting, and manipulating files and directories.
3. Disk Operations: It manages disk storage, including reading from and writing to disk
drives, organizing files, and handling file systems.
4. Batch Processing: Supports scripting of commands in batch files to automate repetitive
tasks.

c. Embedded Operating Systems

Embedded Operating Systems are specialized operating systems designed to manage hardware
in embedded systems, which are dedicated to specific tasks and applications. Features include:

1. Resource Efficiency: They are optimized for systems with limited resources such as
memory and processing power. Examples include real-time constraints and minimal
overhead.
2. Real-Time Capabilities: Many embedded OSs support real-time operations to ensure
timely responses to external events.
3. Specific Functionality: Tailored to perform specific functions or control specific
hardware. Examples include operating systems in appliances, automotive systems, and
medical devices.
4. Minimal User Interface: Often have minimal or no graphical user interface, focusing
instead on direct hardware control and specific application needs.

Examples of embedded operating systems include RTOS (Real-Time Operating Systems) like
FreeRTOS and Embedded Linux.
Q.8 Describe functions of an operating system.

Answer: The functions of an operating system (OS) are essential for managing the hardware and
software resources of a computer. Here are the primary functions:

1. Process Management

 Explanation: The OS handles the creation, scheduling, and termination of processes. It


manages process synchronization, communication, and deadlock handling.
 Example: When you run a program, the OS creates a process for it, schedules it for
execution, and manages its lifecycle until it completes.

2. Memory Management

 Explanation: The OS is responsible for managing the computer's memory. It allocates


memory to processes when they need it and deallocates it when it's no longer needed,
ensuring efficient use of memory resources.
 Example: When multiple applications are open, the OS ensures each gets the necessary
memory while preventing conflicts.

3. File Management

 Explanation: The OS manages files on the computer. It handles the creation, deletion,
reading, writing, and organization of files in directories, as well as managing file
permissions and storage.
 Example: When you save a document, the OS writes the data to the storage device and
maintains information about where the file is located.

4. Input/Output (I/O) System Management

 Explanation: The OS manages input and output devices like keyboards, mice, printers,
and displays. It provides a standard interface for these devices to interact with software.
 Example: When you type on a keyboard, the OS captures the keystrokes and directs
them to the appropriate application.

5. Secondary Storage Management

 Explanation: The OS manages secondary storage devices, such as hard drives and SSDs.
It handles data storage, retrieval, and organization on these devices.
 Example: The OS keeps track of free space on a hard drive and ensures data is stored
efficiently.
6. Network Management

 Explanation: The OS manages network connections, allowing computers to


communicate with each other over a network. It handles data transmission, error
detection, and network security.
 Example: When you access the internet, the OS manages the network interface, connects
to the network, and transmits data to and from the web.

7. Protection System

 Explanation: The OS ensures that all programs and users of the system do not interfere
with each other. It provides mechanisms to control access to the computer's resources,
ensuring security and privacy.
 Example: The OS prevents unauthorized users from accessing sensitive data by
enforcing user authentication and file permissions.

8. Command-Interpreter System

 Explanation: Also known as the shell, this function interprets and executes commands
given by the user. It provides a user interface for interacting with the operating system.
 Example: When you use the command prompt in Windows or the terminal in Linux, the
OS interprets and executes the commands you enter.

These functions collectively ensure that the operating system effectively manages all aspects of a
computer's operation, providing a stable and efficient environment for running applications.

Q.9 Write in detail about DOS, Windows, and UNIX operating systems.

 Answer:

Disk Operating System (DOS)

Disk Operating System (DOS) refers to a family of operating systems that manage disk storage
and provide a command-line interface for user interaction. The most notable DOS operating
systems include MS-DOS and its various derivatives.

Key Features:

1. Command-Line Interface (CLI): DOS primarily operates through a text-based


command line. Users type commands to perform operations like file manipulation,
program execution, and system configuration.
2. File Management: DOS supports basic file operations such as creating, deleting,
copying, and renaming files and directories. It uses the FAT (File Allocation Table) file
system for managing disk storage.
3. Batch Processing: DOS supports batch files (.bat), which are scripts containing a
sequence of commands that can be executed automatically. This feature is useful for
automating repetitive tasks.
4. Disk Operations: DOS provides tools to manage disk partitions, format disks, and
handle disk errors. It supports both floppy disks and hard drives.
5. Single-Tasking: DOS is a single-tasking operating system, meaning it can only execute
one program at a time. Modern multitasking capabilities are limited or non-existent in
standard DOS versions.

Example:

MS-DOS (Microsoft Disk Operating System) was a dominant OS for personal computers in
the 1980s and early 1990s. It was widely used before the advent of more advanced graphical
operating systems like Windows.

Windows Operating System

Windows is a family of graphical operating systems developed by Microsoft. The Windows OS


has evolved significantly since its introduction and is known for its user-friendly interface and
broad application support.

Key Features:

1. Graphical User Interface (GUI): Windows provides a graphical interface with


windows, icons, menus, and pointers, making it user-friendly and accessible for non-
technical users.
2. Multitasking: Modern Windows versions support multitasking, allowing users to run
multiple applications simultaneously. It uses a preemptive multitasking model to manage
CPU time among running processes.
3. File System Support: Windows initially used the FAT file system and later introduced
NTFS (New Technology File System), which supports larger files, enhanced security,
and better performance.
4. System Services and APIs: Windows includes a wide range of system services and APIs
that support application development. This includes support for networking, hardware
drivers, and multimedia.
5. Security Features: Recent versions of Windows incorporate advanced security features
like User Account Control (UAC), Windows Defender, and BitLocker encryption to
protect against malware and unauthorized access.

Example:

Windows 10 and Windows 11 are the latest major releases in the Windows operating system
family, offering a modern interface, extensive software support, and integration with cloud
services.
UNIX Operating System

UNIX is a powerful, multiuser, multitasking operating system originally developed in the 1960s
and 1970s at AT&T's Bell Labs. It has influenced many modern operating systems and has
several variants, including commercial and open-source versions.

Key Features:

1. Multitasking and Multiuser Capabilities: UNIX supports multiple users and multiple
processes running concurrently. It uses a time-sharing model to manage CPU resources
effectively.
2. File System: UNIX uses a hierarchical file system with a single root directory (/) and
directories branching off it. Files and directories are organized in a tree-like structure,
making it easy to manage and navigate.
3. Portability: UNIX is designed to be portable across different hardware platforms. Its
codebase is written in the C programming language, which enhances its portability.
4. Security and Permissions: UNIX has a robust permission model, where files and
directories have associated access permissions (read, write, execute) for the owner,
group, and others.
5. Command-Line Interface and Shells: UNIX provides a powerful command-line
interface. Users interact with the system through shells like Bash (Bourne Again Shell) or
KornShell, which support scripting and automation.
6. Networking: UNIX includes extensive networking capabilities, allowing systems to
communicate over networks using protocols like TCP/IP.

Example:

Linux is a popular UNIX-like operating system based on the principles of UNIX. It is open-
source and widely used in various environments, including servers, desktops, and embedded
systems. Examples of Linux distributions include Ubuntu, Red Hat Enterprise Linux
(RHEL), and Debian.

Q.10 How and where real-time operating system is used?

Answer: Real-Time Operating Systems (RTOS) are designed to provide deterministic and
predictable responses to external events within a strict time constraint. They are used in systems
where timely processing and response are critical, and delays can lead to system failure or
undesirable outcomes.

Key Characteristics of RTOS:

1. Deterministic Behavior: RTOS ensures that critical tasks are executed within a
guaranteed time frame. This is essential for systems where timing is crucial.
2. Priority-Based Scheduling: RTOS often uses priority-based scheduling to ensure that
high-priority tasks receive prompt attention.
3. Minimal Latency: RTOS aims to minimize latency, the delay between the occurrence of
an event and the system's response.
4. Concurrency Management: Efficient management of multiple concurrent tasks, often
through mechanisms like semaphores and mutexes, is essential to prevent conflicts and
ensure smooth operation.

Applications of RTOS:

1. Embedded Systems:
o Automotive Systems: RTOS is used in automotive control systems, such as
airbag deployment, anti-lock braking systems (ABS), and engine control units
(ECUs), where timely responses are critical for safety and performance.
o Industrial Automation: RTOS manages real-time processes in manufacturing
systems, robotics, and control systems to ensure precise and reliable operations.
2. Consumer Electronics:
o Medical Devices: RTOS is employed in medical equipment like pacemakers,
infusion pumps, and imaging devices, where precise timing and reliability are
crucial for patient safety and device functionality.
o Home Appliances: In devices such as washing machines, microwave ovens, and
smart thermostats, RTOS ensures timely operation and coordination of various
functions.
3. Telecommunications:
o Network Routers and Switches: RTOS is used in networking equipment to
handle high-speed data transmission, manage network traffic, and ensure low
latency communication.
4. Aerospace and Defense:
o Avionics Systems: RTOS is essential in flight control systems, navigation
systems, and other avionics applications where reliable and timely processing is
critical for safe and efficient operation.
o Missile Guidance Systems: RTOS is used in missile guidance and control
systems to ensure precise targeting and response.
5. Real-Time Data Processing:
o Financial Systems: In trading systems, RTOS ensures that financial transactions
and market data processing are handled with minimal delay to maintain market
integrity and performance.
o Surveillance Systems: RTOS manages real-time video processing and analysis in
security and surveillance systems, enabling prompt detection and response to
events.

Examples of RTOS:

 FreeRTOS: A popular open-source RTOS used in various embedded applications.


 VxWorks: A commercial RTOS used in aerospace, defense, and industrial applications.
 QNX: Known for its use in automotive and industrial systems, providing a reliable and
responsive operating environment.
 RTEMS: Used in embedded systems, including space missions and industrial control
systems.

In summary, RTOS plays a crucial role in applications where timely and predictable processing
is necessary to ensure system performance, safety, and reliability.

 Q.11 Differentiate the following:

 DOS vs Windows

DOS (Disk Operating System):

 User Interface: Primarily command-line based. Users interact with the system by typing
commands.
 Multitasking: Single-tasking (standard versions). Only one application runs at a time.
 File System: Uses FAT (File Allocation Table). File management and disk operations are
basic.
 Modern Use: Mostly obsolete for general computing but still used in some legacy
systems and embedded environments.

Windows:

 User Interface: Graphical User Interface (GUI). Users interact with the system using
windows, icons, and menus.
 Multitasking: Supports multitasking, allowing multiple applications to run
simultaneously.
 File System: Uses NTFS (New Technology File System) in modern versions, which
supports advanced features like large file sizes and improved security.
 Modern Use: Widely used for personal computing, business environments, and gaming.

 Process vs Thread

Process:

 Definition: A process is an independent program in execution with its own memory


space and resources. Each process operates in its own address space.
 Resource Allocation: Each process has its own resources (e.g., memory, file handles).
 Isolation: Processes are isolated from each other; one process cannot directly access the
memory or resources of another process.

Thread:

 Definition: A thread is a smaller unit of execution within a process. Threads within the
same process share the same memory space and resources.
 Resource Allocation: Threads share resources with other threads in the same process,
which can lead to faster context switching compared to processes.
 Isolation: Threads within the same process are not isolated from each other, which
allows for easier communication but requires careful synchronization to avoid conflicts.

 Multitasking vs Multiprogramming

Multitasking:

 Definition: The capability of an operating system to execute multiple tasks or processes


simultaneously. It can be further divided into:
o Preemptive Multitasking: The OS allocates CPU time to different tasks and
switches between them based on priorities or time slices.
o Cooperative Multitasking: Tasks voluntarily yield control of the CPU to allow
other tasks to run.

Multiprogramming:

 Definition: A technique where multiple programs are loaded into memory and the CPU
switches between them. The primary goal is to maximize CPU utilization by keeping it
busy with various processes.
 Execution: In multiprogramming, multiple programs are not necessarily executed
simultaneously but are managed to ensure that the CPU remains busy, typically through
context switching.

 Parallel Processing vs Distributed Operating System

Parallel Processing:

 Definition: The simultaneous execution of multiple processes or threads across multiple


processors or cores within a single computer system. This can involve both shared-
memory and distributed-memory architectures.
 Objective: To increase computational speed and efficiency by dividing tasks into smaller
sub-tasks that can be executed concurrently.

Distributed Operating System:

 Definition: An OS that manages a group of separate, interconnected computers to make


them appear as a single coherent system to users. It handles resource management,
communication, and coordination across multiple machines.
 Objective: To provide seamless resource sharing and efficient computing by integrating
multiple networked systems into a unified operating environment.
 Single-user vs Multi-user Operating System

Single-user Operating System:

 Definition: An operating system designed to be used by one user at a time. It does not
support concurrent user access.
 Examples: MS-DOS, early versions of Windows.
 Usage: Ideal for personal computers and devices where only one person interacts with
the system at any given time.

Multi-user Operating System:

 Definition: An operating system that supports multiple users simultaneously. It manages


user accounts, permissions, and concurrent access to system resources.
 Examples: UNIX, Linux, Windows Server.
 Usage: Commonly used in environments such as servers, mainframes, and networked
systems where multiple users need to access and share resources concurrently.
Chapter No.2 “System Development Life Cycle”

Exercise Solution

Q.1 Fill in the Blanks:

1. The requirements that define the function of a software system are called functional
requirements.
2. All the activities that make a software system available for use is known as software
deployment or implementation.
3. The person who is familiar with a variety of programming languages, operating systems,
and computer hardware is known as a system analyst.
4. A software tester is basically a programmer having a specialty in testing the computer
programs.
5. A project manager is a professional in the field of project management.

Q.2 Multiple Choice Questions:

1. The first step in the system development life cycle is:


o a. Analysis
o b. Planning
o c. Problem Identification (Correct Answer)
o d. Development and Documentation
2. The organized process or set of steps that needs to be followed to develop an
information system is known as:
o a. Analytical cycle
o b. Design cycle
o c. Program specifications
o d. System Development Life Cycle (Correct Answer)
3. Enhancements, upgradation and bugs fixation are done during the _____ step in the
SDLC.
o a. Maintenance and Evaluation (Correct Answer)
o b. Problem Identification
o c. Design
o d. Development and Documentation
4. The _____ determines whether the project should go forward.
o a. Feasibility (Correct Answer)
o b. Problem Identification
o c. System Evaluation
o d. Program Specification
5. _____ spend most of their time in the beginning stages of the SDLC, talking with
end-users, gathering requirements, documenting systems and proposing solutions.
o a. Project Managers
o b. System Analysts (Correct Answer)
o c. Network Engineers
od. Database Administrators
6. The entities having a positive or negative influence in the project completion are
known as:
o a. Stakeholders (Correct Answer)
o b. Stake Supervisors
o c. Stake Owners
o d. Full Stake Developer
7. System maintenance is performed in response to _____
o a. Business Changes
o b. Hardware and Software Changes
o c. User's Requests for Additional Features
o d. All of the Above (Correct Answer)

Q.3 True/False:

1. A stakeholder is any person or organization who has a direct or indirect interest in


the project.
o True
2. System maintenance is performed to gather the requirements of the proposed
system.
o False
3. The how, when, what type of questions are answered in the planning phase of
SDLC.
o True
4. The three architectures i.e., algorithms, pseudo code and flowcharts are used in the
implementation phase of SDLC.
o False
5. Each phase of SDLC is accomplished as a discrete, separate step.
o True

Q.4: Define Software Development Life Cycle (SDLC). What are its objectives?

Answer:
The Software Development Life Cycle (SDLC) is a systematic process used for developing
software applications. It outlines a series of steps that are followed to create high-quality
software. The SDLC provides a structured approach to software development, ensuring that the
software is developed in a consistent, efficient, and reliable manner.
Objectives of SDLC:

1. Deliver High-Quality Software: SDLC ensures that the software meets or exceeds the
expectations of the end-users by following a structured process that emphasizes quality at
every phase.
2. Meet User Requirements: The SDLC ensures that the final software product fulfills the
specific needs and requirements of its users.
3. Manage Costs and Time: By planning and managing each phase of development, the
SDLC helps in controlling the overall cost and time required for software development.
4. Minimize Risks: The SDLC includes phases like analysis, design, and testing, which
help in identifying and mitigating risks early in the development process.
5. Improve Project Management: SDLC provides a clear framework for managing the
project, ensuring that all stakeholders understand the progress and status of the
development.
6. Ensure Maintainability and Scalability: The SDLC emphasizes creating software that
can be easily maintained, updated, and scaled as needed.
7. Facilitate Communication and Collaboration: The SDLC involves multiple
stakeholders, including developers, testers, analysts, and users. It ensures effective
communication and collaboration among all parties involved.

Q.5: Briefly explain the phases of SDLC.

Answer:
Phases of the Software Development Life Cycle (SDLC):

1. Planning:
o Objective: Define the project's purpose, scope, and constraints.
o Activities:
 Conduct feasibility studies (technical, operational, and financial).
 Develop a project plan including timelines, resources, and budget.
 Identify stakeholders and establish communication channels.
o Deliverables: Project charter, scope statement, and project management plan.
2. Analysis:
o Objective: Gather and analyze requirements to understand what the system needs
to accomplish.
o Activities:
 Engage with stakeholders through interviews, surveys, and workshops to
gather requirements.
 Document functional and non-functional requirements.
 Create use cases, process flows, and data models.
o Deliverables: Requirements specification document, use case diagrams, and data
flow diagrams.
3. Design:
o Objective: Create detailed design specifications that outline how the system will
be built.
o Activities:
 Design system architecture, including hardware and software components.
 Develop detailed design documents for databases, user interfaces, and
application logic.
 Create prototypes or mockups if needed.
o Deliverables: Design specification document, architecture diagrams, and
interface prototypes.
4. Development:
o Objective: Build the system according to the design specifications.
o Activities:
 Write code for the application, following coding standards and best
practices.
 Integrate components and modules to form a complete system.
 Perform initial testing during development (unit testing).
o Deliverables: Source code, compiled binaries, and initial test results.
5. Testing:
o Objective: Ensure the system is free of defects and meets the specified
requirements.
o Activities:
 Conduct various types of testing (e.g., unit testing, integration testing,
system testing, and user acceptance testing).
 Identify, document, and fix defects and issues.
 Validate that all requirements are met and the system performs as
expected.
o Deliverables: Test plans, test cases, defect reports, and test summary reports.
6. Deployment:
o Objective: Deliver the completed system to the production environment and
make it available to users.
o Activities:
 Install the system on production servers or distribute it to users.
 Configure the system and perform final checks to ensure a smooth
deployment.
 Provide training and documentation for users.
o Deliverables: Deployed system, user manuals, and training materials.
7. Maintenance:
o Objective: Support and enhance the system after deployment to address issues
and adapt to changing needs.
o Activities:
 Monitor system performance and usage.
 Address user-reported issues and fix bugs.
 Implement updates and enhancements based on user feedback and
evolving requirements.
o Deliverables: Maintenance logs, update patches, and enhanced system features.

Q.6: Why is the Software Development Life Cycle important for the development of
software?

Answer:
The Software Development Life Cycle (SDLC) is crucial for several reasons:
1. Structured Approach: SDLC provides a systematic and organized method for software
development, ensuring that all aspects of the project are addressed. This helps in
managing complexity and maintaining consistency throughout the development process.
2. Clear Requirements: By following the SDLC, requirements are thoroughly gathered and
documented in the early phases. This minimizes misunderstandings and helps ensure that
the final product meets user needs and expectations.
3. Risk Management: SDLC phases, such as planning and analysis, help identify potential
risks and issues early in the project. This proactive approach allows for risk mitigation
strategies to be implemented before they become significant problems.
4. Efficient Resource Management: The SDLC framework facilitates better planning and
allocation of resources (time, budget, personnel). This leads to more efficient use of
resources and helps avoid project overruns and delays.
5. Quality Assurance: The testing phase in the SDLC ensures that the software is
thoroughly evaluated for defects and issues. This helps improve the quality of the final
product, making it more reliable and user-friendly.
6. Project Visibility: The SDLC provides clear milestones and deliverables, allowing
stakeholders to track progress and provide feedback throughout the project. This
transparency helps keep the project aligned with its goals and objectives.
7. Documentation: Each phase of the SDLC involves creating documentation (e.g.,
requirements, design, test plans). This documentation serves as a reference for
developers, testers, and future maintenance activities, ensuring continuity and
consistency.
8. User Involvement: The SDLC involves users and stakeholders in the requirements
gathering and testing phases. This helps ensure that the final product aligns with user
needs and expectations, increasing user satisfaction.
9. Maintenance and Support: The maintenance phase ensures that the software continues
to function well after deployment. It allows for ongoing support, updates, and
improvements, ensuring the software remains relevant and effective over time.
10. Regulatory and Compliance: For projects with regulatory or compliance requirements,
the SDLC helps ensure that these are addressed appropriately throughout the
development process, reducing the risk of non-compliance.

Q.7: Who are stakeholders of SDLC? Describe their responsibilities.

Answer:
Stakeholders in the Software Development Life Cycle (SDLC) are individuals or groups with an
interest in the project's outcome. Each stakeholder plays a specific role and has unique
responsibilities throughout the SDLC. Here are some key stakeholders and their typical
responsibilities:

1. Project Sponsor:
o Responsibilities: Provides funding and resources for the project. They champion
the project, define high-level goals and objectives, and approve major decisions
and changes.
2. Project Manager:
o Responsibilities: Oversees the project from initiation to completion. Manages the
project plan, schedule, and budget. Coordinates the efforts of the project team,
handles communication with stakeholders, and ensures the project meets its
objectives and deadlines.
3. Business Analyst:
o Responsibilities: Gathers and documents business requirements. Analyzes and
understands user needs, translates these into technical requirements, and ensures
that the software meets business goals. They act as a bridge between the business
stakeholders and the development team.
4. Development Team:
o Responsibilities: Includes software developers, programmers, and engineers who
design, code, and build the software according to the specifications. They are
responsible for implementing the functionality and ensuring the software is built
to standard.
5. Quality Assurance (QA) Team:
o Responsibilities: Tests the software to identify defects and ensure it meets the
specified requirements. They create and execute test cases, report bugs, and verify
that issues are resolved before the software is deployed.
6. UI/UX Designers:
o Responsibilities: Design the user interface and user experience aspects of the
software. They create prototypes, design layouts, and ensure that the software is
user-friendly and meets aesthetic and usability standards.
7. End Users:
o Responsibilities: Use the software in their daily operations. They provide
feedback on functionality, usability, and performance. Their input is crucial in
validating that the software meets real-world needs and expectations.
8. System Administrators/IT Support:
o Responsibilities: Manage the deployment, configuration, and maintenance of the
software in the production environment. They handle issues related to system
performance, security, and user support.
9. Database Administrators (DBAs):
o Responsibilities: Manage the design, implementation, and maintenance of
databases used by the software. They ensure data integrity, performance, and
security.
10. Regulatory and Compliance Officers:
o Responsibilities: Ensure that the software complies with relevant laws,
regulations, and industry standards. They review the software development
process and the final product to ensure it meets all required compliance
requirements.
11. Marketing and Sales Teams:
o Responsibilities: Promote and sell the software. They provide input on market
requirements and customer expectations, and support the software’s market
launch and distribution strategies.
12. Training and Documentation Specialists:
o Responsibilities: Create user manuals, help documentation, and training
materials. They assist in training end-users and ensure that adequate support
resources are available.

Each stakeholder’s involvement and contributions are critical to the successful completion of the
software project. Their collaboration and communication throughout the SDLC help ensure that
the software meets its intended goals and delivers value to the organization and its users.

Q.8: Differentiate between algorithm and pseudo code.

Answer:

Algorithms and pseudocode are both tools used in programming and software development to
design and communicate solutions to problems. However, they serve different purposes and are
used in different ways. Here’s a comparison:

Algorithm

1. Definition: An algorithm is a step-by-step procedure or a set of rules designed to perform


a specific task or solve a particular problem. It’s a general, high-level description of how
to achieve a goal.
2. Nature: Abstract and language-independent. It focuses on the logic and sequence of steps
required to solve a problem without being tied to a specific programming language or
syntax.
3. Representation: Typically written in plain English or mathematical notation. It can be
expressed as a flowchart, a list of steps, or a verbal description.
4. Purpose: To outline the overall approach and methodology for solving a problem. It
provides a high-level view of the problem-solving process.
5. Example: An algorithm for sorting a list of numbers might involve steps like comparing
elements, swapping them if necessary, and repeating the process until the list is sorted.

Pseudocode

1. Definition: Pseudocode is a way of representing an algorithm using a simplified,


informal syntax that mimics programming languages. It combines elements of natural
language and programming language constructs to describe the logic of a program.
2. Nature: More structured and closer to actual code. It uses a syntax that resembles
programming languages but is still readable and understandable by humans. It’s less
formal than actual code but more structured than plain English.
3. Representation: Written in a format that uses keywords and conventions similar to
programming languages but without strict syntax rules. It often includes control
structures like loops and conditionals.
4. Purpose: To outline the detailed steps of an algorithm in a format that can be easily
translated into actual code. It helps programmers understand the logic and flow of the
algorithm before coding.
5. Example: Pseudocode for sorting a list of numbers might look like this:

Procedure SortList

For each element in the list

Compare the element with the next one

If the element is greater than the next one

Swap them

Repeat until the list is sorted

End Procedure

Key Differences

 Level of Detail: Algorithms are high-level descriptions, while pseudocode is more


detailed and closer to actual code.
 Formality: Algorithms can be informal and may not follow specific syntax rules, while
pseudocode uses a more structured format that aligns with programming language
constructs.
 Purpose: Algorithms are used to outline the general approach to solving a problem,
whereas pseudocode is used to detail the implementation of the algorithm in a way that
can be easily converted into actual code.

In summary, algorithms provide a broad overview of problem-solving steps, while pseudocode


offers a more detailed, readable way to express these steps in a format that can be translated into
code.

Q.9: Briefly identify the role of the personnel involved in SDLC.

Answer:

the roles of personnel involved in the Software Development Life Cycle (SDLC):

1. Project Sponsor: Provides financial resources and support, sets project goals, and makes
high-level decisions. They champion the project and ensure alignment with
organizational objectives.
2. Project Manager: Oversees the entire project, including planning, execution, and
delivery. Manages schedules, resources, and budgets, coordinates team efforts, and
ensures the project stays on track.
3. Business Analyst: Gathers and documents business requirements, analyzes user needs,
and translates these into technical requirements. Acts as a liaison between stakeholders
and the development team.
4. Development Team: Comprises developers and programmers who design, code, and
build the software according to the specifications and design documents.
5. Quality Assurance (QA) Team: Tests the software to identify defects and ensure it
meets requirements. They create and execute test plans and report issues to be fixed.
6. UI/UX Designers: Design the user interface and user experience of the software. They
create prototypes and ensure the software is user-friendly and visually appealing.
7. End Users: Use the software in real-world scenarios. Provide feedback on functionality
and usability, helping to validate that the software meets their needs.
8. System Administrators/IT Support: Manage the deployment, configuration, and
maintenance of the software. Provide technical support and address performance and
security issues.
9. Database Administrators (DBAs): Design, implement, and maintain databases. Ensure
data integrity, performance, and security.
10. Regulatory and Compliance Officers: Ensure the software complies with relevant laws,
regulations, and standards. Review processes and the final product for compliance.
11. Marketing and Sales Teams: Promote and sell the software. Provide input on market
requirements and support the software’s launch and distribution.
12. Training and Documentation Specialists: Create user manuals, help documentation,
and training materials. Assist in training end-users and provide ongoing support
resources.

Each role is crucial in ensuring that the software project is completed successfully, meeting the
desired objectives and delivering value to stakeholders.

Q.10: Design a flowchart for the following algorithm.

Algorithm:

sum = 0, N=10
x = 1
while x ≤ N do
sum = sum + x
x = x + 1
end while
print sum

Answer:

Flowchart Description:

1. Start
2. Initialize sum = 0 and x = 1
3. Decision: Is x ≤ N?
o If Yes: Continue to Step 4
o If No: Go to Step 6
4. Process: sum = sum + x
5. Process: x = x + 1 (Go back to Step 3)
6. Output: Print sum
7. End

This flowchart represents the given algorithm, where the loop continues until the value of x
exceeds N, at which point the sum is printed.
Chapter No.3 “Object Oriented Programming Using C++”

Exercise Solution

• Q.1 Fill in the Blanks

1. In C/C++ language, a hexadecimal number is represented by writing 0x


symbol.
2. ? : is the conditional operator used in C++.
3. Output of the logical and relational operators is true/false.
4. Assigning values to a variable during declaration time is called initialization.
5. Each C++ program has main() function from where the execution of the
program starts.

• Q.2 Select the correct choice for the following Multiple Choice Questions:
• i. What does the given expression evaluate to? E = 6 + 5 * 4 % 3
• a. 1
• b. 8 ✔️
• c. 11
• d. 9
• ii. (true && true) || false
• a. true ✔️
• b. false
• c. both a and b
• d. incorrect expression
• iii. Expression C = i++ causes
• a. Value of i assigned to C and then i incremented by 1 ✔️
• b. to be incremented by 1 and then value of i assigned to C
• c. Value of i assigned to C
• d. to be incremented by 1
• iv. Which of the following languages is a subset of C++ language?
• a. C language ✔️
• b. Java language
• c. VB language
• d. C# language
• v. In C++ language char ch='3' represents:
• a. A digit
• b. An integer constant
• c. A character constant ✔️
• d. A word

• Q.3 True/False
1. Definition for the C++ object cout is stored in the header file conio.h.
o False (The correct header is iostream.h)
2. In C++, a statement ends with : symbol.
o False (A statement ends with a ; semicolon.)
3. int 30sum is the correct declaration of the variable 30sum.
o False (Variable names cannot start with a number.)
4. In C++, the statement a = a + 40 is the same as a += 40.
o True
5. Size of short int data type is 4 bytes.
o False (Typically, short int is 2 bytes, but it can vary depending
on the system.

• Q.4 Evaluate the following:


• (false && true) || true
• True
• (false && true) || false || true
• True
• (6 > 7 || 5 > 4) && (7 > 8)
• False
• !(7 > 6) && (3 > 4)
• False

• Q.5 Invalid Variable Declarations:


 int my variable name; (Spaces are not allowed in variable names)
 int 3some; (Variable names cannot start with a number)
 int void = 5; (void is a reserved keyword in C++)
 int cats = 5, dogs = 5; (This one is actually valid)
 int meters_of_pipe; (This one is valid)
 int length, width = 5; (This one is valid)
Q.6 Write a C++ program to get 5 subjects marks of a student and then calculate its
total, average, and percentage and display them on the screen.

Solution:

Here's a simple C++ program that takes input for 5 subjects' marks, calculates the
total, average, and percentage, and displays them:
#include <iostream>
using namespace std;
int main() {
// Declare variables to hold the marks of 5 subjects
int marks1, marks2, marks3, marks4, marks5;
int totalMarks;
float average, percentage;
// Input marks for each subject
cout << "Enter marks for subject 1: ";
cin >> marks1;
cout << "Enter marks for subject 2: ";
cin >> marks2;
cout << "Enter marks for subject 3: ";
cin >> marks3;
cout << "Enter marks for subject 4: ";
cin >> marks4;
cout << "Enter marks for subject 5: ";
cin >> marks5;
// Calculate total marks
totalMarks = marks1 + marks2 + marks3 + marks4 + marks5;

// Calculate average
average = totalMarks / 5.0;
// Calculate percentage
percentage = (totalMarks / 500.0) * 100; // Assuming each subject is out of
100

// Display the results


cout << "Total Marks: " << totalMarks << endl;
cout << "Average Marks: " << average << endl;
cout << "Percentage: " << percentage << "%" << endl;
return 0;
}

Explanation:

1. Input Section:
o The program first asks the user to input marks for 5 subjects.
2. Calculation Section:
o It then calculates the total marks by summing up the marks of all
subjects.
o The average is calculated by dividing the total marks by 5.
The percentage is calculated assuming each subject is out of 100 marks,
o
so the total maximum marks would be 500.
3. Output Section:
o Finally, it displays the total marks, average, and percentage on the
screen.

Q.7 Write a C++ program to find out the maximum value out of four integers using the
conditional operator.

Solution:

Here's a C++ program that uses the conditional (ternary) operator to find the maximum value out
of four integers:

#include <iostream>
using namespace std;
int main() {
int a, b, c, d;
int max;
// Input four integers
cout << "Enter the first integer: ";
cin >> a;
cout << "Enter the second integer: ";
cin >> b;
cout << "Enter the third integer: ";
cin >> c;
cout << "Enter the fourth integer: ";
cin >> d;
// Find the maximum value using the conditional (ternary) operator
max = (a > b) ? ((a > c) ? ((a > d) ? a : d) : (c > d ? c : d))
: ((b > c) ? ((b > d) ? b : d) : (c > d ? c : d));
// Output the maximum value
cout << "The maximum value is: " << max << endl;
return 0;
}

Explanation:

1. Input Section:
o The program prompts the user to input four integers.
2. Calculation Section:
o The conditional (ternary) operator is used to compare the integers.
o The logic for finding the maximum is structured as follows:
 First, compare a and b.
 Then, compare the result of a or b with c.
 Finally, compare the result of that with d to determine the maximum.
3. Output Section:
o The program then prints the maximum value among the four integers.

Q.8 Write a C++ program to find out the roots of a quadratic equation.

Solution:

To find the roots of a quadratic equation, we can use the quadratic formula:

x=−b±b2−4ac2ax = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}x=2a−b±b2−4ac

where aaa, bbb, and ccc are coefficients of the quadratic equation ax2+bx+c=0ax^2 + bx + c =
0ax2+bx+c=0.

Here's a C++ program to find the roots of a quadratic equation:

#include <iostream>
#include <cmath> // For sqrt() function
using namespace std;

int main() {
double a, b, c;
double discriminant, root1, root2, realPart, imaginaryPart;

// Input coefficients a, b, and c


cout << "Enter coefficient a: ";
cin >> a;
cout << "Enter coefficient b: ";
cin >> b;
cout << "Enter coefficient c: ";
cin >> c;

// Calculate the discriminant


discriminant = b*b - 4*a*c;

// Check the nature of the roots


if (discriminant > 0) {
// Two distinct and real roots
root1 = (-b + sqrt(discriminant)) / (2*a);
root2 = (-b - sqrt(discriminant)) / (2*a);
cout << "Roots are real and different." << endl;
cout << "Root 1 = " << root1 << endl;
cout << "Root 2 = " << root2 << endl;
}
else if (discriminant == 0) {
// Two real and equal roots (repeated root)
root1 = -b / (2*a);
cout << "Roots are real and the same." << endl;
cout << "Root 1 = Root 2 = " << root1 << endl;
}
else {
// Complex roots
realPart = -b / (2*a);
imaginaryPart = sqrt(-discriminant) / (2*a);
cout << "Roots are complex and different." << endl;
cout << "Root 1 = " << realPart << " + " << imaginaryPart << "i" <<
endl;
cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" <<
endl;
}

return 0;
}

Explanation:

1. Input Section:
o The program prompts the user to input the coefficients aaa, bbb, and ccc of the
quadratic equation.
2. Calculation Section:
o The discriminant is calculated using the formula
discriminant=b2−4ac\text{discriminant} = b^2 - 4acdiscriminant=b2−4ac.
o Depending on the value of the discriminant:
 If it's positive, the equation has two distinct real roots.
 If it's zero, the equation has two equal real roots.
 If it's negative, the equation has two complex conjugate roots.
3. Output Section:
o The program outputs the roots of the quadratic equation depending on the nature
of the discriminant.

Q.9 Write a C++ program to find out the area of a rectangle and display the result on the
screen.

Solution:

Here's a simple C++ program to calculate the area of a rectangle and display the result on the
screen:

#include <iostream>
using namespace std;

int main() {
float length, width, area;

// Input the length and width of the rectangle


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

// Calculate the area of the rectangle


area = length * width;

// Display the result


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

return 0;
}

Explanation:

1. Input Section:
o The program prompts the user to input the length and width of the rectangle.
2. Calculation Section:
o The area is calculated using the formula area = length * width.
3. Output Section:
o The program displays the calculated area on the screen.

Q.10 Write a C++ program to get the age of a student from the user at runtime and display
it on the screen.

Solution:

Here’s a simple C++ program that prompts the user to input their age and then displays it:

#include <iostream>
using namespace std;

int main() {
int age;

// Input the age of the student


cout << "Enter your age: ";
cin >> age;

// Display the age


cout << "Your age is: " << age << " years old." << endl;

return 0;
}

Explanation:

1. Input Section:
o The program prompts the user to enter their age.
2. Output Section:
o The program then displays the entered age on the screen.
Chapter No.4 “Control Structure”

Exercise Solution

Q.1 Fill in the Blanks

I. An if statement can include multiple statements provided that they are enclosed
within a block.
II. The switch statement controls program flow by executing a specific set of statements,
depending on the value returned by an integer or character expression.
III. When the value returned by a switch statement expression does not match a case
label, the default statements within the label execute.
IV. You can exit a switch statement using a(n) break statement.
V. Each repetition of a looping statement is called a(n) iteration.

Q.2 Multiple Choice Questions

i. Find out the error in the following block of code:

if (x = 100)

cout << "x is 100";

 a. 100 should be enclosed in quotations


 b. There is no semicolon at the end of the first line
 c. Equals to operator mistake (Correct Answer)
 d. Variable x should not be inside quotation

Explanation: The condition x = 100 is an assignment operation, not a comparison. It should be x


== 100.

ii. Looping in a program means:

 a. Jumping to the specified branch of the program


 b. Repeat the specified lines of code (Correct Answer)
 c. Both a & b
 d. It is executed without any condition

Explanation: Looping is the process of repeating a block of code multiple times.

iii. Which of the following is not a looping statement in C++?

 a. while
 b. until (Correct Answer)
 c. do
 d. for

Explanation: until is not a valid looping statement in C++. The correct looping statements are
while, do, and for.

iv. Which of the following is not a conditional jump statement in C++?

 a. if
 b. goto
 c. for (Correct Answer)
 d. do-while

Explanation: The for loop is not a jump statement. The if, goto, and do-while statements involve
conditional jumps.

v. Which of the following is a selection statement in C++?

 a. break
 b. goto
 c. exit
 d. switch (Correct Answer)

Explanation: The switch statement is used for making selections based on the value of an
expression.

vi. The continue statement:

 a. resumes the program if it is hanged


 b. resumes the program if a break was applied
 c. skips the rest of the loop in the current iteration (Correct Answer)
 d. Both a & b

Explanation: The continue statement skips the rest of the loop's body in the current iteration and
moves on to the next iteration of the loop.

vii. Consider the following two pieces of code and choose the best answer:

1.

switch (x) {

case 1:

cout <<"x is 1";


break;

case 2:

cout <<"x is 2";

break;

default:

cout <<"value of x unknown";

2.

if (x == 1){

cout <<"x is 1";

else if (x == 2){

cout << "x is 2";

else {

cout <<"value of x unknown";

 a. Both of the above code fragments have the same behaviour (Correct Answer)
 b. Both of the above code fragments produce different effects
 c. The first code produces more results than the second
 d. The second code produces more results than the first

Explanation: Both the switch statement and the if-else ladder produce the same output based on
the value of x. They both check the value of x and execute the corresponding block of code.

viii. Observe the following block of code and determine what happens when x=2:

switch (x) {
case 1:

case 2:

case 3:

cout << "x is between 1.. 3";

break;

default:

cout << "x is not within the range, so need to say Thank You!";

 a. Program jumps to the end of the switch statement


 b. The code after default will run since there is no task for x=2
 c. Will display "x is between 1 ... 3" (Correct Answer)
 d. "x is not within the range, so need to say Thank You!"

Explanation: When x = 2, the control will fall through case 2. The code within this case will be
executed, which outputs "x is between 1.. 3", followed by a break statement, ending the switch
block.

ix. Which of the following is true for switch statement in C++?

 a. It uses labels instead of blocks


 b. We need to put a break statement at the end of each case (Correct Answer)
 c. We can put a range for case such as case 1..3
 d. switch statement is executed on the basis of a condition

Explanation: The switch statement in C++ uses labels (like case 1:) to match the value being
evaluated. To avoid "fall through" (where multiple cases are executed), a break statement is
typically used to exit the switch after a case block is executed.

Q.3 Write TRUE/FALSE against the following statements.

i. Decision-making structures cannot be nested. False

ii. Body of do while loop is executed at least once if the condition is false. True

iii. When for statement begins executing, at the same time the initialization expression is
also executed? True

iv. switch statement is a better alternative of nested if-else structure. True


v. Syntax of if-else statement is:

• else {
• }
• if (condition) {
• } False

Q.4 Write a C++ program that takes three numbers as input and displays whether all

numbers are equal or not by using nested if condition.

Solution:

C++ program that takes three numbers as input and checks whether all numbers are equal using
nested if conditions:

#include <iostream>
using namespace std;

int main() {
int num1, num2, num3;

// Taking input from the user


cout << "Enter three numbers: ";
cin >> num1 >> num2 >> num3;

// Checking if all numbers are equal using nested if condition


if (num1 == num2) {
if (num2 == num3) {
cout << "All numbers are equal." << endl;
} else {
cout << "The numbers are not equal." << endl;
}
} else {
cout << "The numbers are not equal." << endl;
}

return 0;
}

Explanation:

1. Input: The program first takes three integers (num1, num2, num3) as input from the user.
2. First if Statement: It checks if num1 is equal to num2. If true, it proceeds to the nested
if.
3. Nested if Statement: If num1 is equal to num2, the program then checks if num2 is also
equal to num3.
o If both conditions are true, all three numbers are equal, and the program prints
"All numbers are equal."
o If num2 is not equal to num3, it prints "The numbers are not equal."
4. Else: If the first if condition fails (i.e., num1 is not equal to num2), the program
immediately prints "The numbers are not equal."

Example:

 Input: 5 5 5
 Output: All numbers are equal.
 Input: 3 5 3
 Output: The numbers are not equal.

This program effectively uses nested if conditions to determine if all three input numbers are
equal.

Q.5 Write a program using **for** loop that prints product of all odd numbers from 1
to 10.

Solution:

C++ program that uses a for loop to calculate and print the product of all odd numbers from 1 to
10:

#include <iostream>
using namespace std;

int main() {
int product = 1;

// Loop through numbers from 1 to 10


for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) { // Check if the number is odd
product *= i; // Multiply product by the odd number
}
}

// Output the result


cout << "The product of all odd numbers from 1 to 10 is: " << product <<
endl;

return 0;
}
Explanation:

1. Initialization: The variable product is initialized to 1. This will hold the cumulative
product of the odd numbers.
2. For Loop: The loop iterates from 1 to 10:
o if (i % 2 != 0) checks whether the current number i is odd. The modulus
operator % returns the remainder when i is divided by 2. If the remainder is not 0,
then i is odd.
o If the number is odd, it is multiplied by the current value of product.
3. Output: After the loop ends, the program prints the final value of product, which is the
product of all odd numbers between 1 and 10.

Output:

The output of this program will be:

The product of all odd numbers from 1 to 10 is: 945

Q.6 Write a program using while loop that takes an integer for a variable nValue, and
returns the sum of all the numbers from 1 to nValue.
Hint: For example, nValue=5 should return 15, which is 1+2+3+4+5.

Solution:

C++ program that uses a while loop to calculate the sum of all numbers from 1 to nValue:

#include <iostream>

int main() {
int nValue, sum = 0, i = 1;

// Prompt user for input


std::cout << "Enter an integer: ";
std::cin >> nValue;

// Calculate sum using while loop


while (i <= nValue) {
sum += i;
i++;
}

// Output the result


std::cout << "The sum of all numbers from 1 to " << nValue << " is " <<
sum << std::endl;

return 0;
}
Explanation:

1. Initialization: We initialize sum to 0 and i to 1.


2. While Loop: The loop runs while i is less than or equal to nValue.
o Add to Sum: Each iteration adds i to sum.
o Increment: i is incremented by 1.
3. Output: After the loop completes, we print the sum.

You can compile and run this program. It will ask you for an integer, compute the sum of all
integers from 1 to that integer, and display the result.

Q.7 Write a program that displays the product components of a number without
repeating them. For example, if the user enters 24, it displays 24*1, 12*2, 8*3 and 6*4.

Solution:

C++ program that finds and displays the unique factor pairs of a given number. Here's how you
can do it:

#include <iostream>

int main() {
int number;

// Prompt user for input


std::cout << "Enter a number: ";
std::cin >> number;

std::cout << "The product components of " << number << " are:" <<
std::endl;

// Loop to find and display factor pairs


for (int i = 1; i <= number / 2; ++i) {
if (number % i == 0) {
int factor = number / i;
if (i < factor) { // Ensure each pair is only printed once
std::cout << i << "*" << factor << std::endl;
}
}
}

// Print the number itself as the last pair


std::cout << number << "*1" << std::endl;

return 0;
}
Explanation:

1. Initialization: We start by reading an integer from the user.


2. Loop: We loop from 1 to number / 2 to find all factors of the number.
o Check Factor: For each i, if i is a factor (number % i == 0), then number / i
is the corresponding factor.
o Print Pair: We print the pair (i, number / i) only if i is less than number / i
to avoid duplicate pairs like 24*1 and 1*24.
3. Print Final Pair: We also print the number itself paired with 1 to cover all factors.

This program ensures that each unique factor pair is displayed without repeating them.

Q.8 Write a C++ program to read the address of a person and exit when the user enters
dot (.) from the keyboard.

Solution:

C++ program that reads the address of a person and exits when the user enters a dot (.):

#include <iostream>
#include <string>

int main() {
std::string address;

std::cout << "Enter the address (enter '.' to exit):" << std::endl;

while (true) {
std::getline(std::cin, address);

if (address == ".") {
break; // Exit the loop if the user enters '.'
}

std::cout << "Address entered: " << address << std::endl;


}

std::cout << "Exiting program." << std::endl;

return 0;
}

Explanation:

1. Input: We use std::getline to read the entire line of input, which allows for multi-
word addresses.
2. Check for Exit: The program checks if the input is a single dot (.). If it is, the loop
breaks and the program exits.
3. Display Address: For any other input, the program prints the address entered.

You can run this program and enter addresses line by line. The program will continue to prompt
for input until you enter a dot (.) to terminate it.

Q.9 Write a C++ program to find out the area of a rectangle and if any side is zero then
display the message "There is no triangle".

Solution:

C++ program that calculates the area of a rectangle. If either the length or the width of the
rectangle is zero, it displays the message "There is no triangle" (assuming that was meant to be
"rectangle" instead of "triangle" based on the context):
#include <iostream>

int main() {
float length, width;

// Prompt user for length and width


std::cout << "Enter the length of the rectangle: ";
std::cin >> length;

std::cout << "Enter the width of the rectangle: ";


std::cin >> width;

// Check if either length or width is zero


if (length == 0 || width == 0) {
std::cout << "There is no rectangle." << std::endl;
} else {
// Calculate area
float area = length * width;
std::cout << "The area of the rectangle is: " << area << std::endl;
}

return 0;
}
Explanation:

1. Input: The program prompts the user to enter the length and width of the rectangle.
2. Check for Zero: It checks if either the length or the width is zero.
o If either value is zero, it prints "There is no rectangle."
3. Calculate and Display Area: If both length and width are non-zero, it calculates the area of the
rectangle and prints it.

You can compile and run this program, enter the dimensions of the rectangle, and it will display
the appropriate message or the calculated area based on the input values.
Q.10 Write a C++ program to input a character from the keyboard and display the
message after testing whether it is Vowel or Consonant.
Solution:

C++ program that inputs a character from the keyboard and determines whether it is a vowel or a
consonant:

#include <iostream>

int main() {
char ch;

// Prompt user for input


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

// Convert character to lowercase to simplify the comparison


ch = tolower(ch);

// Check if the character is a vowel or consonant


if (ch >= 'a' && ch <= 'z') { // Check if it's a letter
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
std::cout << ch << " is a Vowel." << std::endl;
} else {
std::cout << ch << " is a Consonant." << std::endl;
}
} else {
std::cout << ch << " is not an alphabetic character." << std::endl;
}

return 0;
}

Explanation:

1. Input: The program prompts the user to enter a single character.


2. Lowercase Conversion: It converts the character to lowercase using tolower for easier
comparison (optional, but useful for case-insensitivity).
3. Check Alphabet: It first checks if the character is within the range of alphabetic
characters ('a' to 'z').
o Vowel Check: If the character is one of 'a', 'e', 'i', 'o', or 'u', it is identified as a
vowel.
o Consonant Check: If it's not a vowel but still an alphabetic character, it is
identified as a consonant.
4. Non-Alphabet Check: If the character is not an alphabetic character, it notifies that the
input is not a valid alphabetic character.

You can compile and run this program, then enter any character to see whether it is a vowel,
consonant, or neither.
Chapter No.5 “Arrays and Strings”

Exercise Solution

Q.1 Fill in the Blanks:

i. In C/C++ language, normally the indexing of an array starts from 0.

ii. The size of the array int x[10] is 10.

iii. char century[100][365][24][60][60] is an example of a multidimensional array.

iv. An array of characters is called a string.

v. float x[12] defines a one-dimensional array of type float.

Q.2 Select the correct choice for the following Multiple Choice Questions:

i. A collection of data items of the same data type placed in contiguous memory locations is
called Array.

 a. Record
 b. Array (Correct Answer)
 c. Program
 d. File

ii. Observe the following statements and decide what they do.

string mystring;

getline(cin, mystring);

 a. reads a line of string from cin into mystring (Correct Answer)


 b. reads a line of string from mystring into cin
 c. cin can't be used this way
 d. getline is not a function

iii. Which of the header files must be included to use string stream?

 a. <iostream>
 b. <string>
 c. <sstring>
 d. <sstream> (Correct Answer)
iv. The location number of an item in an array is called Index.

 a. Data
 b. Value
 c. Index (Correct Answer)
 d. Constant

v. Strings are character arrays. The last index of it contains the null character \0.

 a. \n
 b. \t
 c. \0 (Correct Answer)
 d. \1

Q.3 Write TRUE/FALSE against the following statements:

I. Array is a collection of heterogeneous type of data.

 FALSE (Arrays are collections of data items of the same data type.)

II. Array can be initialized at declaration time.

 TRUE (Arrays can be initialized at the time of declaration.)

III. char vowel[5] declares an integer type array that holds the vowel characters of English
language.

 FALSE (The declaration char vowel[5] creates an array of char, not int. It can hold
characters, such as vowels.)

IV. Loop is the best tool for handling large arrays.

 TRUE (Loops are commonly used to process or manipulate large arrays efficiently.)

V. Array elements are stored in the memory wherever free space is available.

 FALSE (Array elements are stored in contiguous memory locations.)


Q.4 Declare an array to hold the high temperature (to the nearest tenth of a degree) for
each day of a year. Assign a value of 0 to each day.

Solution:

To declare an array to hold the high temperature for each day of a year and initialize each value
to 0, you can use the following code in C++:

Declaration and Initialization


#include <iostream>

int main() {
// Declare an array to hold temperatures for each day of a year
const int daysInYear = 365;
float temperatures[daysInYear] = {0}; // Initialize all values to 0

// Example output to verify initialization


std::cout << "Temperature for the first day: " << temperatures[0] <<
std::endl;

return 0;
}

Explanation

 const int daysInYear = 365;: Defines a constant for the number of days in a year.
 float temperatures[daysInYear] = {0};: Declares an array of float to hold the
temperatures. All elements are initialized to 0 using the brace-enclosed initializer list.

In this example, the array temperatures will hold the high temperature for each day of the year,
initialized to 0.

Q.5 Write down a C++ program to find the number of elements in array using sizeof()
operator.

Solution:

To find the number of elements in an array using the sizeof() operator in C++, you can use the
following approach. The sizeof() operator returns the size of the array in bytes, and by
dividing this by the size of a single element, you get the number of elements in the array.

Here's a C++ program that demonstrates this:

#include <iostream>

int main() {
// Declare and initialize an array
int arr[] = {10, 20, 30, 40, 50};

// Calculate the number of elements in the array


size_t arraySize = sizeof(arr) / sizeof(arr[0]);

// Output the number of elements


std::cout << "The number of elements in the array is: " << arraySize <<
std::endl;

return 0;
}

Explanation

1. sizeof(arr): Returns the total size of the array arr in bytes.


2. sizeof(arr[0]): Returns the size of one element of the array (in this case, an int).
3. sizeof(arr) / sizeof(arr[0]): Divides the total size of the array by the size of one
element to get the number of elements in the array.

This program will output:

The number of elements in the array is: 5

This approach ensures that you can correctly find the number of elements in the array regardless
of the type or size of the array.

Q.6 Write down a C++ program to find the multiplication of two matrices A[3][2] and
B[2][3].

Solution:

To multiply two matrices in C++, you need to follow these steps:

1. Define the matrices: Matrix A with dimensions 3x2 and Matrix B with dimensions 2x3.
2. Perform matrix multiplication: The result will be a matrix C with dimensions 3x3.
3. Print the resulting matrix.

Here’s a complete C++ program to perform the multiplication of matrices A and B:

#include <iostream>

int main() {
// Define matrices A and B
const int rowsA = 3, colsA = 2;
const int rowsB = 2, colsB = 3;

int A[rowsA][colsA] = { {1, 2},


{3, 4},
{5, 6} };

int B[rowsB][colsB] = { {7, 8, 9},


{10, 11, 12} };

// Matrix C will be the result of A * B


int C[rowsA][colsB] = {0};

// Perform matrix multiplication


for (int i = 0; i < rowsA; ++i) {
for (int j = 0; j < colsB; ++j) {
C[i][j] = 0; // Initialize element
for (int k = 0; k < colsA; ++k) {
C[i][j] += A[i][k] * B[k][j];
}
}
}

// Print the resulting matrix C


std::cout << "Matrix C (result of A * B):\n";
for (int i = 0; i < rowsA; ++i) {
for (int j = 0; j < colsB; ++j) {
std::cout << C[i][j] << " ";
}
std::cout << std::endl;
}

return 0;
}

Explanation

1. Matrix Definitions:
o Matrix A: A 3x2 matrix.
o Matrix B: A 2x3 matrix.
2. Matrix Multiplication:
o The result matrix C will have dimensions 3x3.
o C[i][j] is computed as the sum of the products of the corresponding elements
from the i-th row of A and the j-th column of B.
3. Output:
o The resulting matrix C is printed in a 3x3 format.

This program multiplies the two matrices and displays the resulting matrix.
Q.7 Write a C++ program to copying string using strcpy() function.

Solution:

C++ program that demonstrates how to copy a string using the strcpy() function from the C
Standard Library:

#include <iostream>
#include <cstring> // Required for strcpy()

int main() {
// Define the source string
char source[] = "Hello, World!";

// Declare a destination array with enough space


char destination[50]; // Ensure it is large enough to hold the source
string

// Copy the source string to the destination string using strcpy()


strcpy(destination, source);

// Output the copied string


std::cout << "Source String: " << source << std::endl;
std::cout << "Destination String: " << destination << std::endl;

return 0;
}

Explanation

1. Include <cstring>: This header file is required for the strcpy() function.
2. Define the Source String:
o char source[] = "Hello, World!"; initializes the source string.
3. Declare the Destination Array:
o char destination[50]; is the array where the string will be copied. Ensure this
array is large enough to accommodate the source string and the null terminator.
4. Copy the String:
o strcpy(destination, source); copies the contents of source to
destination.
5. Print the Strings:
o Output both the source and destination strings to verify that the copy was
successful.

This program will output:

Source String: Hello, World!


Destination String: Hello, World!
Note

 Ensure the destination array is large enough to hold the source string, including the null
terminator. If the destination array is too small, it can lead to buffer overflow and
undefined behavior.

Q.8 Write down a C++ program to find the subtraction and addition of two matrices
A[3][3] and B[3][3].

Solution:

C++ program that performs both addition and subtraction of two 3x3 matrices:

#include <iostream>

int main() {
// Define matrices A and B
const int size = 3;
int A[size][size] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };

int B[size][size] = { {9, 8, 7},


{6, 5, 4},
{3, 2, 1} };

// Matrices to hold the results of addition and subtraction


int sum[size][size];
int difference[size][size];

// Calculate the sum and difference of matrices A and B


for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
sum[i][j] = A[i][j] + B[i][j];
difference[i][j] = A[i][j] - B[i][j];
}
}

// Print the resulting matrices


std::cout << "Matrix A:\n";
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
std::cout << A[i][j] << " ";
}
std::cout << std::endl;
}

std::cout << "\nMatrix B:\n";


for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
std::cout << B[i][j] << " ";
}
std::cout << std::endl;
}

std::cout << "\nSum of A and B:\n";


for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
std::cout << sum[i][j] << " ";
}
std::cout << std::endl;
}

std::cout << "\nDifference of A and B:\n";


for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
std::cout << difference[i][j] << " ";
}
std::cout << std::endl;
}

return 0;
}

Explanation

1. Define the Matrices:


o Matrix A and Matrix B are both defined as 3x3 matrices with sample values.
2. Declare Result Matrices:
o Matrix sum to store the result of matrix addition.
o Matrix difference to store the result of matrix subtraction.
3. Compute Sum and Difference:
o Iterate through each element of matrices A and B to compute the sum and
difference.
4. Print Results:
o Print matrices A and B.
o Print the sum and difference matrices.

Output

The program will print:

Matrix A:
1 2 3
4 5 6
7 8 9

Matrix B:
9 8 7
6 5 4
3 2 1

Sum of A and B:
10 10 10
10 10 10
10 10 10

Difference of A and B:
-8 -6 -4
-2 0 2
4 6 8

This program performs matrix addition and subtraction and displays the results clearly.

Q.9 Write a C++ program to find the transpose of a matrix A[3][3].

Solution:

To find the transpose of a matrix, you essentially swap its rows and columns. For a given matrix
A[3][3], its transpose will be a matrix B[3][3] where element B[i][j] is equal to A[j][i].

Here’s a C++ program that calculates the transpose of a 3x3 matrix:

#include <iostream>

int main() {
// Define the original matrix A
const int size = 3;
int A[size][size] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };

// Define the matrix B to store the transpose


int B[size][size];

// Compute the transpose of matrix A


for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
B[j][i] = A[i][j];
}
}

// Print the original matrix A


std::cout << "Matrix A:\n";
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
std::cout << A[i][j] << " ";
}
std::cout << std::endl;
}

// Print the transposed matrix B


std::cout << "\nTranspose of Matrix A:\n";
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
std::cout << B[i][j] << " ";
}
std::cout << std::endl;
}

return 0;
}

Explanation

1. Define the Original Matrix A:


o Matrix A is a 3x3 matrix initialized with sample values.
2. Define the Matrix B:
o Matrix B will store the transpose of A.
3. Compute the Transpose:
o For each element A[i][j], assign it to B[j][i]. This effectively swaps rows and
columns.
4. Print Results:
o Print matrix A and its transpose matrix B.

Output

The program will output:

Matrix A:
1 2 3
4 5 6
7 8 9

Transpose of Matrix A:
1 4 7
2 5 8
3 6 9

This program correctly calculates and displays the transpose of a 3x3 matrix.

Q.10 Write a C++ program to read the temperature of the whole week in an array and
then find the hottest day of the week.

Solution:

To find the hottest day of the week based on temperature readings stored in an array, you need
to:

1. Read the temperature values for each day of the week.


2. Find the maximum temperature in the array.
3. Determine the index (day) of the hottest temperature.

Here’s a C++ program to accomplish this:

#include <iostream>

int main() {
const int daysInWeek = 7;
float temperatures[daysInWeek];
float maxTemperature = -9999.0; // Initialize to a very low value
int hottestDayIndex = 0;

// Read the temperature for each day of the week


std::cout << "Enter the temperatures for the week (7 days):\n";
for (int i = 0; i < daysInWeek; ++i) {
std::cout << "Day " << (i + 1) << ": ";
std::cin >> temperatures[i];
}

// Find the hottest day


for (int i = 0; i < daysInWeek; ++i) {
if (temperatures[i] > maxTemperature) {
maxTemperature = temperatures[i];
hottestDayIndex = i;
}
}

// Print the result


std::cout << "The hottest day of the week is Day " << (hottestDayIndex +
1) << " with a temperature of " << maxTemperature << " degrees." <<
std::endl;

return 0;
}

Explanation

1. Define the Array:


o temperatures[7] to store temperatures for 7 days of the week.
2. Initialize Variables:
o maxTemperature to a very low value so that any real temperature will be higher.
o hottestDayIndex to store the index of the hottest day.
3. Read Temperatures:
o Use a loop to read temperatures for each day from user input.
4. Find the Hottest Day:
o Iterate through the array to find the maximum temperature and its index.
5. Print Results:
o Output the day with the highest temperature and the temperature itself.
Sample Output

If the user inputs temperatures like 23.5, 25.0, 22.1, 30.0, 28.5, 26.7, 24.3, the
program will output:

The hottest day of the week is Day 4 with a temperature of 30 degrees.

This program efficiently finds and reports the hottest day based on the provided temperatures.

Q.11 Write a C++ program to read ten alphabets of English from the keyboard into a
character type array and then sort them in descending order.

Solution:

To read ten alphabets from the keyboard, store them in a character array, and then sort them in
descending order, you can use the following C++ program:

#include <iostream>
#include <algorithm> // For std::sort

int main() {
const int numOfAlphabets = 10;
char alphabets[numOfAlphabets];

// Read 10 alphabets from the keyboard


std::cout << "Enter 10 alphabets:\n";
for (int i = 0; i < numOfAlphabets; ++i) {
std::cin >> alphabets[i];
}

// Sort the array in descending order


std::sort(alphabets, alphabets + numOfAlphabets, [](char a, char b) {
return a > b; // Sorting in descending order
});

// Print the sorted array


std::cout << "\nAlphabets in descending order:\n";
for (int i = 0; i < numOfAlphabets; ++i) {
std::cout << alphabets[i] << " ";
}
std::cout << std::endl;

return 0;
}

Explanation

1. Include Headers:
o <algorithm> for the std::sort function.
2. Define the Array:
o char alphabets[numOfAlphabets] to store 10 characters.
3. Read Characters:
o Use a loop to read 10 characters from the keyboard.
4. Sort in Descending Order:
o Use std::sort with a lambda function to sort the characters in descending order.
The lambda function [](char a, char b) { return a > b; } compares
characters and ensures sorting in descending order.
5. Print the Sorted Array:
o Output the sorted characters.

Sample Output

If the user inputs the characters b, e, a, z, k, n, d, r, c, f, the program will output:

Alphabets in descending order:


z r k n f e d c b a

This program efficiently sorts and displays the alphabets in descending order based on user
input.

Q.12 Write a C++ program to find sum of the values of a two dimensional array int
Test[2][3] and display the result on the screen.

Solution:

To find the sum of all values in a 2D array int Test[2][3] and display the result, you can use
the following C++ program:

#include <iostream>

int main() {
// Define a 2D array with 2 rows and 3 columns
const int rows = 2;
const int cols = 3;
int Test[rows][cols] = { {1, 2, 3},
{4, 5, 6} };

int sum = 0; // Variable to hold the sum of the array elements

// Calculate the sum of the array elements


for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
sum += Test[i][j];
}
}

// Display the result


std::cout << "The sum of the values in the array is: " << sum <<
std::endl;

return 0;
}

Explanation

1. Define the Array:


o int Test[2][3] initializes a 2D array with 2 rows and 3 columns with sample
values.
2. Initialize the Sum Variable:
o int sum = 0; initializes the sum to zero.
3. Calculate the Sum:
o Use nested loops to iterate through each element of the 2D array.
o Add each element to the sum variable.
4. Display the Result:
o Print the total sum of all elements in the array.

Sample Output

Given the array Test with values { {1, 2, 3}, {4, 5, 6} }, the program will output:

The sum of the values in the array is: 21

This program calculates and displays the sum of all the values in the 2D array.
Q.13 Write a brief note on the following:

a. One dimensional array

c. Concatenation of string

b. Two dimensional array

d. Strings

Solution:

a. One-Dimensional Array

Definition: A one-dimensional array, also known as a single-dimensional array, is a data


structure that stores a collection of elements of the same type in a contiguous memory location.
The array elements are accessed using a single index.

Example:

int arr[5] = {10, 20, 30, 40, 50};

Key Points:

 Declaration: type name[size];


 Indexing: Starts from 0 up to size-1.
 Access: Elements are accessed using arr[index].
 Usage: Ideal for storing a list of items where only one dimension is required, such as a
list of scores or temperatures.

Advantages:

 Simple and efficient for sequential data storage.


 Easy to access elements with direct indexing.

Disadvantages:

 Fixed size: The size of the array must be known at compile time and cannot be changed
dynamically.

b. Two-Dimensional Array

Definition: A two-dimensional array is an array of arrays, where each element is itself an array.
It can be visualized as a matrix with rows and columns.
Example:

int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

Key Points:

 Declaration: type name[rows][columns];


 Indexing: Uses two indices: matrix[row][column].
 Access: Elements are accessed using both row and column indices.
 Usage: Useful for representing tabular data, such as spreadsheets or game boards.

Advantages:

 Suitable for modeling data with two dimensions, like grids or tables.
 Allows for more complex data organization.

Disadvantages:

 Larger memory footprint compared to one-dimensional arrays.


 Fixed size: Rows and columns must be defined at compile time.

c. Concatenation of String

Definition: Concatenation of strings refers to the process of joining two or more strings end-to-
end to form a single string.

Example:

#include <iostream>
#include <string>

int main() {
std::string str1 = "Hello, ";
std::string str2 = "World!";
std::string result = str1 + str2; // Concatenation

std::cout << result << std::endl; // Output: Hello, World!


return 0;
}

Key Points:

 Operator: The + operator is used to concatenate strings in C++.


 Function: The append() function can also be used for concatenation.

Advantages:

 Allows for flexible string manipulation.


 Supports dynamic string creation and modification.

d. Strings

Definition: In C++, a string is a sequence of characters terminated by a null character (\0). The
std::string class in the Standard Library provides a more flexible and powerful way to work
with strings compared to C-style strings (character arrays).

Example:

#include <iostream>
#include <string>

int main() {
std::string str = "Hello, World!";
std::cout << str << std::endl;
return 0;
}

Key Points:

 Declaration: std::string str; or std::string str = "text";


 Operations: Supports various operations like concatenation, comparison, and substring
extraction.
 Functions: Provides member functions like length(), substr(), and find().

Advantages:

 Dynamic size: Can grow or shrink as needed.


 Rich set of functions for manipulation and querying.
Chapter No.6 “Functions”

Exercise Solution

Q.No.1: Fill in the Blanks.

i. Normally a function can return one value.


ii. The only difference between the function declarator and function prototype is the use
of semicolon (;).
iii. The scope of global variable declared in a C++ program is throughout the entire
program.
iv. Using function overloading, we can declare multiple functions with the same name,
having slightly different purpose.
v. If a function needs to return a value to the calling function, then its return type should
not use the keyword void.

Q.No.2: Select the correct choice for the following Multiple Choice Questions.

• i. The phenomenon of having two or more functions in a program with the same
names but different number and types of parameters is known as:
a. Inline Function
b. Nested Function
c. Function overloading
d. Recursive Function
Correct answer: c. Function overloading
• ii. We declare a function with ______ if it does not have any return type.
a. long
b. double
c. void
d. int
Correct answer: c. void
• iii. Arguments of a function are separated with ________________.
a. Comma (,)
b. Semicolon (;)
c. Colon (:)
d. Hyphen (-)
Correct answer: a. Comma (,)
• iv. Variables inside parentheses of function declarations have ____ level access.
a. Local
b. Global
c. Module
d. Universal
Correct answer: a. Local
• v. Observe the following function declaration and choose the best answer:
int divide (int a, int b = 2)
a. Variable b is of integer type and will always have value 2
b. Variable a and b are of int type and the initial value of both variables is 2
c. Variable b is of international scope and will have value 2
d. Variable b will have value 2 if not specified when calling the function
Correct answer: d. Variable b will have value 2 if not specified when calling
the function

Q.No.4: Write a program with a function that takes two int parameters, adds them together, and then
returns the sum.

Solution:

C++ program with a function that takes two int parameters, adds them, and returns the sum:

#include <iostream>
using namespace std;

// Function to add two integers and return the sum


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

int main() {
int num1, num2, sum;

// Input two numbers from the user


cout << "Enter the first number: ";
cin >> num1;

cout << "Enter the second number: ";


cin >> num2;

// Call the function to add the numbers


sum = addNumbers(num1, num2);

// Output the result


cout << "The sum is: " << sum << endl;

return 0;
}
Explanation:

 Function addNumbers(int a, int b): This function takes two integers as parameters,
adds them together, and returns the sum.
 In the main function, the user is prompted to enter two numbers. These numbers are
passed to the addNumbers function, and the result (sum) is printed.

Sample Output:
Enter the first number: 5
Enter the second number: 7
The sum is: 12
Q.No.5: Write a program with a function name "mean" to read in three integers from the keyboard to
find the arithmetic mean.

Solution:

C++ program that uses a function named mean to read three integers from the keyboard and
calculates the arithmetic mean:

#include <iostream>
using namespace std;

// Function to calculate the arithmetic mean of three integers


float mean(int a, int b, int c) {
return (a + b + c) / 3.0; // Return the mean as a float
}

int main() {
int num1, num2, num3;
float result;

// Input three integers from the user


cout << "Enter the first number: ";
cin >> num1;

cout << "Enter the second number: ";


cin >> num2;

cout << "Enter the third number: ";


cin >> num3;

// Call the mean function to calculate the arithmetic mean


result = mean(num1, num2, num3);

// Output the result


cout << "The arithmetic mean is: " << result << endl;

return 0;
}
Explanation:

 Function mean(int a, int b, int c): This function takes three integers as input,
adds them, and returns the arithmetic mean by dividing the sum by 3.0 (to ensure the
result is a floating-point value).
 In the main function, the user is prompted to enter three integers, which are then passed
to the mean function. The result is printed to the screen.

Sample Output:
Enter the first number: 4
Enter the second number: 6
Enter the third number: 8
The arithmetic mean is: 6
Q.No.6: Write a C++ program having a function name rectangle to read the length and width of a
rectangle from the keyboard and find the area of the rectangle. The result should be returned to the
main program for displaying on the screen.

Solution:

C++ program that includes a function named rectangle to read the length and width of a
rectangle, calculates the area, and returns the result to the main program for display:
#include <iostream>
using namespace std;

// Function to calculate the area of a rectangle


float rectangle(float length, float width) {
return length * width; // Return the area
}

int main() {
float length, width, area;

// 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;

// Call the rectangle function to calculate the area


area = rectangle(length, width);

// Output the result


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

return 0;
}
Explanation:

 Function rectangle(float length, float width): This function takes the length and
width as parameters, calculates the area by multiplying them, and returns the result.
 In the main function, the user is prompted to enter the length and width of the rectangle. These
values are then passed to the rectangle function, and the calculated area is printed to the
screen.

Sample Output:
Enter the length of the rectangle: 5.5
Enter the width of the rectangle: 3.2
The area of the rectangle is: 17.6
Q.No.7: Write a C++ program having two function names area and perimeter to find the area and
perimeter of a square.

Solution:

C++ program that includes two functions, area and perimeter, to calculate the area and
perimeter of a square:

#include <iostream>
using namespace std;

// Function to calculate the area of a square


float area(float side) {
return side * side; // Area = side^2
}

// Function to calculate the perimeter of a square


float perimeter(float side) {
return 4 * side; // Perimeter = 4 * side
}

int main() {
float side;

// Input the side length from the user


cout << "Enter the side length of the square: ";
cin >> side;

// Call the functions to calculate area and perimeter


float squareArea = area(side);
float squarePerimeter = perimeter(side);

// Output the results


cout << "The area of the square is: " << squareArea << endl;
cout << "The perimeter of the square is: " << squarePerimeter << endl;

return 0;
}

Explanation:

 Function area(float side): This function takes the length of a side of the square as a
parameter and calculates the area using the formula Area=side2\text{Area} =
\text{side}^2Area=side2.
 Function perimeter(float side): This function calculates the perimeter of the square
using the formula Perimeter=4×side\text{Perimeter} = 4 \times
\text{side}Perimeter=4×side.
 In the main function, the user is prompted to enter the side length of the square. The side
length is passed to both the area and perimeter functions, and the results are printed to
the screen.

Sample Output:
Enter the side length of the square: 4
The area of the square is: 16
The perimeter of the square is: 16

Q.No.8: Write a C++ program to read a number from the keyboard and then pass it to a
function to determine whether it is prime or composite.

Solution:

C++ program that reads a number from the keyboard and passes it to a function to determine
whether the number is prime or composite:

#include <iostream>
using namespace std;

// Function to check if a number is prime or composite


void checkPrimeComposite(int number) {
if (number <= 1) {
cout << number << " is neither prime nor composite." << endl;
return;
}

bool isPrime = true; // Flag to indicate if the number is prime

// Check for factors from 2 to the square root of the number


for (int i = 2; i * i <= number; i++) {
if (number % i == 0) {
isPrime = false; // Found a factor, not prime
break;
}
}

if (isPrime) {
cout << number << " is a prime number." << endl;
} else {
cout << number << " is a composite number." << endl;
}
}

int main() {
int number;

// Input a number from the user


cout << "Enter a number: ";
cin >> number;

// Call the function to check if the number is prime or composite


checkPrimeComposite(number);

return 0;
}
Explanation:

 Function checkPrimeComposite(int number): This function takes an integer as input


and determines whether it is a prime or composite number:
o If the number is less than or equal to 1, it is neither prime nor composite.
o The function checks for factors from 2 up to the square root of the number. If it
finds any factors, the number is composite; otherwise, it is prime.
 In the main function, the user is prompted to enter a number, which is then passed to the
checkPrimeComposite function. The result is printed to the screen.

Sample Output:
Enter a number: 11
11 is a prime number.

Enter a number: 10
10 is a composite number.

Enter a number: 1
1 is neither prime nor composite.

Q.No.9: Write a C++ program to get an integer number from keyboard in main
program and pass it as an argument to a function where it calculate and display
the table.
Solution:

C++ program that takes an integer number from the keyboard in the main program and passes it
as an argument to a function that calculates and displays its multiplication table:

#include <iostream>
using namespace std;

// Function to display the multiplication table of a number


void displayTable(int number) {
cout << "Multiplication Table for " << number << ":" << endl;
for (int i = 1; i <= 10; i++) {
cout << number << " x " << i << " = " << number * i << endl;
}
}

int main() {
int number;

// Input an integer number from the user


cout << "Enter an integer number: ";
cin >> number;

// Call the function to display the multiplication table


displayTable(number);

return 0;
}

Explanation:

 Function displayTable(int number): This function takes an integer as input and


displays its multiplication table from 1 to 10.
 In the main function, the user is prompted to enter an integer number. This number is
passed to the displayTable function, which prints the multiplication table.

Sample Output:
Enter an integer number: 5
Multiplication Table for 5:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Q.No10: Define function along with the advantages.


Solution:

Definition of a Function

In C++, a function is a block of code designed to perform a specific task. It can take inputs
(known as arguments or parameters), perform operations, and optionally return a value.
Functions help in organizing code, making it modular and reusable.

Syntax of a Function in C++

return_type function_name(parameter_list) {
// body of the function
// ... code to perform the task ...
return value; // Optional
}

Example of a Function
#include <iostream>
using namespace std;
// Function to add two numbers
int add(int a, int b) {
return a + b; // Returns the sum of a and b
}

int main() {
int num1 = 5, num2 = 10;
int sum = add(num1, num2); // Function call
cout << "Sum: " << sum << endl; // Output: Sum: 15
return 0;
}

Advantages of Functions

1. Modularity: Functions break down complex problems into smaller, manageable tasks.
Each function can be developed and tested independently.
2. Code Reusability: Once a function is defined, it can be called multiple times in the
program. This reduces redundancy and saves development time.
3. Ease of Maintenance: Changes to the code can be made in one place (the function),
rather than in every location where the code appears, making it easier to manage and
update.
4. Improved Readability: Functions allow for better organization of code. Descriptive
function names can clarify what specific blocks of code do, enhancing readability.
5. Encapsulation: Functions can encapsulate specific tasks and hide implementation
details. This allows users to interact with the function without needing to understand its
internal workings.
6. Parameterization: Functions can accept parameters, allowing the same function to
perform tasks with different inputs, which adds flexibility.
7. Facilitation of Debugging: Isolating code in functions makes it easier to debug and
identify issues since you can test individual functions independently of the entire
program.
8. Supports Recursion: Functions can call themselves, allowing for recursive solutions to
problems that can be broken down into smaller sub-problems.

Q.No.11: How function prototype and declarator differ from each other? Explain
with the help of examples.
Solution:

In C++, function prototypes and function declarators are closely related concepts, but they
serve different purposes. Here’s a breakdown of their differences along with examples.

Function Prototype
A function prototype is a declaration of a function that specifies its name, return type, and
parameters, but does not provide the body of the function. It informs the compiler about the
function's signature before the function is actually defined, allowing the function to be called
before its actual definition appears in the code.

Syntax of a Function Prototype

return_type function_name(parameter_list);

Example of Function Prototype

#include <iostream>
using namespace std;

// Function prototype
int add(int a, int b); // Declaration of the function

int main() {
int sum = add(5, 10); // Function call
cout << "Sum: " << sum << endl;
return 0;
}

// Function definition
int add(int a, int b) {
return a + b; // Returns the sum of a and b
}

Function Declarator

A function declarator includes the function's name and its parameters, but it is typically part of
the function definition. It specifies the function signature, but it is used within the context of
defining the function body.

Syntax of a Function Declarator

return_type function_name(parameter_list) {
// function body
}

Example of Function Declarator

#include <iostream>
using namespace std;

// Function definition with a declarator


int multiply(int x, int y) { // Declarator
return x * y; // Returns the product of x and y
}

int main() {
int product = multiply(4, 5); // Function call
cout << "Product: " << product << endl;
return 0;
}

Key Differences

Aspect Function Prototype Function Declarator


Declares the function and its
Purpose Part of the function definition
signature
Only provides the function's name Includes the body of the
Definition
and parameters function
int add(int a, int b) {
Example int add(int a, int b);
... }
Can be used before the Yes, allows for early calls to the No, must be part of the
function definition function function definition
Contains Body No Yes

Q.No.12: Define default arguments. Describe the advantages and disadvantages


of default arguments.
Solution:

Definition of Default Arguments

In C++, default arguments are predefined values that are automatically assigned to function
parameters if no argument is provided during the function call. This feature allows for more
flexible function calls, enabling users to omit some arguments while still providing a complete
and valid function invocation.

Syntax

When defining a function, you can specify default values for parameters as follows:

return_type function_name(parameter1_type parameter1 = default_value1,


parameter2_type parameter2 = default_value2) {
// function body
}

Example of Default Arguments


#include <iostream>
using namespace std;

// Function with default arguments


void displayInfo(string name, int age = 18, string city = "Unknown") {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "City: " << city << endl;
}

int main() {
// Calling the function with all arguments
displayInfo("Alice", 25, "New York");

// Calling the function with one default argument


displayInfo("Bob", 30);

// Calling the function with all default arguments


displayInfo("Charlie");

return 0;
}

Output
Name: Alice
Age: 25
City: New York
Name: Bob
Age: 30
City: Unknown
Name: Charlie
Age: 18
City: Unknown

Advantages of Default Arguments

1. Increased Flexibility: Default arguments allow users to call functions with fewer
parameters, making the function more versatile and adaptable to different situations.
2. Reduced Code Duplication: Functions with default arguments can reduce the need for
multiple overloaded functions, thereby minimizing redundancy in the code.
3. Simplified Function Calls: Users can call functions with varying numbers of arguments
without having to specify every parameter, making code easier to read and write.
4. Improved Maintainability: Default arguments can simplify maintenance since there are
fewer overloaded versions to manage, and changes can be made in one place.
5. Enhanced Usability: They make functions easier to use, especially for those who may
not require the full set of parameters.

Disadvantages of Default Arguments

1. Ambiguity: If not used carefully, default arguments can lead to ambiguity in function
calls, especially if multiple functions with similar signatures exist. The compiler may not
be able to determine which function to call.
2. Overloading Limitations: Default arguments can limit function overloading options
because the compiler cannot differentiate between functions that only differ by the
presence of default arguments.
3. Readability Issues: When a function has multiple parameters with default values, it may
be unclear which arguments are being passed unless the function calls are well-
documented.
4. Inflexible Parameter Order: Default arguments must be specified from right to left,
meaning that once a default argument is set, all arguments to the right must also have
defaults. This can limit how you design your functions.
5. Potential for Misuse: Users might rely too heavily on defaults and fail to provide
important parameters, leading to unintended behavior or logic errors in the program.

Q.No.13: What is meant by the term function overloading? How a function can
be overloaded in C++? Describe it with the help of an example program.
Solution:
Definition of Function Overloading
Function overloading is a feature in C++ that allows multiple functions to have the same name
but differ in their parameter lists. This means that you can define several versions of a function
that perform similar tasks but take different types or numbers of arguments. The compiler
determines which function to call based on the arguments passed during the function call.
How Function Overloading Works
Function overloading works by distinguishing functions based on:

1. Number of parameters: Functions with the same name but different numbers of parameters.
2. Data types of parameters: Functions with the same name but different types of parameters.
3. Order of parameters: Functions with the same name but different orders of parameter types.

Example Program for Function Overloading


Here's a C++ program that demonstrates function overloading by defining multiple versions of a
function named add:
#include <iostream>
using namespace std;

// Function to add two integers


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

// Function to add three integers


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

// Function to add two double values


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

int main() {
int intSum1 = add(5, 10); // Calls the first add function
int intSum2 = add(5, 10, 15); // Calls the second add function
double doubleSum = add(5.5, 10.5); // Calls the third add function

cout << "Sum of two integers: " << intSum1 << endl; // Output: 15
cout << "Sum of three integers: " << intSum2 << endl; // Output: 30
cout << "Sum of two doubles: " << doubleSum << endl; // Output: 16

return 0;
}
Explanation of the Example

1. Function Definitions:
o The first add function takes two integer parameters and returns their sum.
o The second add function takes three integer parameters and returns their sum.
o The third add function takes two double parameters and returns their sum.
2. Function Calls:
o The add function is called with two integers, invoking the first version.
o The add function is called with three integers, invoking the second version.
o The add function is called with two doubles, invoking the third version.
3. Output:
o The program outputs the results of each function call.

Sample Output

Sum of two integers: 15


Sum of three integers: 30
Sum of two doubles: 16
Advantages of Function Overloading

 Improved Code Readability: Having the same function name for similar operations makes the
code easier to read and understand.
 Reduced Code Redundancy: You can use the same function name for different operations
without creating multiple names.
 Flexibility: Allows functions to handle different types of inputs and use the same operation
without confusion.

Q.No.14: Describe the role of the following in function overloading:


- Data types of arguments
- Number of arguments
- Order of arguments
Solution:
Function overloading in C++ allows multiple functions to share the same name, provided they
differ in their signatures. The signature of a function includes its name and the types and order of
its parameters (but not the return type). Here’s how the following aspects play a role in function
overloading:

1. Data Types of Arguments

The data types of the arguments are crucial for distinguishing between overloaded functions.
You can have multiple functions with the same name but with different data types for their
parameters. This allows the same operation to be performed on different types of data.

Example

#include <iostream>
using namespace std;

// Function to add two integers


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

// Function to add two floating-point numbers


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

int main() {
int intResult = add(5, 10); // Calls the integer version
double doubleResult = add(5.5, 10.5); // Calls the double version

cout << "Integer sum: " << intResult << endl; // Output: 15
cout << "Double sum: " << doubleResult << endl; // Output: 16

return 0;
}

2. Number of Arguments

The number of arguments is another way to differentiate between overloaded functions. You can
have functions with the same name but different numbers of parameters. This is particularly
useful for functions that perform similar tasks but might require different levels of detail.

Example

#include <iostream>
using namespace std;

// Function to add two integers


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

// Function to add three integers


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

int main() {
int sumTwo = add(5, 10); // Calls the version with 2 parameters
int sumThree = add(5, 10, 15); // Calls the version with 3 parameters

cout << "Sum of two integers: " << sumTwo << endl; // Output: 15
cout << "Sum of three integers: " << sumThree << endl; // Output: 30

return 0;
}

3. Order of Arguments

The order of arguments is also significant in function overloading. If you have functions with
parameters of different data types, changing the order can create distinct functions. This allows
you to overload functions based on how the parameters are arranged.

Example

#include <iostream>
using namespace std;

// Function to add an integer and a double


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

// Function to add a double and an integer


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

int main() {
double result1 = add(5, 10.5); // Calls the first version
double result2 = add(5.5, 10); // Calls the second version

cout << "Result of adding int and double: " << result1 << endl; //
Output: 15.5
cout << "Result of adding double and int: " << result2 << endl; //
Output: 15.5

return 0;
}
Summary

 Data Types of Arguments: Different data types allow the same function name to be used
for operations on different data types, enhancing flexibility and usability.
 Number of Arguments: Functions can be overloaded based on the number of parameters
they accept, allowing for variations in the function's functionality without creating
multiple function names.
 Order of Arguments: The arrangement of parameter types can differentiate overloaded
functions, enabling the same name to refer to distinct operations based on how the
arguments are passed.

Together, these aspects contribute to the versatility and readability of code in C++, making
function overloading a powerful feature in the language.

Q.No.15: Differentiate the following:


- Built-in function vs User defined function
- Local variable vs Global variable
- Formal parameters vs Actual parameters
- Local function vs Global function
- Passing arguments by values vs passing arguments by reference
Solution:

1. Built-in Function vs User Defined Function

Aspect Built-in Function User Defined Function


Functions provided by the Functions created by the programmer to
Definition
programming language itself. perform specific tasks.
printf(), scanf(), sqrt(), int add(int a, int b), void
Examples
strlen(). display().
Directly used without any definition; Must be defined before they can be used;
Usage
standard functions. tailored to specific needs.
Only available in the scope where they are
Availability Available in standard libraries.
defined or declared.
Usually optimized for speed by the Performance may vary based on the
Performance
language implementers. implementation.
2. Local Variable vs Global Variable

Aspect Local Variable Global Variable


A variable defined outside all
A variable defined within a function or block,
Definition functions, accessible throughout the
accessible only within that function/block.
program.
Limited to the function/block in which it is Accessible from any part of the
Scope
defined. program, including all functions.
Exists only during the execution of the
Lifetime Exists for the lifetime of the program.
function/block.
Memory Allocated on the stack. Allocated in the data segment.
cpp int x = 5; // Global
Example cpp int x = 5; // Local variable variable

3. Formal Parameters vs Actual Parameters

Aspect Formal Parameters Actual Parameters


Variables defined in the function signature that Values or variables passed to the
Definition
accept values when the function is called. function during the function call.
Local to the function and cannot be accessed Can be any variable or value used
Scope
outside of it. when calling the function.
cpp func(5, 10); // 5 and 10
Example cpp void func(int x, int y) { ... } are actual parameters

4. Local Function vs Global Function

Aspect Local Function Global Function


A function defined within another A function defined outside any other
Definition function, accessible only within that function, accessible from anywhere in the
enclosing function. program.
Limited to the enclosing function; cannot Accessible from any function in the
Scope
be called from outside. program.
cpp void outer() { void inner() {
Example ... }; } cpp void globalFunc() { ... }

Exists only during the execution of the


Lifetime Exists for the lifetime of the program.
enclosing function.
5. Passing Arguments by Values vs Passing Arguments by Reference

Aspect Passing Arguments by Values Passing Arguments by Reference


A copy of the actual argument is made A reference (or address) of the actual
Definition
and passed to the function. argument is passed to the function.
Changes made to the parameter inside
Effect on Actual Changes made to the parameter inside
the function do not affect the actual
Parameter the function affect the actual argument.
argument.
Syntax cpp void func(int x) { ... } cpp void func(int &x) { ... }
Requires more memory as a copy of More efficient in terms of memory as
Memory
the argument is created. only the reference is passed.
Useful for complex data types or when
Useful for simple data types where
Use Case modifications to the argument are
changes are not needed.
required.
Chapter No.7 “Pointers”

Exercise Solution

Q.No.1: Fill in the Blanks.

i. Pointers are special type of variable that store memory addresses of other variables.
ii. If we have a statement int n; and we want to define a pointer to 'n' then its data type must be
of the type int.
iii. Assigning values to a pointer during its declaration time is called pointer initialization.
iv. & is the reference operator.
v. * is the dereference operator which can be read as "value pointed by" operator.

Q.No.2: Multiple Choice Questions:

i. If we have the statement int *Ptr; then to what Ptr points?

a. Points to an integer type variable


b. Points to a character type variable
c. Points to a floating point type variable
d. Points to null variable

 Correct Answer: a. Points to an integer type variable

ii. A pointer is:

a. A keyword used to create variables


b. A variable that stores address of an instruction
c. A variable that stores address of another variable
d. All of the above

 Correct Answer: c. A variable that stores address of another variable

iii. The operator used to get the value at the address stored in a pointer variable is:

a. *
b. &
c. &&
d. ||

 Correct Answer: a. *

iv. Which of the statements is correct about the following segment of code?

int i = 10;
int *j = &i;
a. j and i are pointers to an int
b. i is a pointer to an int and stores address of j
c. j is a pointer to an int and stores address of i
d. j is a pointer to a pointer to an int and stores address of i

 Correct Answer: c. j is a pointer to an int and stores address of i

v. In pointers, the dereference operator * is used to:

a. Address the value of the pointer variable


b. Points to the value stored in the variable pointed by the pointer variable
c. Both a and b
d. None of the above

 Correct Answer: b. Points to the value stored in the variable pointed by the pointer
variable

Q.No.3: Write TRUE/FALSE against the following statements.

i. The statement int *ptr; defines an ordinary C++ variable.

 FALSE (It defines a pointer variable, not an ordinary variable.)

ii. The following lines of code assign the value of the variable Temp to the pointer variable
PTemp:

float Temp;
float *PTemp = &Temp;

 FALSE (This assigns the address of Temp to PTemp, not the value of Temp.)

iii. Pointer variables can be initialized by addresses of the variables to which they refer.

 TRUE

iv. To assign addresses to pointers, a programmer needs a special type of operator called the
address-of operator &.

 TRUE

v. When a variable is declared in C++, the compiler reserves location for this variable in
computer memory to store data.

 TRUE
Q.No.4: Define the term pointer. Describe the advantages of using pointer
variables.
Solution:
Definition of Pointer
A pointer in C++ is a special type of variable that stores the memory address of
another variable. Pointers provide a powerful way to manipulate data in memory
directly. They are used for dynamic memory allocation, array manipulation, and
for creating complex data structures like linked lists, trees, and graphs.
Characteristics of Pointers:
 Type-specific: A pointer's type determines the type of variable it points to.
For example, an int* pointer points to an integer type variable.
 Dereferencing: You can access the value stored at the memory address
held by the pointer using the dereference operator (*).
 Address-of Operator: The address of a variable can be obtained using the
address-of operator (&).

Advantages of Using Pointer Variables


1. Dynamic Memory Management:
o Pointers allow for dynamic allocation and deallocation of memory
using operators like new and delete. This enables the creation of data
structures that can grow and shrink in size during runtime, such as
linked lists and dynamic arrays.
2. Efficient Array and String Manipulation:
o Pointers can be used to efficiently navigate and manipulate arrays
and strings. Since arrays are contiguous blocks of memory, using
pointers can lead to more efficient data access and processing.
3. Passing by Reference:
o Pointers can be used to pass variables to functions by reference. This
means that any changes made to the parameter within the function
affect the original variable, allowing for more efficient data
manipulation without the overhead of copying large data structures.
4. Complex Data Structures:
o Pointers are essential for implementing complex data structures like
linked lists, trees, graphs, etc. They enable the creation of nodes that
can dynamically link to one another, allowing for flexible data
organization.
5. Memory Address Manipulation:
o Pointers allow programmers to manipulate memory directly, giving
them greater control over data storage and retrieval. This can lead to
more efficient use of memory and performance optimizations.
6. Function Pointers:
o Pointers can be used to store the address of functions, allowing for
dynamic function calls. This enables techniques like callback
functions and can facilitate the implementation of event-driven
programming.
7. Reduced Memory Overhead:
o By using pointers, you can avoid the overhead of copying large data
structures when passing them to functions, as only the address is
passed, not the entire data structure.

Q.No.5: What is the difference between the dereference operator * and


reference operator &? Explain with the help of some lines of code.
Solution:
Difference Between Dereference Operator (*) and Reference Operator (&):
In C++, the dereference operator (*) and the reference operator (&) serve different purposes
when working with pointers. Here’s a breakdown of their functions:
1. Dereference Operator (*):
o The dereference operator is used to access the value at the memory address stored in a
pointer variable. It allows you to retrieve or modify the value that the pointer is pointing
to.
2. Reference Operator (&):
o The reference operator is used to obtain the memory address of a variable. It allows you
to create a pointer that points to that variable.

Example Code
Here’s an example to illustrate the differences between the dereference operator (*) and the
reference operator (&):
#include <iostream>
using namespace std;

int main() {
int var = 42; // Declare an integer variable
int* ptr = &var; // Use the reference operator (&) to get the
address of var

cout << "Value of var: " << var << endl; // Outputs: 42
cout << "Address of var: " << &var << endl; // Outputs the
address of var
cout << "Value of ptr: " << ptr << endl; // Outputs the
address stored in ptr (address of var)
cout << "Value pointed to by ptr: " << *ptr << endl; // Outputs: 42
(dereference ptr to get the value of var)

// Modifying the value of var using the pointer


*ptr = 100; // Dereference ptr to change the value at that address

cout << "New value of var: " << var << endl; // Outputs: 100

return 0;
}
Explanation of the Code:

1. Variable Declaration:
o int var = 42; initializes an integer variable var with the value 42.
2. Reference Operator (&):
o int* ptr = &var; uses the reference operator to obtain the address of var. The
pointer ptr now holds the memory address of var.
3. Printing Values:
o cout << "Value of var: " << var; prints the value of var, which is 42.
o cout << "Address of var: " << &var; prints the memory address of var using
the reference operator.
o cout << "Value of ptr: " << ptr; prints the address stored in ptr, which is
the same as the address of var.
o cout << "Value pointed to by ptr: " << *ptr; uses the dereference
operator to access the value at the memory address stored in ptr. This outputs 42.
4. Modifying Value Using Dereference Operator (*):
o *ptr = 100; uses the dereference operator to access the value at the memory
address pointed to by ptr and changes it to 100. This modifies var indirectly through
the pointer.
5. Final Output:
o cout << "New value of var: " << var; prints the updated value of var, which
is now 100.

Q.No.6: What is meant by the term pointer initialization? Write a simple


program to illustrate this concept.

Solution:

Pointer Initialization
Pointer initialization refers to the process of assigning a pointer variable a valid memory
address at the time of its declaration. Proper initialization ensures that the pointer points to a
valid memory location before it is dereferenced, preventing undefined behavior in the program.
There are various ways to initialize a pointer, such as assigning it the address of an existing
variable, using nullptr, or allocating memory dynamically.

Simple Program to Illustrate Pointer Initialization


Here’s a simple C++ program that demonstrates pointer initialization by assigning it the address
of an existing variable:
#include <iostream>
using namespace std;

int main() {
int num = 25; // Declare an integer variable
int* ptr = &num; // Initialize the pointer with the address
of num

// Display the value of num using the pointer


cout << "Value of num: " << num << endl; // Output: 25
cout << "Address of num: " << &num << endl; // Output:
Address of num
cout << "Pointer ptr points to address: " << ptr << endl; // Output:
Address of num
cout << "Value pointed to by ptr: " << *ptr << endl; // Output: 25

// Modifying the value of num using the pointer


*ptr = 50; // Change the value at the address pointed by
ptr

cout << "New value of num: " << num << endl; // Output: 50

return 0;
}
Explanation of the Program:

1. Variable Declaration:
o int num = 25; initializes an integer variable num with the value 25.
2. Pointer Initialization:
o int* ptr = &num; initializes the pointer ptr with the address of the variable num.
The reference operator (&) is used to obtain the address of num.
3. Display Output:
o cout << "Value of num: " << num; prints the value of num, which is 25.
o cout << "Address of num: " << &num; prints the memory address of num.
o cout << "Pointer ptr points to address: " << ptr; prints the address
stored in ptr, which should match the address of num.
o cout << "Value pointed to by ptr: " << *ptr; uses the dereference
operator (*) to access the value stored at the address held by ptr, which is 25.
4. Modifying Value Using Pointer:
o *ptr = 50; changes the value at the memory address pointed to by ptr to 50. This
indirectly modifies the value of num.
5. Final Output:
o cout << "New value of num: " << num; prints the updated value of num, which
is now 50.

Q.No.7: How the declaration of a pointer variable is different from the


declaration of a simple variable?
Solution:
The declaration of a pointer variable is different from the declaration of a simple (non-pointer)
variable in several key aspects. Here are the main differences:

1. Syntax

 Simple Variable Declaration: A simple variable is declared by specifying its data type
followed by the variable name.

Example:
int num; // Declares an integer variable named num

 Pointer Variable Declaration: A pointer variable is declared by specifying its data type
followed by an asterisk (*) before the variable name, indicating that it is a pointer to the
specified data type.

Example:
int* ptr; // Declares a pointer variable named ptr that points to an
integer
2. Data Type

 Simple Variable: A simple variable directly holds a value of its specified data type (e.g.,
int, float, char).
 Pointer Variable: A pointer variable holds the address of a variable of a specific data
type. The type of pointer indicates what type of variable it can point to (e.g., int* for
integers, float* for floats).

3. Initialization

 Simple Variable: A simple variable can be directly initialized with a value during its
declaration.

Example:
int num = 10; // Directly initializes num with the value 10

 Pointer Variable: A pointer must be initialized with a valid memory address (typically
the address of another variable) or set to nullptr. It cannot be directly assigned a value
of its data type.

Example:
int num = 10;
int* ptr = &num; // Initializes ptr with the address of num
4. Memory Storage

 Simple Variable: Memory is allocated for the variable itself, where the actual value is
stored.
 Pointer Variable: Memory is allocated for the pointer itself, which stores the address of
another variable. The size of a pointer may vary depending on the architecture (typically
4 bytes on a 32-bit system and 8 bytes on a 64-bit system).

5. Usage

 Simple Variable: Used to store and manipulate data directly.


 Pointer Variable: Used for indirect access to data, dynamic memory management, and
creating complex data structures (like linked lists, trees, etc.).

Example Code
Here’s a simple example to illustrate the difference:
#include <iostream>
using namespace std;
int main() {
// Simple variable declaration
int num = 10; // Declares and initializes a simple variable
cout << "Value of num: " << num << endl; // Outputs: 10

// Pointer variable declaration


int* ptr = &num; // Declares a pointer variable and initializes it
with the address of num
cout << "Value of ptr: " << ptr << endl; // Outputs the address of num
cout << "Value pointed to by ptr: " << *ptr << endl; // Outputs: 10

return 0;
}
Chapter No.8 “Objects and Classes”

Exercise Solution

Q.No.1: Fill in the Blanks.


i. A constructor is a member function that is called automatically when an object
is created.
ii. The ability to reuse code already defined for the new purpose is referred to as
inheritance.
iii. In OOP, the main advantage of inheritance includes code reusability.
iv. An object of a class can be defined as a variable of type class.
v. Function overloading is used to achieve polymorphism.

Q.No.2: Select the correct choice for the following Multiple Choice Questions
i. A constructor is called whenever __________________________.
a. An object is destroyed
b. An object is created
c. A class is declared
d. A class is used
Correct answer: b. An object is created
ii. Destructor is used for __________________________.
a. Initializing the values of data members in an object
b. Initializing arrays
c. Freeing memory allocated to the object of the class when it was created
d. Creating an object
Correct answer: c. Freeing memory allocated to the object of the class when it
was created
iii. The name of destructor is always preceded by the symbol ______.
a. +
b. %
c. -
d. ~
Correct answer: d. ~
iv. Constructors are commonly used for __________________________.
a. Constructing programs
b. Running classes
c. Initializing objects
d. All of the above
Correct answer: c. Initializing objects
v. Inheritance is used to __________________________.
a. Increase the size of a program
b. Make the program simpler
c. Provide the facility of code reusability
d. Provide the facility of data hiding
Correct answer: c. Provide the facility of code reusability

Q.No.3: Write TRUE/FALSE against the following statements


i. C++ is a pure object-oriented programming language.
FALSE ✓ (C++ supports both procedural and object-oriented programming
paradigms, so it is not purely object-oriented.)

ii. One of the main features of object-oriented programming language is data


hiding.
TRUE ✓

iii. If you do not declare a constructor in a class, the compiler will furnish a default
constructor for you automatically.
TRUE ✓
iv. A constructor is a function that is called when an instance of a class is deleted.
FALSE ✗ (A destructor is called when an instance of a class is deleted, not a
constructor.)

v. Function overloading is an example of polymorphism.


TRUE ✓

Q.No.4: Write a class Marks with three data members to store three marks.
Write three member functions in() to input marks, sum() to calculate and return
the sum and avg() to calculate and return the average marks.

Solution:

C++ program that defines a class Marks with three data members to store marks and member
functions to input marks, calculate the sum, and calculate the average:

C++ Code:
#include <iostream>
using namespace std;

class Marks {
private:
int mark1, mark2, mark3; // Data members to store three marks

public:
// Member function to input marks
void in() {
cout << "Enter three marks: ";
cin >> mark1 >> mark2 >> mark3;
}

// Member function to calculate and return the sum of marks


int sum() {
return mark1 + mark2 + mark3;
}

// Member function to calculate and return the average of marks


float avg() {
return sum() / 3.0; // Calling sum() to calculate the average
}
};
int main() {
Marks student; // Creating an object of class Marks

// Input marks
student.in();

// Display the sum and average of the marks


cout << "Sum of marks: " << student.sum() << endl;
cout << "Average of marks: " << student.avg() << endl;

return 0;
}

Explanation:

 Data Members:
o mark1, mark2, and mark3 are private data members to store the three marks.
 Member Functions:
o in(): This function prompts the user to input three marks and stores them in the
data members.
o sum(): This function calculates the sum of the three marks and returns the result.
o avg(): This function calculates the average of the three marks by dividing the
sum by 3 and returns the result.

Sample Output:
Enter three marks: 85 90 80
Sum of marks: 255
Average of marks: 85

Q.No.5: Write a C++ program implementing inheritance between Employee


(base class) and Manager (derived class).
Solution:

C++ program that demonstrates inheritance between a base class Employee and a derived class
Manager. The program will define basic properties and methods for the Employee class and
extend those properties in the Manager class.

C++ Program
#include <iostream>
#include <string>
using namespace std;

// Base class
class Employee {
protected:
string name;
int id;

public:
// Constructor to initialize Employee data members
Employee(string empName, int empId) {
name = empName;
id = empId;
}

// Function to display employee details


void displayEmployeeInfo() {
cout << "Employee Name: " << name << endl;
cout << "Employee ID: " << id << endl;
}
};

// Derived class
class Manager : public Employee {
private:
string department;

public:
// Constructor to initialize Manager data members
Manager(string empName, int empId, string dept) : Employee(empName,
empId) {
department = dept;
}

// Function to display manager details


void displayManagerInfo() {
// Call base class function to display employee info
displayEmployeeInfo();
cout << "Department: " << department << endl;
}
};

int main() {
// Create a Manager object
Manager manager("Alice Johnson", 101, "Sales");

// Display manager details


manager.displayManagerInfo();

return 0;
}

Explanation

1. Base Class (Employee):


o The Employee class has two protected data members: name (to store the
employee's name) and id (to store the employee's ID).
o It has a constructor that initializes these data members.
o The displayEmployeeInfo() function displays the employee's name and ID.
2. Derived Class (Manager):
o The Manager class inherits from the Employee class using public inheritance.
o It has an additional private data member: department (to store the manager's
department).
o The constructor of the Manager class initializes its own department data member
and calls the base class constructor to initialize the name and id.
o The displayManagerInfo() function first calls the base class function to display
employee details and then displays the manager's department.
3. Main Function:
o An object of the Manager class is created with the name "Alice Johnson", ID 101,
and department "Sales".
o The displayManagerInfo() function is called to show the manager's details,
including their employee information.

Sample Output

When you run the program, it will display the following output:

Employee Name: Alice Johnson


Employee ID: 101
Department: Sales

This program illustrates how inheritance allows the Manager class to build upon the functionality
of the Employee class, promoting code reusability and organization.

Q.No.6: Diagrammatically represent the following scenario of inheritance:


• We have Shape as a base class and Circle, Rectangle, Triangle and Square as
its derived classes.
Solution:

Here’s a diagrammatic representation of the inheritance scenario where Shape is the base class
and Circle, Rectangle, Triangle, and Square are its derived classes.

Inheritance Diagram
Shape
/|\
/ | \
/ | \
/ | \
Circle | Rectangle
|
Triangle
|
Square
Explanation of the Diagram:

1. Base Class:
o Shape
is the base class. It may contain common attributes and methods relevant to
all shapes, such as area and perimeter.
2. Derived Classes:
o Circle, Rectangle, Triangle, and Square are the derived classes. Each of these
classes inherits the properties and methods from the Shape class and can have
additional properties or methods specific to their shape.

Relationships:

 The arrows (or lines) represent the inheritance relationship where the derived classes
inherit from the base class.
 The derived classes can access public and protected members of the Shape class,
enabling them to utilize and extend its functionality.

Summary:

This diagram illustrates a clear hierarchy in which all the specific shape classes derive from a
common Shape class, emphasizing the concept of inheritance in object-oriented programming.

Q.No.7: Write a class that displays a simple message on the screen whenever an
object of that class is created.
Solution:

C++ program that defines a class which displays a simple message on the screen whenever an
object of that class is created. This is accomplished using a constructor that outputs the message
when an instance of the class is instantiated.

C++ Program
#include <iostream>
using namespace std;

// Class definition
class SimpleMessage {
public:
// Constructor
SimpleMessage() {
cout << "A new object of SimpleMessage class has been created!"
<< endl;
}
};
int main() {
// Creating an object of SimpleMessage class
SimpleMessage message1; // Message will be displayed here
SimpleMessage message2; // Message will be displayed here as well

return 0;
}

Explanation

1. Class Definition:
o The class SimpleMessage is defined with a public constructor.
2. Constructor:
o The constructor of the class SimpleMessage is defined to print a message to the
console whenever an object of the class is created. The message displayed is:

A new object of SimpleMessage class has been created!

3. Main Function:
o Inside the main() function, two objects of the SimpleMessage class are created
(message1 and message2).
o When each object is created, the constructor is automatically called, and the
message is displayed.

Sample Output

When you run the program, the output will look like this:

A new object of SimpleMessage class has been created!


A new object of SimpleMessage class has been created!

This implementation demonstrates the use of constructors in C++ to perform actions at the time
of object creation.

Q.No.8: Write a C++ program implementing a class with the name Time. This
class should have a constructor to initialize the time, hours, minutes and
seconds. The class should have another function named ToSecond() to convert
and display the time into seconds.
Solution:

C++ program that defines a class named Time, which includes a constructor to initialize hours,
minutes, and seconds. The class also has a member function ToSecond() that converts the time
into total seconds and displays the result.
C++ Program
#include <iostream>
using namespace std;

class Time {
private:
int hours; // Hours
int minutes; // Minutes
int seconds; // Seconds

public:
// Constructor to initialize time
Time(int h, int m, int s) {
hours = h;
minutes = m;
seconds = s;
}

// Function to convert time into seconds and display it


void ToSecond() {
int totalSeconds = (hours * 3600) + (minutes * 60) + seconds;
cout << "Total time in seconds: " << totalSeconds << " seconds"
<< endl;
}
};

int main() {
// Create an object of Time class and initialize it
Time time(1, 30, 45); // 1 hour, 30 minutes, and 45 seconds

// Call the ToSecond function to display the time in seconds


time.ToSecond();

return 0;
}

Explanation

1. Class Definition:
o The Time class has three private data members: hours, minutes, and seconds to
store the time.
2. Constructor:
o The constructor Time(int h, int m, int s) initializes the three data members
with the values provided when an object of the class is created.
3. Member Function ToSecond():
o The ToSecond() function calculates the total time in seconds using the formula:
Total Seconds=(hours×3600)+(minutes×60)+seconds\text{Total Seconds} =
(\text{hours} \times 3600) + (\text{minutes} \times 60) +
\text{seconds}Total Seconds=(hours×3600)+(minutes×60)+seconds
o It then displays the total time in seconds.
4. Main Function:
o An object of the Time class is created and initialized with 1 hour, 30 minutes, and
45 seconds.
o The ToSecond() function is called to display the total time in seconds.

Sample Output

When you run the program, the output will look like this:

Total time in seconds: 5445 seconds

Q.No.9: What is object? How objects are created to access members of a class?
Solution:

What is an Object?

In object-oriented programming (OOP), an object is an instance of a class. It represents a real-


world entity with specific attributes (data members) and behaviors (member functions or
methods). Objects encapsulate data and the functions that operate on that data, promoting a
modular approach to programming.

Key Characteristics of an Object:

1. State: The current values of the object's data members.


2. Behavior: The methods or functions defined in the class that operate on the object's data.
3. Identity: A unique identifier for the object, distinguishing it from other objects.

Creating Objects and Accessing Members of a Class

To use a class in C++, you need to create an object of that class. Here’s how objects are created
and how you can access members of a class:

Steps to Create an Object:

1. Define the Class: First, you define the class with its attributes and methods.
2. Instantiate the Object: Create an object using the class name followed by the object
name.
3. Access Members: Use the dot operator (.) to access the attributes and methods of the
class.

Example in C++

Here's a simple example to illustrate how to create an object and access its members.
#include <iostream>
using namespace std;

// Class definition
class Car {
public:
// Data members
string brand;
int year;

// Member function to display car details


void displayInfo() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};

int main() {
// Step 1: Create an object of Car class
Car myCar;

// Step 2: Access and set the members using the dot operator
myCar.brand = "Toyota"; // Setting the brand
myCar.year = 2020; // Setting the year

// Step 3: Call the member function to display car details


myCar.displayInfo(); // Output: Brand: Toyota, Year: 2020

return 0;
}

Explanation of the Example:

1. Class Definition: The Car class is defined with two data members (brand and year) and
a member function (displayInfo()).
2. Creating an Object: In the main() function, an object myCar of the Car class is created.
3. Accessing Members:
o The data members brand and year are accessed and set using the dot operator.
For example, myCar.brand = "Toyota"; sets the brand of myCar.
o The displayInfo() member function is called using the dot operator to display
the car's information.

Q.No.10: Explain inheritance and polymorphism with examples.


Solution:

Inheritance

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new


class (called a derived class or subclass) to inherit the properties and behaviors (methods) of an
existing class (called a base class or superclass). This promotes code reusability, as the derived
class can utilize the functionality of the base class while adding its own features.

Types of Inheritance:

1. Single Inheritance: A class inherits from one base class.


2. Multiple Inheritance: A class inherits from multiple base classes.
3. Multilevel Inheritance: A class inherits from another derived class.
4. Hierarchical Inheritance: Multiple classes inherit from a single base class.

Example of Inheritance

Here’s a simple example demonstrating inheritance in C++:

#include <iostream>
using namespace std;

// Base class
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};

// Derived class
class Dog : public Animal {
public:
void bark() {
cout << "Barking..." << endl;
}
};

int main() {
Dog myDog; // Creating an object of the derived class
myDog.eat(); // Calling the base class function
myDog.bark(); // Calling the derived class function

return 0;
}

Explanation of Inheritance Example:

 Base Class (Animal): Contains a method eat().


 Derived Class (Dog): Inherits from the Animal class and adds a new method bark().
 Object Creation: An object myDog of the Dog class is created. It can access both eat()
from the Animal class and bark() from its own class.

Polymorphism
Polymorphism is another core concept in OOP that allows objects to be treated as instances of
their parent class, even when they are of derived classes. It enables methods to perform
differently based on the object that invokes them. Polymorphism can be achieved in two ways:

1. Compile-time Polymorphism (Method Overloading and Operator Overloading)


2. Runtime Polymorphism (Method Overriding using Virtual Functions)

Example of Polymorphism

Here’s an example demonstrating runtime polymorphism using virtual functions:

#include <iostream>
using namespace std;

// Base class
class Shape {
public:
virtual void draw() { // Virtual function
cout << "Drawing a shape." << endl;
}
};

// Derived class 1
class Circle : public Shape {
public:
void draw() override { // Override base class method
cout << "Drawing a circle." << endl;
}
};

// Derived class 2
class Rectangle : public Shape {
public:
void draw() override { // Override base class method
cout << "Drawing a rectangle." << endl;
}
};

int main() {
Shape* shape; // Base class pointer

// Creating a Circle object


Circle circle;
shape = &circle;
shape->draw(); // Calls Circle's draw method

// Creating a Rectangle object


Rectangle rectangle;
shape = &rectangle;
shape->draw(); // Calls Rectangle's draw method

return 0;
}
Explanation of Polymorphism Example:

 Base Class (Shape): Contains a virtual method draw().


 Derived Classes (Circle and Rectangle): Both override the draw() method to provide
specific implementations.
 Base Class Pointer: A pointer of type Shape is used to point to objects of the derived
classes (Circle and Rectangle).
 Dynamic Binding: When shape->draw() is called, the appropriate draw() method of
the derived class is invoked based on the actual object type, demonstrating runtime
polymorphism.
Chapter No.9 “File Handling”

Exercise Solution

Q.No.1: Fill in the Blanks:

i. In C++ language, for handling of files, the header file <fstream> is used.

ii. The function close is used for closing a file.

iii. In the statement, open(“xyz.txt”, ios::out);, xyz.txt file is opened in output mode.

iv. If all output operations are to be performed at the end of the file, then ios::app should be
used in the open function.

v. A stream is “a continuous flow or succession of bytes.”

Q.No.2: Select the correct choice for the following Multiple Choice Questions:
i. eof stands for ______________.
a. errors-on-files
b. end-of-file ✓
c. exit-of-file
d. Execution of file
ii. In file handling, open() function is used ______________.
a. to open C++ compiler
b. to open a file ✓
c. both a and b
d. Open a function
iii. Default mode parameter for ofstream is ______________.

a. ios::out ✓
b. ios::in
c. ios::binary
d. both a and b
iv. A text file has the extension ________.
a. .doc
b. .docx
c. .txt ✓
d. .bin
v. ios::binary is used as an argument to open() function for __________.
a. opening file for input operation.
b. opening file for output operation.
c. opening file in binary mode. ✓
d. Open file for binary operation.

Q.No.3: Write TRUE/FALSE against the following statements:

i. A string stream is a stream which reads input from or writes output to an associated string.
TRUE ✓

ii. The eof() is a pointer which returns false when there are no more data to be read from an input
file stream, and true otherwise.
FALSE ✗ (eof() returns true when the end of the file is reached, and false otherwise.)

iii. To open a file in binary mode, we need to set the file mode to ios::binary.
TRUE ✓

iv. close() Function is used in C++ file handling for opening a new file.
FALSE ✗ (The close() function is used to close an opened file, not for opening a new file.)

v. Those files that store data in text format and are readable by humans are called text files.
TRUE ✓

Q.No.4: Define file. Describe different types of file.

Solution:

A file is a collection of data or information that is stored on a storage device, such as a hard
drive, SSD, USB drive, or cloud storage. Files can contain various types of data, including text,
images, audio, video, and more. They are identified by a unique name and extension, which
indicates the type of content they hold and determines how the data can be accessed or processed
by software applications.

Different Types of Files

Files can be broadly categorized into two main types:

1. Text Files:
o Definition: These files store data in a human-readable format, using plain text or
characters.
o Characteristics:
 Typically encoded in ASCII or UTF-8 format.
 Can be easily opened and edited using text editors (e.g., Notepad, Vim).
 Often have extensions like .txt, .csv, .html, or .xml.
o Example:
 A .txt file containing a list of names.
 A .csv file storing tabular data that can be opened in spreadsheet
applications.
2. Binary Files:
o Definition: These files store data in a format that is not human-readable,
consisting of binary data (0s and 1s).
o Characteristics:
 May contain various data types, such as images, audio, video, or compiled
programs.
 Cannot be easily opened or edited with standard text editors; requires
specific software (e.g., image editors, audio players).
 Often have extensions like .bin, .exe, .jpg, .mp3, or .zip.
o Example:
 An image file (e.g., .jpg) storing pixel data.
 An executable file (e.g., .exe) containing machine code.

Summary of File Types

Common
File Type Description Examples
Extensions
Store data in human-readable .txt, .csv, .html, Document files, CSV
Text Files
format .xml spreadsheets
Binary Store data in a non-human- .bin, .exe, .jpg, Images, audio files,
Files readable format .mp3 executables
Q.No.5: Describe different types of operations performed on the files.

Solution:

Different Types of Operations Performed on Files

In file handling, several operations can be performed to manage data stored in files. Here’s a
breakdown of the common file operations:

1. Creating a File:
o Description: The process of generating a new file on a storage device. If the file
already exists, it may either be overwritten or a new file with a different name can
be created.
o Example in C++:

ofstream outfile("newfile.txt"); // Creates a new text file

2. Opening a File:
o Description: Accessing an existing file to perform read/write operations. Files
can be opened in different modes (e.g., read, write, append).
o Modes:
 Input mode (ios::in): For reading data.
 Output mode (ios::out): For writing data.
 Append mode (ios::app): For adding data to the end of the file.
 Binary mode (ios::binary): For handling binary data.
o Example in C++:

ifstream infile("data.txt"); // Opens a file for reading

3. Reading from a File:


o Description: Retrieving data from a file into the program. This can be done
character by character, line by line, or in a block.
o Example in C++:

string line;
while (getline(infile, line)) {
cout << line << endl; // Reads and prints each line
}

4. Writing to a File:
o Description: Sending data from the program to a file. This can also be done
character by character, line by line, or in a block.
o Example in C++:

ofstream outfile("output.txt");
outfile << "Hello, World!" << endl; // Writes to the file
5. Appending to a File:
o Description: Adding data to the end of an existing file without overwriting its
current content.
o Example in C++:

ofstream outfile("output.txt", ios::app); // Opens the file in


append mode
outfile << "New line added." << endl; // Appends to the
file

6. Closing a File:
o Description: Finalizing access to a file. It ensures that any changes made during
the session are saved and frees up system resources.
o Example in C++:

infile.close(); // Closes the input file


outfile.close(); // Closes the output file

7. Checking the End of File (EOF):


o Description: Determining whether the end of the file has been reached during a
read operation.
o Example in C++:

if (infile.eof()) {
cout << "End of file reached." << endl;
}

8. Seeking in a File:
o Description: Moving the file pointer to a specific location within the file,
allowing random access to data.
o Example in C++:

infile.seekg(0, ios::beg); // Moves the pointer to the beginning


of the file

Summary of File Operations

File Operation Description


Creating a File Generating a new file on the storage device
Opening a File Accessing a file for read/write operations
Reading from a File Retrieving data from a file
Writing to a File Sending data to a file
Appending to a File Adding data to the end of an existing file
Closing a File Finalizing access to a file and freeing system resources
Checking EOF Determining if the end of the file has been reached
Seeking in a File Moving the file pointer to a specific location
Q.No.6: Define streams. Describe input and output streams in detail.

Solution:

Definition of Streams

In C++, a stream is an abstraction that represents a flow of data. Streams provide a mechanism
for input (reading data) and output (writing data) in a consistent manner. They allow for the
handling of data in a sequential manner, whether the data comes from the keyboard, a file, or
another source. The use of streams simplifies the process of data input and output by providing a
uniform interface for these operations.

Types of Streams

There are two primary types of streams in C++:

1. Input Streams: Used to read data from a source.


2. Output Streams: Used to write data to a destination.

Input Streams

Definition

An input stream is a flow of data coming into a program from an external source, such as a
keyboard or a file. The primary class used for input operations in C++ is istream.

Common Input Stream Objects

 cin: Standard input stream, typically used to read input from the keyboard.
 ifstream: Input file stream used to read data from files.

Operations with Input Streams

1. Reading from Standard Input (cin):


o The cin object is used to read data entered by the user from the keyboard.
o Example:

int number;
cout << "Enter a number: ";
cin >> number; // Reads an integer from standard input

2. Reading from Files (ifstream):


o An ifstream object is used to read data from a file.
o Example:

ifstream infile("data.txt");
string line;
while (getline(infile, line)) {
cout << line << endl; // Reads and prints each line from the
file
}
infile.close(); // Don't forget to close the file

3. Error Handling:
o Input streams can indicate errors, such as trying to read data of an incorrect type.
The fail() method can be used to check for input errors.
o Example:

if (cin.fail()) {
cout << "Invalid input!" << endl;
}

Output Streams

Definition

An output stream is a flow of data going out of a program to a destination, such as the console
or a file. The primary class used for output operations in C++ is ostream.

Common Output Stream Objects

 cout: Standard output stream, typically used to write output to the console.
 ofstream: Output file stream used to write data to files.

Operations with Output Streams

1. Writing to Standard Output (cout):


o The cout object is used to display output on the console.
o Example:

cout << "Hello, World!" << endl; // Prints "Hello, World!" to


the console

2. Writing to Files (ofstream):


o An ofstream object is used to write data to a file.
o Example:

ofstream outfile("output.txt");
outfile << "This is a line of text." << endl; // Writes a line
to the file
outfile.close(); // Close the file when done

3. Formatting Output:
o C++ provides several manipulators for formatting output, such as setw,
setprecision, and fixed.
o Example:

cout << fixed << setprecision(2) << 3.14159 << endl; // Outputs
3.14

4. Error Handling:
o Similar to input streams, output streams can also indicate errors, such as issues
writing to a file. The fail() method can be used to check for output errors.
o Example:

if (outfile.fail()) {
cout << "Error writing to file!" << endl;
}

Summary of Input and Output Streams

Common Example
Stream Type Purpose
Objects Operation
Reads data from a source (keyboard or cin >> variable;
Input Stream cin, ifstream
file)
Output Writes data to a destination (console or cout << "Text";
cout, ofstream
Stream file)

Q.No.7: What is meant by the term mode of file opening? Describe different modes of
opening file.

Solution:

Mode of File Opening

The mode of file opening refers to the specific way a file is accessed when it is opened in a
program. The mode determines the operations that can be performed on the file, such as reading,
writing, or appending data. Different modes provide various functionalities for handling files and
dictate how the file contents are managed during the operation.

In C++, file opening modes are specified as arguments in the open() function or directly in the
constructor of file stream objects (like ifstream, ofstream, or fstream). The modes are
defined using constants from the fstream library.

Different Modes of Opening a File

1. Input Mode (ios::in):


o Description: Opens a file for reading. If the file does not exist, the open operation
fails.
o Usage: Typically used with ifstream objects.
o Example:

ifstream infile("example.txt", ios::in); // Open for reading

2. Output Mode (ios::out):


o Description: Opens a file for writing. If the file already exists, it is truncated
(emptied). If it does not exist, a new file is created.
o Usage: Typically used with ofstream objects.
o Example:

ofstream outfile("example.txt", ios::out); // Open for writing

3. Append Mode (ios::app):


o Description: Opens a file for writing at the end of the file. If the file does not
exist, a new file is created. The contents of the file are preserved, and new data is
added to the end.
o Usage: Can be used with both ofstream and fstream.
o Example:

ofstream outfile("example.txt", ios::app); // Open for appending

4. Binary Mode (ios::binary):


o Description: Opens a file in binary mode rather than text mode. This mode is
used for reading or writing binary data (such as images or executable files).
o Usage: Can be combined with other modes (like ios::in | ios::binary).
o Example:

ifstream infile("example.bin", ios::in | ios::binary); // Open


binary file for reading

5. Truncation Mode (ios::trunc):


o Description: Used with ios::out to truncate a file to zero length if it already
exists. This is the default behavior when opening a file with ios::out.
o Example:

ofstream outfile("example.txt", ios::out | ios::trunc); //


Truncates existing file

6. Read/Write Mode (ios::in | ios::out):


o Description: Opens a file for both reading and writing. The file must exist. If it
does not, the open operation fails.
o Usage: Typically used with fstream objects.
o Example:
fstream file("example.txt", ios::in | ios::out); // Open for
reading and writing

Summary of File Opening Modes

Mode Description Example


ios::in
Open for reading; fails if the file does ifstream infile("file.txt",
not exist. ios::in);

ios::out
Open for writing; truncates the file if it ofstream outfile("file.txt",
exists. ios::out);

ios::app
Open for appending; creates a new file ofstream outfile("file.txt",
if it does not exist. ios::app);

ios::binary
Open in binary mode; used for binary ifstream infile("file.bin",
data. ios::binary);
Truncate the file to zero length if it
ios::trunc `ofstream outfile("file.txt", ios::out
exists (default for ios::out).
Open for reading and writing; fails if the
`ios::in ios::out`
file does not exist.

Q.No8: What is file handling? Explain it in detail.

Solution:

File Handling in C++

File handling refers to the process of creating, reading, writing, and managing files in a
programming environment. In C++, file handling is crucial for persistent data storage, allowing
programs to save data beyond their execution lifecycle. Through file handling, developers can
store user input, results, configurations, logs, and other types of data in files, enabling them to
retrieve or modify this data later.

Importance of File Handling

1. Data Persistence: Files allow data to be saved and retrieved later, making applications
more functional and user-friendly.
2. Large Data Handling: Files are essential for managing large volumes of data that
exceed the memory capacity of the system.
3. Inter-process Communication: Files can serve as a medium for sharing data between
different applications or processes.

Key Components of File Handling


1. File Streams: C++ uses streams to represent a flow of data to and from files. The most
commonly used stream classes for file handling are:
o ifstream: Input file stream for reading from files.
o ofstream: Output file stream for writing to files.
o fstream: File stream that can handle both input and output.
2. File Modes: When opening a file, different modes can be specified to determine how the
file can be accessed. Common modes include:
o ios::in: Open for reading.
o ios::out: Open for writing.
o ios::app: Open for appending data.
o ios::binary: Open in binary mode.
3. File Operations: The primary operations involved in file handling are:
o Creating a File: Using ofstream to create a new file.
o Opening a File: Accessing an existing file for reading or writing.
o Reading from a File: Using ifstream to read data from a file.
o Writing to a File: Using ofstream to write data to a file.
o Appending to a File: Adding data to the end of an existing file.
o Closing a File: Finalizing operations and releasing resources.

Steps for File Handling in C++

1. Include the Necessary Header: To use file handling features, the <fstream> header
must be included.

#include <fstream>

2. Create File Stream Objects:

ifstream infile; // For reading


ofstream outfile; // For writing

3. Open a File: Specify the file name and mode in the open() function or use it in the
constructor.

outfile.open("data.txt", ios::out); // Opens data.txt for writing

4. Perform File Operations:


o Writing to a File:

outfile << "Hello, File Handling!" << endl;

o Reading from a File:

string line;
infile.open("data.txt", ios::in); // Opens data.txt for reading
while (getline(infile, line)) {
cout << line << endl; // Print each line
}
5. Close the File: Always close files after operations to ensure data integrity and release
system resources.

infile.close();
outfile.close();

Example of File Handling in C++

Here’s a simple example demonstrating file handling in C++:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
// Writing to a file
ofstream outfile("example.txt");
if (outfile.is_open()) {
outfile << "Hello, World!" << endl;
outfile << "Welcome to file handling in C++." << endl;
outfile.close(); // Close the output file
} else {
cout << "Unable to open file for writing." << endl;
}

// Reading from the file


ifstream infile("example.txt");
string line;
if (infile.is_open()) {
while (getline(infile, line)) {
cout << line << endl; // Print each line from the file
}
infile.close(); // Close the input file
} else {
cout << "Unable to open file for reading." << endl;
}

return 0;
}
Q.No9: Differentiate the following:
• bof() vs eof()
• Opening file vs closing file
• Character stream vs string stream
• Reading file vs writing file

Solution:

1. bof() vs eof()

Aspect bof() eof()


Full Form Beginning of File End of File
Checks if the current position of the
Checks if the end of the file has been
Functionality file stream is at the beginning of the
reached during reading.
file.
Returns true if the file pointer is at Returns true if the end of the file has
Return Value
the beginning, false otherwise. been reached, false otherwise.
Commonly used before reading from Commonly used after a read operation to
Usage
a file to ensure the pointer is at the check if the end of the file has been
Context
start. reached.

2. Opening File vs Closing File

Aspect Opening File Closing File


The process of accessing a file to The process of terminating access to a
Definition
perform read or write operations. file after operations are completed.
To prepare the file for reading or To free resources associated with the
Purpose writing, allocating necessary file and ensure all data is written and
resources. saved.
open() method or constructor of file
close() method of the file stream
Function/Method stream classes (e.g., ifstream,
classes.
ofstream).
Failing to open a file may lead to Failing to close a file can lead to data
Consequences
errors in file operations. loss or corruption.

3. Character Stream vs String Stream

Aspect Character Stream String Stream


A stream that handles data as A stream that operates on strings, allowing
Definition
individual characters. input/output to/from a string.
Aspect Character Stream String Stream
Typically used for reading/writing Used for manipulating strings as input or
Use Cases
files or standard input/output. output, useful for formatting and parsing.
Classes istream (for input) and ostream istringstream (for input) and
Used (for output). ostringstream (for output).
Data Type Operates on char data types. Operates on std::string.

4. Reading File vs Writing File

Aspect Reading File Writing File


The process of retrieving data from a
Definition The process of storing data to a file.
file.
To obtain information previously To save new data or modify existing
Purpose
saved in a file. data in a file.
File Stream
Uses ifstream for input operations. Uses ofstream for output operations.
Used
Data flows from the file to the
Data Direction Data flows from the program to the file.
program.

You might also like