0% found this document useful (0 votes)
18 views10 pages

OOP C++ Assignment

The document provides an overview of various data types in C++, including user-defined, derived, and built-in types. It discusses control structures like while and do-while loops, highlighting their differences, and explains the concepts of classes and objects in object-oriented programming. Additionally, it covers exception handling mechanisms in C++ and outlines the components of the Standard Template Library (STL), including containers, algorithms, iterators, and functors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views10 pages

OOP C++ Assignment

The document provides an overview of various data types in C++, including user-defined, derived, and built-in types. It discusses control structures like while and do-while loops, highlighting their differences, and explains the concepts of classes and objects in object-oriented programming. Additionally, it covers exception handling mechanisms in C++ and outlines the components of the Standard Template Library (STL), including containers, algorithms, iterators, and functors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

NAME VAISHNAVI SANTOSH JAYMALI

ROLL NO. 2314506748

PROGRAM BACHELOR OF COMPUTER APPLICATION

SEMESTER II

COURSE NAME OBJECT ORIENTED PROGRAMMING- C++

COURSE CODE DCA-1203

SET – (I)
Question No.
1. Describe the various data types available in c++ ?
ANS.
A number of data types are available in C++, a statically-typed general-purpose programming
language, to handle various forms of data. These data types fall into three general categories: user-
defined, derived, and built-in (primitive).
❖ User defined data types
1. Structure
• used to unify many variable types under a common name.
• syntax: struct StructureName {
type1 member1;
type2 member2; // ...};
2. Classes
• Like structures, but with private, restricted, and public access controls.
• class ClassName {
private:
type1 member1;
type2 member2; // ...
public: // Member functions};
3. Unions
• Like structures, but with every member having the same address in memory.
• union UnionName {
type1 member1;
type2 member2; // ...};
4. Enumerations
• used to define a variable to which one of several preset values can be assigned.
• enum EnumName { value1, value2, value3 };
❖ Derived data types
1. Arrays
• a group of identically typed components kept in close proximity in memory.
• syntax : type arrayName[arraySize];
2. Pointers
• Variables that hold another variable's address.
• type* pointerName; is the syntax.
3. References
• Another variable's alias.
• Syntax is the type&referenceName = existingvariable;
4. Function type
• Show functions that may take parameters and return a particular type.
• returnType functionName(parameterType1, parameterType2) is the syntax used.

❖ Built in data types


1. integer types
• int: The most used integer type is int. Generally, the size is 4 bytes, however the system
may have other requirements.
• short int: Smaller integer type Typically, 2 bytes in size.
• Long int: Usually 4 or 8 bytes in size, a bigger integer type.
• long int: Typically 8 bytes for even larger integer values.
• Unsigned copies: These include unsigned int, unsigned short int, unsigned long int, and
unsigned long long int; they are for non-negative numbers.
2. floating point types
• float: A single, four-byte precision floating-point type.
• double: Usually 8 bytes in size, double precision floating-point type.
• Long double: Extended precision floating-point type; typically comes in sizes of 8, 12, or
16 bytes, however they can vary.
3. character type
• char: A single character, usually one byte, is stored here.
• wchar_t: Depending on the system, two or four bytes are often used for wide characters.
• char16_t: For characters encoded in UTF-16.
• char32_t: For characters encoded in UTF-32.
4. Boolean type
• bool: Denotes values that are true or false. Typically, it is one byte.
Question No.
2. What is the difference between the do-while and the while statement?
ANS.
The distinctions in programming between while and do-while loops. These basic control structures,
known as loops, are used to repeatedly run a code block in response to a specified condition. The
sequence of execution and the timing of the condition evaluation are where they diverge most from
one another. This is a thorough explanation:
❖ While loop
1. Structure:
Syntax: while (condition) {
// Code to execute };
2. Behaviour:
• First Condition: Prior to running the code block, the while loop verifies the condition.
• Entry-Controlled Loop: If the condition is initially false, the loop may not execute at all
because it evaluates the condition first.
3. Flow:
• Assess the situation.
• Run the code block if the condition is true.
• Continue doing this until the condition is no longer true.
❖ Do While loop
1. Structure:
Syntax: do {
// Code to execute
} while (condition);
2. Behaviour:
• Code First: Before examining the condition, the do-while loop runs the code block.
• Exit-Controlled Loop: Regardless of whether the condition is originally true or not, the loop
will always execute at least once since the code block is executed before the condition is
evaluated.
3. Flow:
• Run the code block.
• Assess the situation.
• Proceed again if the condition is met.
• Keep on until the condition is no longer true.

THE PRIMARY DISTINCTION BETWEEN C & C++.


Whereas C++ has a bottom-up approach, C follows a top-down strategy.
Character constants in C are immediately raised to integers, but this isn't the case with C++.
Identifiers in C++ are prohibited from having two or more consecutive underscores in any place. C
identifiers may have underscores in other places, but they cannot begin with two or more consecutive
underscores.
In C++, we are not required to write a return statement for an int main(); but, in C, if we use an int
main (), we must write a return statement.
In C, functions are included to carry out procedures, and input/output is reliant on library files. Input
and Output (I/O) instructions are created using the C++ console commands "cin" and "cout."
Undeclared functions are prohibited in C++. Although functions in C can be declared at the moment
of use, in C++ a function must have a prototype defined before the main().
The behaviour of C++ structures differs from that of C structures.
In C, we are unable to declare the structure's variable immediately after the structure ends, unlike in
C++, after creating structures and enumerators.
IMPORTANT DISTINCTION
➢ Initial Condition Check:
• While: Prior to the loop body executing, the condition is checked. Should the starting condition
be false, the body of the loop might never run.
• Do-While: Before the condition is checked, the loop body runs once. This ensures that the body
of the loop runs at least once.
➢ Application Situations:
• While: Employed in situations where the loop may not need to run if the original condition is not
met.
• Do-While: Use the do-while operator when the loop needs to run at least once, regardless of the
circumstance.
➢ Readability and Goals:
• While: Clearly states that the condition must be true from the beginning for the loop to be
executed.
• Do-While: Makes it apparent that before the condition is tested, the loop must execute at least
once.
Question No.
3. Brief about the class and objects.
ANS.
Fundamental ideas in object-oriented programming (OOP) are classes and objects. They offer a
methodical approach to managing and organising behaviour and data within a programme.
❖ CLASS:
➢ A class is an object creation blueprint or template. It specifies a collection of properties and
functions that the generated objects—class instances—will possess.
➢ Key points:
• Attributes: Fields or Properties are variables that hold information about the object. They
specify the object's status.
• Methods: These are the functions defined inside a class that specify how the objects
created from the class should behave.
➢ Example:
• class Car { public:
// Attributes: std::string brand; std::string model; int year;
// Methods: void displayInfo() {
std::cout \\ "Brand: " \\ brand \\ "Model: " \\ model \\ "Year: " \\ year \\ std::endl; }
};
• The class "Car" in this example has one method (displayInfo) and three attributes (brand,
model, and year).
❖ OBJECTS:
➢ An instance of a class is called an object. It is constructed using the class's defined structure and
is capable of utilising its methods and properties.
➢ Key points:
• Encapsulation:
o Bundling data (attributes) and methods that work with the data into a single unit, or class,
is known as encapsulation.
o Through the use of access specifiers (private, protected, and public), it limits direct access
to a portion of the object's components.
• Inheritance:
o A class (derived class) can inherit properties and methods from another class (base class)
through inheritance.
o encourages the reuse of code and creates a logical structure.
• Polymorphism:
o This property of methods enables them to do diverse actions depending on the object they
are acting upon.
o Usually, overloading and overriding methods are used to implement it.
• Abstraction:
o Abstraction is the process of just displaying an object's essential features while
concealing its intricate implementation details.
o It lessens the labour and complexity of programming.
➢ Example:
• int main() {
// Constructing a Car class object, Car myCar;
// setting attributes
myCar.model = "Hundai"; myCar.year = 2018; myCar.brand = "Tata";
// using methods myCar.displayInfo();
return 0;}
• In this case, myCar is a Car class object. The displayInfo method is called to print the
details of the automobile when the attributes have been assigned values.

Advantages of Using Objects and Classes


• Modularity: Individual classes allow for the independent writing and maintenance of code.
• Reusability: Code reuse is encouraged by the fact that a class can be used to construct
numerous objects after it has been written.
• Scalability: The programme can be easily expanded by adding additional objects and classes.
• Maintainability: Facilitates code management and debugging.

SET – (II)
Question No.
4. Define exception. Define exception handling mechanism.
ANS.
➢ Exception: An event that interferes with a program's usual execution flow is called an exception.
Errors such as faulty input, unavailable resources, or other unforeseen circumstances are typically the
cause. The programme may respond to these fault scenarios without crashing suddenly thanks to
exceptions, which offer a mechanism to treat them gently.
➢ Exception handling mechanism: A method for identifying, managing, and recovering from
exceptions is called exception handling. This method in C++ enables you to create programmes that
are more resilient and fault-tolerant. To handle exceptions, a number of keywords and structures are
used:
1. Try: A code segment that allows for exceptions. It has code that has the potential to throw an
exception.
2. Catch: A section of code meant to manage exceptions. The exceptions thrown by the try block are
caught and handled by it.
3. Throw: Indicates the presence of an incorrect condition by throwing an exception.
Exception handling in C++
Basic syntax:
try {
catch (exception_type1 e1)
catch (exception_type2 e2)
}
Let's look at an example where a division by zero exception is handled.
#include <iostream>
#include <stdexcept>
double divide(int numerator, int denominator) {
if (denominator == 0) {
throw std::runtime_error("Division by zero error"); }
return static_cast<double>(numerator) / denominator; }
int main() {
int num1, num2;
std::cout << "Enter two integers: ";
std::cin >> num1 >> num2;
try {
double result = divide(num1, num2);
std::cout << "Result: " << result << std::endl; }
catch (const std::runtime_error &e) {
std::cerr << "Error: " << e.what() << std::endl; }
return 0;}
In this example
• The main function consists of a try block that executes the divide function;
• If an exception is produced, the catch block catches it and outputs an error message.
• The divide function checks if the denominator is zero and throws a runtime error if it is.
1. Making Exceptions:
• To indicate the occurrence of an exceptional condition, use the throw keyword.
2. Exceptions for Catching:
• To define a block of code that handles the exception, use the catch keyword.
• Exceptions can be caught using a value, reference, or pointer.
3. Several Catch Blocks:
• To handle various kinds of exceptions, you can have more than one catch block.
4. Custom Exceptions:
• By deriving from std::exception or any of its derived classes, you can define your own exception
classes.
5. Standard Exceptions:
• A standard library of exceptions described in is provided by C++.
• std::runtime_error, std::logic_error, std::out_of_range, and other exceptions are frequently
encountered.
Advantages of Exceptional Management
Error Detection: Offers a transparent method for identifying errors as soon as they happen.
Error-Handling Code Separation: This makes the programme easier to comprehend and maintain by
separating the error-handling code from the primary logic.
Resource management: Assures that resources, such as file handles and memory, are appropriately
relinquished in the event of a mistake.
Sturdy Programmes: Increases the program's stability and dependability by offering an organised
method for managing unforeseen circumstances.

C++'s sophisticated exception handling functionality enables programmers to handle mistakes and
exceptional conditions in an organised and effective way. Try, catch, and throw are useful programming
constructs that help you create resilient and fault-tolerant applications that can manage unforeseen
circumstances with grace.

Question No.
5. List and explain the STL components.
ANS.
A robust library that offers a collection of common classes and methods for data structures and
algorithms is the Standard Template Library (STL) in C++. Four general categories can be used to
group STL components: containers, algorithms, iterators, and functors. An outline of each part and
its function in the STL is provided below:
1. Container
Data structures called containers are used to hold groups of items. They offer member functions to
access and manipulate the components, and they oversee the storage area for their elements.
Container Types:
➢ Order Containers: Preserve the elements' order.
• vector: An elastic array with self-adjusting dimensions.
• deque: A double-ended queue with two possible endpoints for insertion and deletion.
• list: A bidirectionally traversable double linked list.
➢ Associative Containers: To arrange and control the elements, use keys.
• set: A group of distinct components arranged according to value.
• Multisets: Multisets enable duplicate elements and are similar to sets.
• map: An enumeration of distinct key-value pairs arranged according to their keys.
• multimap: A map-like structure that permits duplicate keys.
➢ Unordered Containers: The elements should not be kept in order.
• Unordered set: A grouping of distinct components without a set hierarchy.
Identical to an unordered_set, but allowing duplicate elements is the unsegmented_multiset.
• Unordered_map: An arbitrary set of key-value pairings with a single key in each pair.
• Unsorted_multimap: This type of map resembles an unordered_map but permits duplicate keys.
➢ Container Adapters: Adjust the current containers' interface.
• stack: Modifies a container to allow access based on Last In First Out (LIFO).
• queue: Modifies a container so that access is granted FIFO (First In First Out).
• priority_queue: Modifies a container to enable access based on priority, accessing the element
with the highest priority first.
2. Algorithm
A set of functions for carrying out operations on containers are called algorithms, and they can be
used to do a variety of tasks, such as sorting, counting, searching, and modifying items.
common algorithms
➢ Sequence operations that do not modify: Don't change the container's contents.
• For each: A function is applied to a set of elements.
• find: Locates a value's first instance within a range.
• count: Counts how many times a value appears inside a range.
➢ Changing the way sequence operations are performed: Modify the container's contents.
• copy: Transfers elements between ranges.
• transform: Gives each element a function, then saves the outcome.
• replace: Changes a value's occurrences to another value.
➢ Sorting and associated processes:
• sort: Assigns items to a higher or lower order.
• stable_sort: Arranges items in a way that maintains their relative order.
• partial_sort: Sorts the range's first section.
➢ Operational sets:
• Combines two sorted ranges into one.
• comprises: determines whether every element in one sorted range is present in another sorted
range.
• set_union: Determines how two sorted ranges are united.
3. Iterators:
Iterators offer a method of sequentially accessing container elements without disclosing the
underlying representation. They traverse containers and serve as pointers.
➢ Different Iterator Types:
• Single-pass, read-only input iterators are available.
• Single-pass, write-only output iterators.
• Forward Iterators: Multi-pass, read/write access.
• Bidirectional Iterators: traversing both forward and backward.
• Random Access Iterators: Like pointers, they provide direct access to any element.
4. Functors (function objects):
Class instances that override the operator() are called functors, and they are objects that can be used
as if they were functions or function pointers.
➢ Functor Use:
• State can be stored by functors.
• Algorithms may accept them as arguments.
• They have the ability to encapsulate tasks that must be completed on container items.

A complete framework for interacting with data structures and carrying out different operations on them is
offered by the STL components, which include containers, algorithms, iterators, and functors. These
elements are a potent tool for C++ programmers since they are made to be adaptable, effective, and simple
to utilise.
Question No.
6. Explain a type of methods to open a file.
ANS.
The header's Standard Library classes in C++ can be used to open and edit files. These classes are
fstream (file stream for both input and output), ofstream (output file stream), and ifstream (input file
stream). Using the class constructors and the open member function are the two main ways to open a
file. You can choose how the file should be opened with flexibility using either of these approaches.
1. Using the ‘open’ member function:
One flexible method for opening files is the open member function. Objects with the types ifstream,
ofstream, and fstream can be used with this function. The file name and mode in which the file shall
be opened can be specified.
void open(const char* filename, ios_base::openmode mode = ios_base::in | ios_base::out);
➢ Modes of File Opening:
• std::ios::in: By default, ifstream opens for reading.
• std::ios::out: By default, ofstream is open for writing.
• Std::ios::binary: In binary mode, open.
• Std::ios::app: All output procedures are carried out at the end of the file; it is open for
appending.
• Std::ios::ate: Open the file right away and work your way through it.
• std::ios::trunc: The file's contents are shortened if it already exists.
• Std::ios::in Std::ios::out: Both reading and writing are allowed (fstream default)
➢ Ifstream constructor
• The following sentence adds infile to the data for reading (input) and declares it as an
ifstream object.
• Iftream in file("data"); // only input
The programme may contain the following statements:
outfile\\ "total"; outfile\\ sum; infile\\ number; infile \\ string;
• #includeiostream.h> #includefstream.h>
// Programme to create file with one constructor
{ofstream outf(" file1"); int main(); // joins ifile1 and outf
cout\\ "Type the item name here:";
char name[30];
// copy the name from the keyboard to the file called file1.

cin>> name;
float cost; outf \\ name
\\ "\n"; cout \\ "Enter item cost:"; cin>>
// connect file named file1 to inf inf >> name;
// read name from file1 inf >> cost;
// write to file file1 outf.close();
// disconnect file named file1 from outf ifstream inf("file1");
// input the value of cost outf \\ cost \\ "\n";
"" is output by cout; "Item name:" is output by cout; "Item cost:" is output by cout;
inf.close(); //disconnect file named file1 from inf
return 0;}
➢ ofstream constructor
• To manage the stream using the appropriate class, create a file stream object.
• In other words, utilise ofstream classes to build the input and output streams, respectively.
• First, initialise the object with any chosen filename.
• The following statement, for instance, opens the filename "results" for output:
outfile("results"); ofstream; //only output
• The output stream is managed by the outfile, which is constructed as an ofstream object.
• You can use any acceptable C++ name as this object. This statement also opens the "results"
file. and attaching it to the output stream outfile as a result

2. Using open function:


• You can use the open() function to open multiple files that share a stream object. For instance,
there are situations where we wish to process a group of files in order.
• Next, we make a single filestream object and open each file one at a time using it. Here is how
• this can be accomplished:
file: stream-object;
stream-object.open ("filename"); this;
For instance, ofstream outfile; // construct stream
outfile.open("data1"); //connect stream to data1.
The stream is disconnected from data1 by calling outfile.close().
open("data2"); outfile.open; //connect stream to data2
.................
outfile.close(); /disconnect stream from data2...
• The following methods can also be used to open the files:
The programme that follows demonstrates how to handle numerous files.
//Using the open() function to create files
Include
#include
int main () {
ofstream fout; //create output stream object
fout.open(“country”); //connect “country” to it
fout<<"india \n";

fout<<"USA \n";
fout<<"UK \n";
fout.close(); //disconnect "country"
fout.open("capital"); //disconnect "capital";
fout.<<"DELHI\n";

fout<<"WASHINGTON\n";
fout<<"LONDON\n";
four.close();
cons tint N=80; // line size
char line[N];
ifstream fin;
fin.open("country"); //join "country" with it

cout {\"contents of country file\n";


while(fin) //verify file end {
fin.close(line,N); //read a line
cout {\ line; //display it }
fin.close();
fin.open("capital");
cout <<"\n contents of capital file \n";
while()fin {
fin.getline( line, N);
cout<< lie; }
fin.close ();
return 0: }
The open member function or the class constructors of ifstream, ofstream, and fstream can be used to open
files in C++ OOP. You can choose which mode to open the file in, including read, write, append, and binary
modes, using one of the two approaches. Comprehending these techniques is essential for proficient file
management and adjustment, facilitating strong and effective input/output functions in C++ applications.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy