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

Object Oriented Programming – C++ SEM 2

Object Oriented Programming – C++ SEM 2

Uploaded by

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

Object Oriented Programming – C++ SEM 2

Object Oriented Programming – C++ SEM 2

Uploaded by

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

Centre for Distance & Online Education

INTERNAL ASSIGNMENT

SET-I

Q1. Describe the various datatypes available in C++?

A data type in a programming language is a set of data with values having predefined
characteristics. C++ language supports the following data types: char, int, float, double. The
basic datatypes have various modifiers preceding them. The list of modifiers are: signed,
unsigned, long and short. C++ offers a variety of data types to represent different kinds of
information in your programs. These data types define the size and range of values a variable
can hold, along with the operations that can be performed on them. Here's a breakdown of the
key data types in C++:

Fundamental Data Types:

 Integer Types (int, short, long, long long): These store whole numbers. They come
in various sizes, with int being the most common. The size can vary depending on the
system (typically 4 bytes on 32-bit systems).
 Floating-Point Types (float, double, long double): These represent numbers with
decimal points. float offers less precision but takes less memory (usually 4 bytes)
compared to double (8 bytes) and long double (extended precision).
 Character Types (char, wchar_t, char16_t, char32_t): These store single
characters. char typically uses 1 byte and represents characters according to the
system's character encoding. wchar_t and the other wide character types can hold
larger characters like those in international alphabets.
 Boolean Type (bool): This represents logical values, true or false. It typically
occupies 1 byte.
 Void Type (void): This signifies the absence of a value. It's used in function
declarations where a function doesn't return any data.

Derived Data Types:

C++ allows you to create new data types based on existing ones. These derived data types
provide more complex ways to structure your data.

 Arrays: An array stores a fixed collection of elements of the same data type. You
access elements using an index within square brackets.

Mail id:
helpdesk@mujonline.edu.in
Phone: +91 79966 00444 (Toll
Free)
Centre for Distance & Online Education
 Pointers: These variables store memory addresses. They are powerful but require
careful handling to avoid memory-related errors.
 References: Similar to pointers, references provide an alias to an existing variable.
They offer a safer way to work with memory locations.
 Structures (struct): User-defined composite data types that group variables of
different data types under a single name.
 Classes: Similar to structures, but classes offer more features like member functions
that operate on the data within the class.

By understanding these data types and their properties, we can write C++ programs that
effectively manage data and perform operations accurately.

Data Type Size (in bytes) Values that can be taken


Signed int 2 -32768 to 32767
unsigned int 2 0 to 65535
unsigned char 1 -128 to 127
Signed Char 1 0 to 255
Float 4 3.4 X 10-38 to 3.4 X 4 3.4 X 10-38 to 3.4 X 1038
1038 (Precision 7) Doubl (Precision 7)
Double 8 1.7 X 10-308 to 1.7 X 10308
(Precision 15)
Long Double 10 3.4 X 10-4932 to 1.1 X
104932 (Precision 19)
Long Int 4 -2147483648 to 2147483647
Short Int 2 -31768 to 32767

Q2. What is the difference between the do-while and the while statements?

WHILE DO WHILE
While statement starts with a condition and Do-while is similar to while loop, except
repeats block of statements as long as the that a do--while loop body statement
condition is true. executes at least once before the condition
is tested.
In while loop the condition is checked at the In do-while loop, the condition is checked
beginning of loop therefore it is called entry - at the end of loop and so it is called exit-
Mail id:
helpdesk@mujonline.edu.in
Phone: +91 79966 00444 (Toll
Free)
Centre for Distance & Online Education
control statement. control statement
Syntax: Syntax:
while (condition) do
{ //Body of the while loop { // do-while loop body of statements
Statement1; Statement1;
Statement2; Statement2;
}Next statements after while }while (condition expression);
loop;

In the syntax shown above, if the while In the syntax given above, statement1 and
condition is true, then it executes body of the statement2 are executed, and the condition
while statement i.e. statement1 and is checked. In other words, the do-while
statement2 are executed. After execution, the loop body statement executes before the
condition is checked again. If the condition is condition. If the condition is true, then the
true, the statements inside the while loop are statements are executed again, and if the
executed again. This continues until the loop condition is false, then the control is
condition becomes false. transferred to the next statement after the
do-while statement.
The decision on whether to use while or do.. The decision on whether to use while or
while statement depends on whether the do.. while statement depends on whether
statements inside the loop have to be the statements inside the loop have to be
executed atleast once or not. If it has to be executed atleast once or not. If it is not to
executed atleast once, then the do.. while be executed atleast once, then the while
statement should be used. statement should be used.
EXAMPLE: EXAMPLE:
#include<iostream.h> #include
void main (){ int main() {
int n, i = 1, factorial = 1; int n, i = 1, factorial = 1;
cout<< "Enter a positive integer: "; cout<< "Enter a positive integer: ";
cin >> n; cin >> n;

while ( i <= n) { do{


factorial = factorial* i; factorial = factorial* i;
i++; i++;
} } while ( i <= n);
cout<<"Factorial of "<<n<<" = cout<<"Factorial of "<<n<<" =
"<<factorial; "<<factorial;
} }

