C Assigment
C Assigment
INTERNAL ASSIGNMENT
SESSION MARCH 2024
PROGRAM BCA
SEMESTER II
COURSE CODE & NAME DCA1203-Object Oriented Programming – C++
CREDITS 4
NUMBER OF ASSIGNMENTS & 02
MARKS 30 Marks Each
SET-I
Q. No Questions Marks Total Marks
1. Describe the various datatypes available in C++? 10 10
What is the difference between the do-while and the while
2. 10 10
statements?
3. Brief about class and objects. 10 10
SET-II
Q. No Questions Marks Total Marks
Define exception. Explain exception handling
4. 10 10
mechanism.
5. List and explain the STL components. 10 10
6. Explain the types of methods to open a file. 10 10
Q1.
Ans: C++ supports a variety of data types that can be classified into several categories: basic,
derived, enumeration, and user-defined types. Each category and the specific data types within
them are described below.
2. Character Types:
• Char : Represents a single character.
• Unsigned char: Represents a character as an unsigned integer.
• Signed char: Ensures the character is treated as signed.
3. Floating-Point Types:
• Float: Represents a single-precision floating-point number.
• Double: Represents a double-precision floating-point number.
• long double: Represents an extended-precision floating-point number.
4. Boolean Types:
• Bool: Represents a Boolean value (true or false).
These are types defined by the user using structures, classes, and unions.
• Structure:
• A structure is a collection of variables of different data types under a single name.
• Class:
• A class is similar to a structure but also supports features like data encapsulation
and methods.
• Union:
• A union allows storing different data types in the same memory location.
5. Void Type
• void:
• Represents the absence of type. Used as the return type for functions that do not
return a value.
6. Null Pointer
• nullptr:
• Represents a null pointer constant, indicating that the pointer is not pointing to
any object or function.
Q. 2
Ans:
A. Do-While Statement:
• The do-while loop is a control flow statement in programming that ensures a block
of code executes at least once before the condition is tested. This type of loop is
structured with the keyword do followed by a block of code enclosed in braces,
and then the keyword while followed by the condition in parentheses. The loop's
distinctive feature is its execution process: the code block inside the do section
runs first, and only after this initial execution does the condition get evaluated. If
the condition evaluates to true, the loop continues to execute the code block
repeatedly until the condition evaluates to false. This guarantees that the code
inside the do-while loop will run at least once, even if the condition is false at the
first check.
B. While Statement:
• The while loop is one of the fundamental control flow statements in
programming, designed to execute a block of code repeatedly as long as a
specified condition remains true. The structure of a while loop begins with the
keyword while followed by the condition in parentheses and the code block to be
executed within braces. The loop evaluates the condition before entering the
code block, making it a pre-check loop. If the condition evaluates to true, the
code block is executed, and upon completion of the block, the condition is
evaluated again. This cycle continues until the condition evaluates to false, at
which point the loop terminates and the program proceeds with the next
statement following the loop.
• The while loop is particularly suited for scenarios where the number of iterations
is not predetermined and depends entirely on a condition that may change
dynamically during the execution. For instance, it is ideal for tasks like reading
data from a file until the end of the file is reached, where the exact number of
iterations is unknown. Another typical use case is in server processes that need
to run continuously until a certain stop condition is met, such as listening for
client requests. The primary advantage of the while loop is its flexibility and
ability to handle complex conditions, making it a versatile tool in a
programmer’s arsenal. However, it also requires careful management of the
condition to avoid infinite loops, which can occur if the condition never
evaluates to false. Proper initialization and updating of the condition are crucial
to ensure that the while loop functions as intended.
B. Objects:
• Definition: Instances of a class, representing specific realizations of the class's
blueprint.
• State: Each object has its own unique set of attribute values.
• Behaviour: Objects can perform actions defined by their class's methods.
• Modularity: Objects operate independently, making code more manageable and
maintainable.
• Abstraction: Encapsulates data and behaviour, hiding the implementation details
and exposing only necessary functionalities.
• Reuse: Multiple objects can be created from the same class, each with distinct
states but sharing common methods.
• Interaction: Objects can interact with other objects and perform operations based
on their state.
• Dynamic Behaviour: Methods can operate on varying data, adapting to different
scenarios during runtime.
Q.4
Ans:
An exception is an event that disrupts the normal flow of execution in a program. It
typically occurs when an error happens during runtime, such as attempting to divide by zero,
accessing invalid memory, or encountering invalid input. Exceptions are used to signal and
manage errors or unexpected situations that may arise during the execution of a program. They
offer a way to handle errors gracefully and maintain the stability of the program, rather than
allowing it to crash or behave unpredictably.
Exceptions are usually represented by objects derived from an exception class or type, and they
contain information about the nature of the error, such as error codes or descriptive messages.
Most programming languages provide built-in exception classes to represent common error
conditions, and developers can also define custom exceptions to handle specific scenarios in their
applications.
a) Try Block: Code that might throw an exception is placed inside a try block. This block is
executed normally until an exception occurs.
b) Catch Block: When an exception is thrown within the try block, control is transferred to
the corresponding catch block. The catch block contains code to handle the exception, such
as logging the error, displaying a message to the user, or attempting corrective actions.
The catch block can specify the type of exception it handles, allowing different types of
exceptions to be processed differently.
c) Finally Block: Optionally, a finally block can be used to execute code that should run
regardless of whether an exception was thrown or not. This is typically used for cleanup
operations, such as closing files or releasing resources. The finally block ensures that
necessary cleanup occurs even if an error disrupts the normal execution flow.
d) Throw Statement: In some cases, code may need to generate exceptions explicitly using
the throw statement. This allows developers to signal errors or exceptional conditions
intentionally, which can then be caught and handled by appropriate catch blocks.
e) Exception Propagation: If an exception is not caught within a try block, it propagates up
the call stack to the nearest catch block that can handle it. This process continues until the
exception is caught or reaches the top level of the program, where it may result in
program termination if unhandled.
• Error Reporting: Provides detailed information about what went wrong, which aids in
debugging and diagnosing issues. Error Reporting: Provides detailed information about
what went wrong, which aids in debugging and diagnosing issues.
• Separation of Concerns: Allows error-handling code to be separated from regular code
logic, making the code cleaner and more maintainable.
• Control Flow Management: Helps maintain the stability and reliability of the
application by managing errors and exceptional conditions effectively.
Q.5
Ans:
The Standard Template Library (STL) is a powerful feature of the C++ programming
language, providing a collection of generic classes and functions. These are implemented using
templates, enabling code reuse and efficiency. The STL is composed of four primary
components: containers, iterators, algorithms, and function objects (functors). Each component
plays a crucial role in facilitating effective and efficient programming.
Containers: Containers are data structures that store collections of objects. STL provides several
types of containers, each designed for specific use cases:
• vector: Dynamic array that allows random access and efficient resizing.
• deque: Double-ended queue supporting fast insertion and deletion at both ends.
• list: Doubly-linked list enabling fast insertion and deletion anywhere within the
list.
2. Associative Containers: These store elements in sorted order and allow fast retrieval
based on keys. Common associative containers include:
• set: Collection of unique keys, sorted by the keys.
• map: Collection of key-value pairs, sorted by the keys.
• multiset: Similar to set, but allows duplicate keys.
• multimap: Similar to map, but allows duplicate keys.
3. Unordered Containers: These store elements in an unsorted manner, using a hash table
for fast access. Common unordered containers include:
Iterators
Iterators are objects that point to elements within containers. They provide a way to access and
traverse container elements without exposing the underlying structure. Iterators can be thought of
as generalized pointers, supporting operations such as incrementing, dereferencing, and
comparison. There are several types of iterators, each with different capabilities.
3. Forward Iterators: Can read and write elements while moving forward through a cont.
Algorithms
Algorithms are a set of functions for performing operations on containers. They provide a wide
range of functionalities, such as searching, sorting, counting, manipulating, and modifying
elements. Some common algorithms include:
Q.6
Ans: The fstream> library, which provides a variety of classes and methods for opening and
manipulating files, is used to handle files in C++. Ifstream, ofstream, and fstream are the primary
classes utilized for file operations. There are a variety of ways to open files in a variety of modes
offered by each class, each of which serves a distinct purpose. We'll go over these classes and
how they open files in this section. 1. ifstream (File Input Stream) In order to read files, ifstream
is used. It is only capable of reading data from a file and is designed to handle input operations.
When you use ifstream to open a file, you make sure that the file hasn't been changed and can
only be accessed in read-only mode. Using the constructor or the open method, the ifstream
object can open a file. Utilizing constructor: std::ifstream infile("example.txt");
1. ifstream : (File Input Stream) In order to read files, ifstream is used. It is only capable of
reading data from a file and is designed to handle input operations. When you use ifstream to
open a file, you make sure that the file hasn't been changed and can only be accessed in read-
only mode. Using the constructor or the open method, the ifstream object can open a file.
Utilizing constructor: std::ifstream infile("example.txt"); Using the open approach: cpp Use
code. std::ifstream infile; infile.open("example.txt"); Modes: While the default mode is perused
just (std::ios::in), different modes can be joined if vital, for example, std::ios::binary for parallel
perusing. Std::ifstream infile("example.txt", std::ios::binary); is an example with mode. 2.
ofstream (File Stream Output) When opening files for writing, ofstream is utilized. It can only
write data to a file and handles output operations. If a file does not already exist, it is either
created or truncated (erased) when it is opened with ofstream. Using the constructor or the open
method, the ofstream object can open a file. Using the constructor, "example.txt": std::ofstream
outfile Using the open approach: cpp Use code. outfile; std::ofstream;
outfile.open("example.txt"); Modes: The default mode is compose just (std::ios::out), yet
different modes like std::ios::app (attach) and std::ios::binary can be joined. Mode-specific
example: std::ofstream outfile("example.txt," std::ios::app);
3. fstream: The File Stream The class fstream is adaptable and provides support for both input
and output operations. It permits you to open records for perusing and composing, making it
reasonable for situations where you want to perform the two sorts of activities. Using the
constructor or the open method, the fstream object can open a file. The constructor is as follows:
std::fstream file("example.txt," std::ios::in | std::ios::out); Using the open approach: cpp Use
code. file std::fstream; file.open("example.txt," std::ios::in, std::ios::out); Modes: This class
supports multiple modes, including std::ios::binary (binary mode), std::ios::in (read), std::ios::out
(write), std::ios::app (append), and std::ios::trunc (truncate). The mode-specific example is as
follows: std::fstream file("example.txt", std::ios::in | std::ios::out | std::ios::binary); Modes in
Summary std::ios::in: Readable now. std::ios::out: Available for writing (cuts the file in half).