Computer Science Part-2
Computer Science Part-2
1 “Introduction”
Exercise Solution
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.
a. Application software
b. System software
c. Driver
d. Utility program
Correct Answer: b. System software
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. Windows 98
b. Windows 11
c. DOS
d. Windows NT
Correct Answer: b. Windows 11
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
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
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
True
Q.4 What is an Operating System? Explain 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:
Each type of operating system is designed to meet specific needs, from managing multiple users
to ensuring real-time performance in critical systems.
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.
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:
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.
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.
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:
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
2. Memory Management
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.
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.
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
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) 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:
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.
Key Features:
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.
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.
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:
In summary, RTOS plays a crucial role in applications where timely and predictable processing
is necessary to ensure system performance, safety, and reliability.
DOS vs Windows
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:
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:
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:
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.
Exercise Solution
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.3 True/False:
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.
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.
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.
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
Pseudocode
Procedure SortList
Swap them
End Procedure
Key Differences
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.
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.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.
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
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:
where aaa, bbb, and ccc are coefficients of the quadratic equation ax2+bx+c=0ax^2 + bx + c =
0ax2+bx+c=0.
#include <iostream>
#include <cmath> // For sqrt() function
using namespace std;
int main() {
double a, b, c;
double discriminant, root1, root2, realPart, imaginaryPart;
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;
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;
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
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.
if (x = 100)
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.
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.
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.
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:
case 2:
break;
default:
2.
if (x == 1){
else if (x == 2){
else {
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:
break;
default:
cout << "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.
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.
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
• else {
• }
• if (condition) {
• } False
Q.4 Write a C++ program that takes three numbers as input and displays whether all
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;
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;
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:
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;
return 0;
}
Explanation:
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;
std::cout << "The product components of " << number << " are:" <<
std::endl;
return 0;
}
Explanation:
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 '.'
}
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;
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;
return 0;
}
Explanation:
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.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);
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
FALSE (Arrays are collections of data items of the same data type.)
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.)
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.
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++:
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
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.
#include <iostream>
int main() {
// Declare and initialize an array
int arr[] = {10, 20, 30, 40, 50};
return 0;
}
Explanation
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:
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.
#include <iostream>
int main() {
// Define matrices A and B
const int rowsA = 3, colsA = 2;
const int rowsB = 2, colsB = 3;
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!";
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.
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} };
return 0;
}
Explanation
Output
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.
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].
#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} };
return 0;
}
Explanation
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:
#include <iostream>
int main() {
const int daysInWeek = 7;
float temperatures[daysInWeek];
float maxTemperature = -9999.0; // Initialize to a very low value
int hottestDayIndex = 0;
return 0;
}
Explanation
If the user inputs temperatures like 23.5, 25.0, 22.1, 30.0, 28.5, 26.7, 24.3, the
program will output:
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];
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
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} };
return 0;
}
Explanation
Sample Output
Given the array Test with values { {1, 2, 3}, {4, 5, 6} }, the program will output:
This program calculates and displays the sum of all the values in the 2D array.
Q.13 Write a brief note on the following:
c. Concatenation of string
d. Strings
Solution:
a. One-Dimensional Array
Example:
Key Points:
Advantages:
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:
Advantages:
Suitable for modeling data with two dimensions, like grids or tables.
Allows for more complex data organization.
Disadvantages:
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
Key Points:
Advantages:
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:
Advantages:
Exercise Solution
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;
int main() {
int num1, num2, sum;
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;
int main() {
int num1, num2, num3;
float result;
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;
int main() {
float length, width, area;
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;
int main() {
float side;
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;
if (isPrime) {
cout << number << " is a prime number." << endl;
} else {
cout << number << " is a composite number." << endl;
}
}
int main() {
int number;
return 0;
}
Explanation:
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;
int main() {
int number;
return 0;
}
Explanation:
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
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.
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.
return_type function_name(parameter_list);
#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.
return_type function_name(parameter_list) {
// function body
}
#include <iostream>
using namespace std;
int main() {
int product = multiply(4, 5); // Function call
cout << "Product: " << product << endl;
return 0;
}
Key Differences
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:
int main() {
// Calling the function with all arguments
displayInfo("Alice", 25, "New York");
return 0;
}
Output
Name: Alice
Age: 25
City: New York
Name: Bob
Age: 30
City: Unknown
Name: Charlie
Age: 18
City: Unknown
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.
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.
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
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.
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;
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;
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;
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.
Exercise Solution
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.
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: b. Points to the value stored in the variable pointed by the pointer
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 (&).
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)
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.
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.
int main() {
int num = 25; // Declare an integer variable
int* ptr = # // Initialize the pointer with the address
of num
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 = # 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: " << # 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.
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 = # // 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
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
return 0;
}
Chapter No.8 “Objects and Classes”
Exercise Solution
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
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.)
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;
}
// Input marks
student.in();
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
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;
}
// 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;
}
int main() {
// Create a Manager object
Manager manager("Alice Johnson", 101, "Sales");
return 0;
}
Explanation
Sample Output
When you run the program, it will display the following output:
This program illustrates how inheritance allows the Manager class to build upon the functionality
of the Employee class, promoting code reusability and organization.
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:
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:
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;
}
int main() {
// Create an object of Time class and initialize it
Time time(1, 30, 45); // 1 hour, 30 minutes, and 45 seconds
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:
Q.No.9: What is object? How objects are created to access members of a class?
Solution:
What is an Object?
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:
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;
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
return 0;
}
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.
Inheritance
Types of Inheritance:
Example of Inheritance
#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;
}
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:
Example of Polymorphism
#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
return 0;
}
Explanation of Polymorphism Example:
Exercise Solution
i. In C++ language, for handling of files, the header file <fstream> is used.
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.
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.
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 ✓
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.
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.
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:
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++:
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++:
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++:
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++:
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++:
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
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.
cin: Standard input stream, typically used to read input from the keyboard.
ifstream: Input file stream used to read data from files.
int number;
cout << "Enter a number: ";
cin >> number; // Reads an integer from standard input
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.
cout: Standard output stream, typically used to write output to the console.
ofstream: Output file stream used to write data to files.
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;
}
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:
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.
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.
Solution:
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.
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.
1. Include the Necessary Header: To use file handling features, the <fstream> header
must be included.
#include <fstream>
3. Open a File: Specify the file name and mode in the open() function or use it in the
constructor.
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();
#include <iostream>
#include <fstream>
#include <string>
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;
}
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()