Mail id:
helpdesk@mujonline.edu.in
Phone: +91 79966 00444 (Toll
Free)
Centre for Distance & Online Education
Q3. Brief about Class and Objects:

Classes provide users a way to create user defined data types. Classes provide a convenient
way to group related data and the methods that operate on data together. One advantage of
creating a class is that when you create an object from the class, you automatically create all
the related fields. Another advantage of using classes is that you can think about them and
manipulate them in the same way as you do with real-life classes. A class is a template that
units data and operations. A class is an abstraction of the real world entities with similar
properties. A class identifies a set of similar objects. A class is implementation of an abstract
data type.
General syntax of class:
class classname
{
variable declaration;
function declaration;
}
Real world entities such as, employee, vehicle, animal, etc. can be modelled by class or it can
model a user defined data type such as string, distance, etc.
Example:
class Student
{
int rollnumber;
string name;
float grade;
};
An instance of a class is known as an object of that class and is used in the program to store
data. The objects are declared in the program like the variable declaration.
Objects are mainly used for the following purposes:
1. Understanding real world and a practical base for designers
2. Decomposition of a problem into objects depends on judgment and nature of problem.
Basically an object is created from a class. The object is created by using the class name
followed by the object name. The statements shown below declare two objects of class
product. product p1; // declare p1 object of the type product
product p2; // declare p2 object of the type product
Both of the objects p1 and p2 will have their own copy of data members.
#include <iostream>

class Car {
public:
std::string brand;
std::string model;
int year;

// Simple function to display car details

Mail id:
helpdesk@mujonline.edu.in
Phone: +91 79966 00444 (Toll
Free)
Centre for Distance & Online Education
void displayDetails() {
std::cout << "Brand: " << brand << std::endl;
std::cout << "Model: " << model << std::endl;
std::cout << "Year: " << year << std::endl;
}
};

int main() {
// Create an object of the Car class
Car myCar;

// Assign values to the object's member variables


myCar.brand = "Honda";
myCar.model = "Civic";
myCar.year = 2023;

// Call the member function to display details


myCar.displayDetails();

return 0;
}
In the given example, We define a class named Car. And in the main function we create an
object of Car named myCar which allocates memory for the object.

SET-II

Q4. Define exception. Explain exception handling mechanism.

Mail id:
helpdesk@mujonline.edu.in
Phone: +91 79966 00444 (Toll
Free)
Centre for Distance & Online Education
The common types of errors which occur in our programs are – logical and syntactic errors.
The reason for logical errors is the poor understanding of the problem and solution procedure.
Syntactic errors occur due to the poor understanding of the programming language. These
errors can be detected by debugging and testing procedures. Sometimes we come across
errors other than the above mentioned ones. These errors are known as exceptions.
Exceptions are run time anomalies or unusual conditions that a program may encounter while
executing. Anomalies might include conditions such as division by zero, access to an array
outside its bounds or running out of memory or disk space. When such an exceptional
condition occurs in a program, it should be identified and handled effectively. Some built in
features are provided by C++ to detect and handle the exceptions which are basically run-
time error.
The exception handling mechanism in C++ is built upon the three keywords named as try,
throw and catch. The block of statements which generates exceptions are prefaced by the
“try” keyword. These blocks of statements are called “try block”. When, an exception is
detected, it is thrown using a throw statement in the try block. A “catch block” defined by the
keyword “catch” catches the exception thrown by the throw statement in the try block, and
handles it appropriately. When an exception is thrown by a try block, the control is
transferred to the catch block and program leaves the try block. It should be noted that the
exceptions are objects that transmit the information about a problem. If a type of object
thrown matches the arg type in the catch statement, then the catch block is executed for
handling the exception. If it doesn’t match, the program is aborted with the help of abort()
function which is invoked by default. When there is no exception then the control is
transferred to the statement immediately after the catch block i.e. the catch block is skipped.
The simple try catch mechanism is shown in the program below. #include
int main()
{
int a,b;
cout << “ Enter the values of a and b:”;
cin >> a;
cin >> b;
int x= a-b;
try
{
if(x!=0)
{
cout << “result (a/x) =” << a/x << “\n”;
}
else //there is an exception
{
throw (x); //throws int object
}
catch(int i) //catches the exception
{
cout << “exception caught : divide by zero error\n”;

Mail id:
helpdesk@mujonline.edu.in
Phone: +91 79966 00444 (Toll
Free)
Centre for Distance & Online Education
}
cout << “end”;
return 0;
}

The output of the above program will be:


First run Enter the values of a and b: 10 5
result (a/x) = 2
end
Second run
Enter the values of a and b: 5 5
exception caught: divide by zero
end

Q5. List and explain the STL components.

The three major components in STL are:


 Containers
 Algorithms
 Iterators.
These components work together to provide support to a variety of programming solutions

Containers: The containers are objects that hold data of the same type. It is a way data is
organized in memory. The STL containers are implemented by template classes, and hence,
can be customized to hold many data types. Very many container types are provided by STL
which represents objects that contain other objects. The major ones are sequence containers,
associative containers and derived containers.

Containers

Mail id:
helpdesk@mujonline.edu.in
Phone: +91 79966 00444 (Toll
Free)
Centre for Distance & Online Education

Sequence Container Associative Container Derived Container


Vector Set Stack
Queue MultiSet Queue
List Map Priority_queue
Multimap

The standard sequence containers include vector, deque and list. Data is stored in linear
sequence in sequence containers. The standard associative containers can be categorized into
set, multiset, map and multimap. Associative containers are a generalization of sequences.
Sequences are indexed by integers; associative containers can be indexed by any type. The
derived containers can be classified into three types i.e., stack, queue and priority queue.

Iterators : An iterator is an object (like a pointer) that points to an element in a container.


Iterators can be used to move through the contents of the container. Iterators can be
incremented or decremented. They connect algorithms with containers, and play an important
role in the manipulation of data stored in the container. These are: input iterators (which can
only be used to read a sequence of values), output iterators (which can only be used to write a
sequence of values), forward iterators (which can be read, written to, and moved forward),
bidirectional iterators (which are like forward iterators but can also move backwards) and
random access iterators (which can move freely any number of steps in one operation)

Algorithm: Algorithms are functions that can be used across a variety of containers for
processing their contents. The STL algorithms are template C++ functions to perform
operations on containers. Although each container provides functions for its basic operations,
more than sixty standard algorithms are provided by STL to support more extended or
complex operations. Standard algorithms also allow us to work with two different types of
containers at the same time. They take iterators that specify part or all of a container. In this
way we can use algorithms to work on entities which are not the containers. For example, we
can use the copy function to copy data from standard input into a vector. Numerous
algorithms used to perform operations such as searching and sorting are provided in the STL;
each of them is implemented to require a certain level of iterator. The algorithms include
sorting operations (sort, merge, min, max, etc.), searching operations (find, count, equal,
etc.), mutating operations (transform, replace, fill, rotate, shuffle), and generalized numeric
operations (accumulate, adjacent difference, etc.)

Function objects: The function object is a function that has been wrapped in a class so that it
looks like an object. The class would have only one member function, an overloaded()
operator and no data. This class is templatized to enable its use with different data types. It is
used as arguments to certain containers and algorithms. For example the statement sort(array,

Mail id:
helpdesk@mujonline.edu.in
Phone: +91 79966 00444 (Toll
Free)
Centre for Distance & Online Education
array+5, greater()); uses the function object greater() to sort the elements contained in array
in the descending order. It is useful in keeping and retrieving state information in functions
passed into other functions. Regular function pointers can also be used as function objects.
Function objects are STL's way of representing "executable data". For example, one of the
STL algorithms is for_each. This applies a function to each object in a container.

Q6. Explain the types of methods to open a file.

For opening a file we need to create a file stream and link it to a filename. We can define a
filename using ifstream, ofstream and fstream classes. These classes are contained in the
header file fstream. Selection of classes which we are going to use depends on the purpose,
i.e., whether you want to write data to the files or to read data from the files.
There are two ways to open a file. These are:
1. Using the constructor function of the class
2. Using the member function open() of the class.
1. Opening file using constructors:
A constructor initializes an object when it is created. Here to initialize the file stream object, a
filename is used. The following steps are required to do this: Create a file stream object to
manage the stream using appropriate class. That is, to create input stream, use ifstream class,
and use ofstream class to create output stream.
For example, the statement below opens the filename “results” for output:
ofstream outfile(“results”); //output only
The outfile is created as an ofstream object that manages the output stream. This object can
be any valid C++ name. The file ‘results’ is also opened by this statement. and this attaches it
to the output stream outfile.

iftream in file(“data”); //input only

Opening a file using open() function


The open() function can be used to open multiple files that use the same stream object. For
example, sometimes we want to process a set of files sequentially. Then we create a single
filestream object, and use it to open each file in turn. This can be done as follows:
file stream-class stream-object;
stream-object.open (“filename”);
Example:
ofstream outfile; // create stream (for output)
outfile.opne(“data1”); //connect stream to data1
………..
………….
outfile.close(); //disconnect stream from data1
outfile.open(“data2”); //connect stream to data2

Mail id:
helpdesk@mujonline.edu.in
Phone: +91 79966 00444 (Toll
Free)
Centre for Distance & Online Education
………….
………....
outfile.close();//disconnect stream from data2
…………..
………….
The above program opens two files in sequence for writing data. It is to be noted that the first
file is closed before opening the second file. This is required to be done because stream can
be connected to only one file at a time.
Sometimes it is required to use two or more files in the program simultaneously. For an
example, we may require to merge two files into a third sorted file. This means, both the
sorted files should be kept open for reading and third one should be kept open for writing. In
such cases, it is needed to create two separate input streams for handling the two input files
and one output stream for handling the output file.
The syntax of open() function that accepts two arguments is as follows:
stream-object.open(“filename”, mode);
The second argument, i.e. mode, describes the purpose for which the file is opened.

Mail id:
helpdesk@mujonline.edu.in
Phone: +91 79966 00444 (Toll
Free)

You might also like