Download as pdf or txt
Download as pdf or txt
You are on page 1of 111

SUBJECT TITLE: C++ LAB BRANCH: DCSE

SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM


38.AIM: Write a CPP program on constructor.

DESCRIPTION:

Syntax:

Default constructor

class sample{

public:

// Default constructor

sample() {

// Constructor code here

};

Parameterized constructor

class sample {

public:

// Parameterized constructor

sample(datatype parameter1, datatype parameter2, ...) {

// constructor code here

};

There are two types of constructors,they are default constructor and parameterized
constructor. A default constructor in C++ is a constructor with no parameters that is
automatically called when you create an object of a class. It has the name name as the
class and it has no return type. Parameterized constructor is also same as default
constructor but it has parameters.

SOURCE CODE:

#include <iostream>

using namespace std;

class sample {

public:

sample() {

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 101
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
cout<<"Default constructor called"<<endl;}

sample(int value) {

this->value = value;

void display() {

cout << "Value: " << value << endl;

private:

int value;

};

int main() {

sample obj1;

sample obj2(42);

obj2.display();

return 0;

SAVING: CONSTRUCTOR.CPP

EXECUTiING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 102
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
39.AIM: Write a CPP program on parameterized constructor.

DESCRIPTION:

Syntax:

class sample {

public:

// Parameterized constructor

sample(datatype parameter1, datatype parameter2, ...) {

// constructor code here

};

A parameterized constructor in C++ is a constructor that accepts one or more


parameters, allowing you to provide initial values when creating an object.

SOURCE CODE:

#include<iostream.h>

class sample

int x;

public:

sample(int a)

x=a;

void display()

cout<<endl<<"value of x is "<<x<<endl;

};

int main()

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 103
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
int abc;

cout<<"enter the value of x:";

cin>>abc;

sample s1(abc);

s1.display();

return 0;

SAVING: PARAMETERCONST.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 104
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
40.AIM: Write a CPP program on Default constructor.

DESCRIPTION:

Syntax:

class sample{

public:

// Default constructor

sample() {

// Constructor code here

};

A default constructor in C++ is a constructor with no parameters that is


automatically called when you create an object of a class. It has the name name as the
class and it has no return type.It is used to initialize member variables of the class.

SOURCE CODE:

#include<iostream.h>

class sample

public:

sample()

cout<<"Default constructor called"<<endl;

};

int main()

sample s1;

return 0;

SAVING: DEFAULTCONST.CPP

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 105
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 106
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
41.AIM: Write a CPP program on calling a constructor implicitly and explicitly.

DESCRIPTION:

A constructor can be called both implicitly and explicitly.

Syntax for Calling a constructor implicitly:

#include<iostream.h>

class class_name(parameter1,parameter 2);

Syntax for calling a constructor explicitly:

#include<iostream.h>

Class_name object_name=constructor(parametr1,parameter 2);

SOURCE CODE:

#include <iostream>

using namespace std;

class Sample {

public:

int value;

// Parameterized constructor

Sample(int val) {

value = val;

cout << "Parameterized constructor called with value: " << val << endl;

};

int main() {

// Implicit call to the parameterized constructor

Sample obj1(42);

cout << "obj1.value: " << obj1.value << endl;

// Explicit call to the parameterized constructor

Sample obj2 = Sample(55);

cout << "obj2.value: " << obj2.value << endl;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 107
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
return 0;

SAVING: IMPLICITEXPLICIT.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 108
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
42.AIM: Write a CPP program using multiple constructors.

DESCRIPTION:

The below program is written using default constructor and parameterized constructor.

Syntax:

Default constructor

class sample{

public:

// Default constructor

sample() {

// Constructor code here

};

Parameterized constructor

class sample {

public:

// Parameterized constructor

sample(datatype parameter1, datatype parameter2, ...) {

// constructor code here

};

SOURCE CODE:

#include <iostream>

using namespace std;

class Sample {

public:

int value;

// Default constructor

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 109
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
Sample() {

value = 0;

cout << "Default constructor called" << endl;

// Parameterized constructor with one integer argument

Sample(int val) {

value = val;

cout << "Parameterized constructor called with value: " << val << endl;

// Parameterized constructor with two integer arguments

Sample(int val1, int val2) {

value = val1 + val2;

cout << "Parameterized constructor called with values: " << val1 << " and " << val2
<< endl;

};

int main() {

// Create objects using different constructors

Sample obj1; // Default constructor

Sample obj2(42); // Parameterized constructor with one argument

cout << "obj2.value: " << obj2.value << endl;

Sample obj3(10, 20); // Parameterized constructor with two arguments

cout << "obj3.value: " << obj3.value << endl;

return 0;

SAVING: CONSTRUCTORS.CPP

EXECUTING: CTRL+F9

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 110
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 111
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
43.AIM: Write a CPP program on constructor overloading.

DESCRIPTION: Similar to function, it is possible to overaload constuctors. A class can


Contain more than one constructor.This is known as constructor overloading.All
constructors are defined with the same name as the class they belong to.All the
constructor contain different number of arguments. Depending upon the number of
Arguments, the compiler executes appropriate constructor.

Syntax:
class class_name
{
public:
class_name()
{ //constructor code }
class_name(variables)
{ //constructor code }
…other variables and functions
};
SOURCE CODE:

#include<iostream>

using namespace std;

class MyClass {

private:

int value;

public:

// Default constructor

MyClass() {

value = 0;

// Constructor with one integer parameter

MyClass(int val) {

value = val;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 112
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
}

// Constructor with two integer parameters

MyClass(int val1, int val2) {

value = val1 + val2;

// Display the value

void display() {

cout << "Value: " << value << endl;

};

int main()

MyClass obj1; // Calls the default constructor

MyClass obj2(5); // Calls the constructor with one parameter

MyClass obj3(3, 7); // Calls the constructor with two parameters

cout << "Object 1: ";

obj1.display();

cout << "Object 2: ";

obj2.display();

cout << "Object 3: ";

obj3.display();

return 0;

SAVING: F2 ---> FILE.CPP

EXECUTING: CTRL+F9

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 113
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 114
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
44.AIM: Write a CPP program to overload constructor using friend function.

DESCRIPTION: It is similar to constructor overloading but the funtion member contain


a key ‘friend’. In C++, you can overload constructors using friend functions, which are
functions that have access to the private and protected members of a class. This allows
you to initialize objects of a class with data from an external function that isn't a member
of the class.

Syntax:
class class_name
{
public:
class_name()
{ //constructor code }
class_name(variables)
{ //constructor code }
…other variables and functions
friend class_name(variables);
};
SOURCE CODE:

#include <iostream>

using namespace std;

class MyClass {

private:

int value;

public:

MyClass() {

value = 0;

MyClass(int val) {

value = val;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 115
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
void display() {

cout << "Value: " << value << endl;

// Declare the friend function

friend MyClass createObject(int val1, int val2);

};

// Define the friend function

MyClass createObject(int val1, int val2)

MyClass newObj;

newObj.value = val1 + val2;

return newObj;

int main()

MyClass obj1;

MyClass obj2(5);

MyClass obj3 = createObject(3, 7);

cout << "Object 1: ";

obj1.display();

cout << "Object 2: ";

obj2.display();

cout << "Object 3: ";

obj3.display();

return 0;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 116
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
SAVING: F2 ---> FILE.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 117
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
45.AIM: Write a CPP program on constructor with default arguments.

DESCRIPTION: In C++, you can create constructors with default arguments, which allows
you to initialize objects of a class with a set of default values for the constructor
parameters. This is a useful feature to make your class more flexible and user-friendly.

Syntax:
class class_name
{
public:
class_name()
{ //constructor code }
class_name(..variables , variable_name=value)
{ //constructor code }
};
SOURCE CODE:

#include <iostream>

using namespace std;

class MyClass {

private:

int value1;

int value2;

public:

// Constructor with default arguments

MyClass(int val1 = 0, int val2 = 0) {

value1 = val1;

value2 = val2;

// Display the values

void display() {

cout << "Value1: " << value1 << ", Value2: " << value2 << endl;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 118
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
}

};

int main() {

MyClass obj1; // Calls the constructor with default arguments

MyClass obj2(5); // Calls the constructor with one argument

MyClass obj3(3, 7); // Calls the constructor with two arguments

cout << "Object 1: ";

obj1.display();

cout << "Object 2: ";

obj2.display();

cout << "Object 3: ";

obj3.display();

return 0;

SAVING: F2 ---> FILE.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 119
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
46.AIM: Write a CPP program on dynamic initialization of objects.

DESCRIPTION: A class objects can be initialized dynamically. That is to say that the initial
values of an object may be provided during runtime. One advantage of dynamic
initialization is that we can provide various initialization formats using overloaded
constructors. This provides the flexiability of using different format of data at run time
depending upon the situation.

SOURCE CODE:

#include<iostream>

using namespace std;

class FD

long int pamount ;

int years;

float rate;

float return_value;

public :

FD(){}

FD(long int p,int y,float r=0.12);

FD(long int p,int y,int r);

int display()

cout<<"\n"<<"principle amount ="<<pamount<<"\n"<<"return value


="<<return_value<<"\n";

} };

FD::FD(long int p,int y,float r)

pamount=p;

years=y;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 120
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
rate=r;

return_value=pamount;

for(int i=1;i<=y;i++)

return_value=return_value*(1.0+r);

FD::FD(long int p,int y,int r)

pamount=p;

years=y;

rate=r;

return_value=pamount;

for(int i=1;i<=y;i++)

return_value=return_value*(1.0+float(r)/100);

int main()

FD f1,f2,f3;

long int p;

int y,R;

float r;

cout<<"enter amount,period ,intrest rate(in percantage)"<<"\n";

cin>>p>>y>>R;

f1=FD(p,y,R);

cout<<"enter amount,period ,intrest rate(in decimal form)"<<"\n";

cin>>p>>y>>r;

f2=FD(p,y,r);

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 121
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
cout<<"enter amount and period\n";

cin>>p>>y;

f3=FD(p,y);

cout<<"\n deposit 1";

f1.display();

cout<<"\n deposit 2";

f2.display();

cout<<"\n deposit 3";

f3.display();

return 0;

SAVING: F2 ---> FILE.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 122
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
47.AIM: Write a CPP program on copy constructor.

DESCRIPTION: A copy constructor in C++ is a special member function used to create a


new object as a copy of an existing object of the same class. This is useful when you need
to duplicate an object, whether for passing it as a function argument, returning it from a
function, or simply creating a new object that's identical to an existing one.

Syntax:
class class_name
{
public:
class_name()
{ //constructor code }
class_name(class_name & obj)
{
//obj is same class another objects
//copy constructor code
}
// …other variables and functions
};
.SOURCE CODE:

#include<iostream>

using namespace std;

class code

int id;

public:

code(){}

code(int a)

id=a;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 123
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
code(code &x)

id=x.id;

void display()

cout<<id;

};

int main()

code a(200);

code b(a);

code c=a;

code d;

d=a;

cout<<"\n id of a=";a.display();

cout<<"\n id of b=";b.display();

cout<<"\n id of c=";c.display();

cout<<"\n id of d=";d.display();

return 0;

SAVING: F2 ---> FILE.CPP

EXECUTING: CTRL+F9

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 124
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 125
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
48.AIM: Write a CPP program on dynamic constructor with using new and delete
operator.

DESCRIPTION: In C++, dynamic memory allocation is commonly used to create objects


at runtime and manage memory manually using the new and delete operators. These
operators allow you to allocate memory on the heap, which persists until explicitly
deallocated. This can be useful when you need objects with a longer lifespan than local
variables.

Syntax for new operator:

pointer_variable = new data-type;

Syntax for delete operator:

delete pointer_variable;

SOURCE CODE:

#include<iostream>

#include<string.h>

using namespace std;

class strin

char *name;

int length;

public:

strin()

length=0;

name=new char[length+1];

strin(char *s)

length=strlen(s);

name=new char[length+1];

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 126
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
strcpy(name,s);

void display()

{ cout<<name<<"\n"; }

void join(strin &a,strin &b);

};

void strin::join(strin &a,strin &b)

length=a.length+b.length;

delete name;

name=new char[length+1];

strcpy(name,a.name);

strcat(name,b.name);

int main()

char *first=" hare krishna";

strin name1(first),name2(" hare krishna"),name3(" krishna rama"),s1,s2;

s1.join(name1,name2);

s2.join(s1,name3);

name1.display();

name2.display();

name3.display();

s1.display();

s2.display();

return 0;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 127
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
SAVING: F2 ---> FILE.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 128
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
49.AIM: Write a CPP program on destructor.

DESCRIPTION: In C++, a destructor is a special member function of a class that is used


to clean up resources and perform other tasks when an object of the class goes out of
scope or is explicitly destroyed. Destructors have the same name as the class with a tilde
(~) character in front of them.

A destructor never takes any argument nor does it return any value .It will be invoked
implicitly by the complier upon exist from the program or block or function as the case
may be ,to clean up storage that is no longer accessible.

Syntax:

class class_name

public:

class_name() //constructor

~class_name() //destructor

};

SOURCE CODE:

#include<iostream>

using namespace std;

int count=0;

class alpha

public:

alpha()

count++;

cout<<"\n number of objects created "<<count;

~alpha()

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 129
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
{

cout<<"\n number of objects destroyed"<<count;

count--;

};

int main()

cout<<"\n \n enter main";

alpha a1,a2,a3,a4;

cout<<"\n \n enter block 1";

alpha a5;

cout<<"\n \n enter block2";

alpha a6;

cout<<"\n\n enter main";

return 0;

SAVING: F2 ---> FILE.CPP

EXECUTING: CTRL+F9

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 130
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 131
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
50.AIM: Write a CPP program on unary operator overloading

DESCRIPTION:

The implementation of unary operator overloading. It introduces a Counter class with an


integer member variable count to represent a simple counting mechanism. The class
defines custom functionality for incrementing and decrementing the count using the ++
and -- unary operators, along with a display() method for printing the current count value.
In the main function, the program creates an instance of the Counter class and
demonstrates the application of the unary operators, emphasizing how to modify their
behavior to manipulate the state of an object within a user-defined class.

Syntax:

class ClassName {

// class members and methods

public:

// Unary operator overloading for operator op

ReturnType operator op() {

// Code for unary operator overloading

};

SOURCE CODE:

#include <iostream>

using namespace std;

class Counter {

private:

int count;

public:

Counter() : count(0) {}

Counter(int c) : count(c) {}

void operator++() {

++count;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 132
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
}

void operator--() {

--count;

void display() {

cout << "Count: " << count << endl;

};

int main() {

Counter c1;

c1.display(); // Should print 0

++c1; // Increment the count

c1.display(); // Should print 1

--c1; // Decrement the count

c1.display(); // Should print 0

return 0;

SAVING: F2 ---> OPERATOR_OVERLOADING.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 133
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
51.Write a CPP program on unary operator overloading using friend function.

DESCRIPTION:

In this program, we have a Counter class that has an int member variable count. We define
a display method to print the current value of count. We use a friend function operator-
to overload the unary operator -. The friend function takes a Counter object as an
argument and returns a new Counter object with the negation of the count value.

In the main function, we create two instances of Counter, c1 and c2. We apply the unary
minus operator to c1 using the friend function, and then print the results using the display
method.

Syntax:

class ClassName {

private:

// class members

public:

// constructor, member functions, etc.

friend ReturnType operator@(ClassName& obj);

};

SOURCE CODE:

#include <iostream>

using namespace std;

class Counter {

private:

int count;

public:

Counter() : count(0) {}

Counter(int c) : count(c) {}

void display() {

cout << "Count: " << count << endl;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 134
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
}

friend Counter operator-(Counter& c);

};

// Friend function to overload unary operator -

Counter operator-(Counter& c) {

return Counter(-c.count);

int main() {

Counter c1(5);

Counter c2;

cout << "Initially for c1: ";

c1.display(); // Should print 5

c2 = -c1; // Applying unary minus to c1

cout << "After unary minus for c1: ";

c1.display(); // Should print 5

cout << "c2: ";

c2.display(); // Should print -5

return 0;

SAVING: F2 ---> UNARY_OPEATOR.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 135
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
52.Write a CPP program on binary operator overloading.

DESCRIPTION:

In this program, we define a Complex class that represents complex numbers with real
and imaginary parts. We overload the + operator for the Complex class to perform addition
of complex numbers. The display method is used to print the real and imaginary parts of
the complex number.

In the main function, we create three instances of the Complex class, c1, c2, and c3, and
perform the addition of two complex numbers using the overloaded + operator. The
program then prints the results to the console using the display method.

Syntax:

class ClassName {

// Class members

public:

// Constructor, member functions, etc.

ReturnType operator@(const ClassName &obj) {

// Implementation of the operator

// Usually involves operations between the current object and the passed
object

};

SOURCE CODE:

#include <iostream>

using namespace std;

class Complex {

private:

float real;

float imag;

public:

Complex() : real(0), imag(0) {}

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 136
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
Complex(float r, float i) : real(r), imag(i) {}

// Binary operator overloading for addition

Complex operator+(const Complex& c) {

Complex temp;

temp.real = real + c.real;

temp.imag = imag + c.imag;

return temp;

// Method to display complex number

void display() {

cout << "Real: " << real << " Imaginary: " << imag << endl;

};

int main() {

Complex c1(2.3, 4.5);

Complex c2(1.6, 2.8);

Complex c3;

c3 = c1 + c2; // Overloaded addition operator

cout << "c1: ";

c1.display();

cout << "c2: ";

c2.display();

cout << "Sum: ";

c3.display();

return 0;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 137
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
SAVING: F2 ---> BINARY.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 138
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
53.Write a CPP program on binary operator overloading using friend function.

DESCRIPTION:

In this program, we define a Complex class that represents complex numbers with real
and imaginary parts. We use a friend function to overload the + operator for the Complex
class to perform addition of complex numbers. The display method is used to print the
real and imaginary parts of the complex number.

In the main function, we create three instances of the Complex class, c1, c2, and c3, and
perform the addition of two complex numbers using the overloaded + operator. The
program then prints the results to the console using the display method.

Syntax:

class ClassName {

private:

// class members

public:

// constructor, member functions, etc.

friend ReturnType operator@(const ClassName& obj1, const ClassName& obj2);

};

SOURCE CODE:

#include <iostream>

using namespace std;

class Complex {

private:

float real;

float imag;

public:

Complex() : real(0), imag(0) {}

Complex(float r, float i) : real(r), imag(i) {}

// Friend function for binary operator overloading

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 139
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
friend Complex operator+(const Complex &c1, const Complex &c2);

// Method to display complex number

void display() {

cout << "Real: " << real << " Imaginary: " << imag << endl;

};

// Definition of the friend function for binary operator overloading

Complex operator+(const Complex &c1, const Complex &c2) {

Complex temp;

temp.real = c1.real + c2.real;

temp.imag = c1.imag + c2.imag;

return temp;

int main() {

Complex c1(2.3, 4.5);

Complex c2(1.6, 2.8);

Complex c3;

c3 = c1 + c2; // Using the overloaded addition operator

cout << "c1: ";

c1.display();

cout << "c2: ";

c2.display();

cout << "Sum: ";

c3.display();

return 0;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 140
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
SAVING: F2 ---> BINARY_FRIEND.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 141
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
54.Write a CPP program on overloading input and output operators.

DESCRIPTION:

In this program, we define a Complex class that represents complex numbers with real
and imaginary parts. We overload the << operator for output and the >> operator for input
using friend functions. The << operator is used to display the complex number, and the
>> operator is used to input the real and imaginary parts of the complex number.

In the main function, we create an instance of the Complex class, c1, and use the
overloaded << and >> operators to display and input the complex number respectively.

Syntax for overloading the output operator (<<):

class ClassName {

// class members

public:

// constructor, member functions, etc.

friend std::ostream& operator<<(std::ostream& out, const ClassName& obj);

};

std::ostream& operator<<(std::ostream& out, const ClassName& obj) {

// Code for output

out << obj.member; // example output

return out;

Syntax for overloading the input operator (>>):

class ClassName {

// class members

public:

// constructor, member functions, etc.

friend std::istream& operator>>(std::istream& in, ClassName& obj);

};

std::istream& operator>>(std::istream& in, ClassName& obj) {

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 142
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
// Code for input

in >> obj.member; // example input

return in;

SOURCE CODE:

#include <iostream>

using namespace std;

class Complex {

private:

float real;

float imag;

public:

Complex() : real(0), imag(0) {}

Complex(float r, float i) : real(r), imag(i) {}

friend ostream &operator<<(ostream &out, const Complex &c);

friend istream &operator>>(istream &in, Complex &c);

};

// Overloading the << operator for output

ostream &operator<<(ostream &out, const Complex &c) {

out << "Real: " << c.real << " Imaginary: " << c.imag << endl;

return out;

// Overloading the >> operator for input

istream &operator>>(istream &in, Complex &c) {

cout << "Enter Real Part: ";

in >> c.real;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 143
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
cout << "Enter Imaginary Part: ";

in >> c.imag;

return in;

int main() {

Complex c1;

cout << "Enter the complex number:" << endl;

cin >> c1;

cout << "The complex number entered is: " << endl;

cout << c1;

return 0;

SAVING: F2 ---> INPUT_OUTPUT.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 144
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
55.AIM: Write a C++ program on overloading input and output operators using friend
function.

DESCRIPTION:

1. The operator overloading function must precede with friend keyword, and declare a
function class scope.
2. Friend operator function takes two parameters in a binary operator, varies one
parameter in a unary operator
3. C++ increases the versatility of operator overloading in C++ since functions can be
overloaded as friend functions as well,
4. Friend function can access private members of a class directly

Friend return-type operator op(variable 1,Varibale2) {

//Statements;

SOURCE CODE:

#include<iostream>

#include<conio.h>

using namespace std;

const int size = 3;

class vector{

int i,v[size];

public:

vector();

vector(int *x);

friend vector operator *(int a,vector b);

friend vector operator *(vector b,int a);

friend istream & operator >> (istream &,vector &);

friend ostream & operator << (ostream &,vector &);};

vector :: vector(){

for(i=0;i<size;i++) v[i]=0; }

vector :: vector(int *x){

for(i=0;i<size;i++) v[i]=x[i];}

vector operator *(int a,vector b){

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 145
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
vector c;

int i;

for(i=0;i<size;i++)

c.v[i]=a*b.v[i];

return c;}

vector operator *(vector b, int a){

vector c;int i;

for(i=0;i<size;i++)

c.v[i]=b.v[i]*a;

return c;}

istream & operator >> (istream &din,vector &b){

int i;

for(i=0;i<size;i++)

din>>b.v[i];

return(din);}

ostream & operator << (ostream &dout,vector &b){

int i;

dout<< "("<<b.v [0];

for(i=1;i<size;i++)

dout << ","<<b.v[i];

dout<<")";

return(dout);}

int x[size]={2,4,6};

int main()

vector m; vector n=x;

cout<<"Enter elements of vector m" << "\n"; cin>>m;

cout<<"\n"; cout<<"m="<<m<<"\n";

vector p,q;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 146
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
p=2*m;

q=n*2;

cout<<"\np="<<p<<"\n";

cout<<"q="<<q<<"\n";

getch();

return 0;

SAVING: F2 ---> FILE.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 147
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
56.AIM: Write a C++ program on operator overloading using “++” operator.

DESCRIPTION:
1. The operator symbol for both prefix(++i) and postfix(i++) are the same
2. Hence, we need two different function definitions to distinguish between them.
3. This is achieved by passing a dummy int parameter in the postfix version.
4. You oyerload the prefix increment operator ++ with either a nonmember function
operator that has one argument of class type or a reference to class type, or with a
member function operator that has no arguments
5. The postfix increment operator ++ can be overloaded for a class type by declaring a
nonmember function operator operator ++ with two arguments, the first having class
type and the second having type int

SOURCE CODE:

#include<iostream>

using namespace std;

class Count

private:

int value;

public:

Count() : value(12) {}

void operator ++ ()

++value;

void operator ++ (int)

value++;

void display()

cout << "Count: " << value << endl;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 148
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
};

int main()

Count count1;

count1++;

count1.display();

++count1;

count1.display();

return 0;

SAVING: F2 ---> FILE.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 149
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
57.AIM: Write a C++ program to return a value from “++” operator.

DESCRIPTION:
1. You overload the prefix increment operator ++ with either a nonmember function
operator that has one argument of class type or a reference to class type, or with a
member function operator that has no arguments
2. The postfix increment operator ++ can be overloaded for a class type by declaring a
nonmember function operator operator++) with two arguments, the first having class
type and the second having type int
3. The postfix operator returns a copy of the value before it was incremented, so it pretty
much has to return a temporary
4. The prefix operator does return the current value of the object, so it can return a
reference to, well, its current value.

SOURCE CODE:

#include<iostream>

using namespace std;

class Count {

private:

int value;

public:

Count() : value(78) {}

Count operator ++ () {

Count temp;

temp.value = ++value;

return temp;}

Count operator ++ (int) {

Count temp;

temp.value = value++;

return temp;}

void display() {

cout << "Count: " << value << endl;}

};

int main()

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 150
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
{

Count count1, result;

result = ++count1;

result.display();

result = count1++;

result.display();

return 0;

SAVING: F2 ---> FILE1.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 151
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
58.AIM: Write a CPP program on ”=” operator.

DESCRIPTION:
1. Suppose that we wish to overload the binary operator == to compare two Point objects.
We could do it as a member function or non-member function
2. To overload as a member function, the declaration is as follows

Syntax:

class class_name {

public:

bool operator==(const classname& rhs) const; }};

Bool-hold a boolean value, true or false a boolean value, true or false

SOURCE CODE:

#include<iostream>

using namespace std;

class Distance {

private:

int feet;

int inches;

public:

Distance() {

feet = 0;

inches = 0;}

Distance(int f, int i) {

feet = f;

inches = i;}

void operator = (const Distance &D ) {

feet = D.feet;

inches = D.inches;}

void displayDistance() {

cout << "F: " << feet << " I:" << inches << endl;}

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 152
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
};

int main()

Distance D1(4,17), D2(15, 21);

cout << "First Distance : ";

D1.displayDistance();

cout << "Second Distance :";

D2.displayDistance();

D1 = D2;

cout << "First Distance :";

D1.displayDistance();

return 0;

SAVING: F2 ---> FILE2.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 153
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
59.AIM: Write a CPP program on “()” operator.

DESCRIPTION:
1. These operators can be overloaded globally or on a class-by-class basis.
2. The function call operator () can be overloaded for objects of class type
3. When you overload (), you are not creating a new way to call a function
4. Rather, you are creating an operator function that can be passed an arbitrary number
of parameters.

Syntax:

class class _name {

public:

class_name operator ()(arguments)

{ }

};

SOURCE CODE:

#include<iostream>

using namespace std;

class Distance {

private:

int feet;

int inches;

public:

Distance() {

feet = 0;

inches = 0;}

Distance(int f, int i) {

feet = f;

inches = i;}

Distance operator ()(int a,int b,int c){

Distance D;

D.feet=a+b+10;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 154
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
D.inches=b+c+100;

void displayDistance() {

cout << "F: " << feet << " I:" << inches << endl;}};

int main()

Distance D1(22,32), D2;

cout << "First Distance : ";

D1.displayDistance();

cout << "Second Distance :";

D1 = D2(10,10,10);

D2.displayDistance();

return 0;

SAVING: F2 ---> FILE.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 155
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
60.AIM: Write a CPP program on ‘<’ operator.

DESCRIPTION:

1. The operator overloading function must preceed with friend keyword, and declare a
function class scope.
2. Friend operator function takes two parameters in a binary operator, varies one
parameter in a unary operator
3. C++ increases the versatility of operator overloading in C++ since functions can be
overloaded as friend functions as well.
4. Friend function can access private members of a class directly

SOURCE CODE:

#include<iostream.h>

#include<conio.h>

class Distance{

private:

int feet;

int inches;

public :

Distance()

feet=0;

inches =0;

Distance(int f,int i){

feet =f;inches=i;

void displayDistance(){

cout<<"F:"<<feet<<"I;"<<inches<<endl;

bool operator <(const Distance& d){

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 156
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
if(feet < d.feet){

return true;

if(feet==d.feet && inches < d.inches){

return true;

return false;

};

int main(){

Distance D1(11,10),D2(5,11);

if(D1 < D2){

cout<<"D1 is less than D2"<<endl;

else

cout<<"D2 is less than D1"<<endl;

getch();

SAVING: F2 ---> FILE5.CPP

EXECUTING: CTRL+F9
OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 157
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
61.AIM: Write a CPP program on ‘<<’ and ‘>>’ operator.

DESCRIPTION:

1. C++ is able to input and gutput the built-in data types using the stream extraction
operator >> and the stream insertion operator <<.
2. The stream insertion and stream extraction operator can be overloaded to perform
input and output for user-defined types like an object.
3. It is important to make operator overloading funetion a friend of a class because it
would be called without creating an object.

SOURCE CODE:

#include <iostream>

using namespace std;

class Distance {
private:

int feet;

int inches;

public:

Distance() {

feet = 0;

inches = 0;

Distance(int f, int i) {

feet = f;

inches = i;
}

friend ostream& operator<<(ostream& output, const Distance& D) {

output << "F:" << D.feet << " I:" << D.inches;

return output;

friend istream& operator>>(istream& input, Distance& D) {

input >> D.feet >> D.inches;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 158
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
return input;

};

int main() {

Distance D1(11, 10), D2(5, 11), D3;

cout << "Enter the value of object: " << endl;

cin >> D3;

cout << "First Distance: " << D1 << endl;

cout << "Second Distance: " << D2 << endl;

cout << "Third Distance: " << D3 << endl;

return 0;

SAVING: F2 ---> FILE6.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 159
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
62.AIM: Write a CPP program on '[ ]' operator.

DESCRIPTION:

1. The subscript or array index operator is denoted by ‘[]’.


2. This operator is generally used with arrays to retrieve and manipulate the array
elements.
3. This is a binary or n-ary operator and is represented in tow parts:

1.Postfix/Primary expression 2. Expression

4. The postfix expression also known as the primary expression, is a pointer such as
array or identifiers.
5. Second expression is an integral value.

SOURCE CODE:

#include <iostream.h>

#include <conio.h>

const int SIZE = 10;

class safearay {

private:

int arr[SIZE];

public:

safearay() {

for (int i = 0; i < SIZE; i++)

arr[i] = i;

int& operator[](int i) {

if (i < 0 || i >= SIZE) {

cout << "Index out of bounds" << endl;

return arr[0]; // Return the first element by default

return arr[i];

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 160
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
}

};

int main() {

safearay A;

cout << "Value of A[2]: " << A[2] << endl;

cout << "Value of A[5]: " << A[5] << endl;

cout << "Value of A[12]: " << A[12] << endl;

getch();

return 0;

SAVING: F2 ---> FILE7.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 161
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
63.AIM: Write a CPP program to illustrate the use of get() and put() character handing
functions.

DESCRIPTION:

1. The classes istream and ostream define two member functions get() and put()
respectively to handle the single character input/output operations.
2. The get() function reads a single character from the associated stream.
3. The put() function writes to the stream and returns a reference to the stream.

SOURCE CODE:

#include <iostream.h>
#include <conio.h>
int main() {
int count = 0;
char c;
cout << "Enter characters: ";
cin.get(c);
while (c != '\n') {
cout.put(c);
count++;
cin.get(c);
}
cout << "\nNumber of characters: " << count << "\n";
getch();
}
SAVING: F2 ---> FILE6.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 162
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
64. AIM: Write a CPP program on getline() function for reading string.

DESCRIPTION:

1. The primary use case of getline() is reading from an input stream in your program.
2. The getline() function does not ignore the leading whitespace characters.
3. So special care should be taken care of about using getline() after cin because cin
ignores whitespace characters leaves it in the stream as garbage.

Syntax :

cin.getline(line,size);

SOURCE CODE:

#include <iostream.h>

#include <conio.h>

int main() {

int size = 20;

char city[20];

cout << "\nEnter city name: ";

cin >> city;

cout << "\nCity = " << city;

cout << "\nEnter city name again: ";

cin.ignore(); // Ignore the newline character from the previous input

cin.getline(city, size);

cout << "\nEnter city name: " << city;

cout << "\nEnter city name now: ";

cin.getline(city, size);

cout << "\nCity name: " << city;

getch();

return 0;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 163
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
SAVING: F2 ---> FILE8.CPP

EXECUTING: CTRL+F9
OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 164
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
65.AIM: Write a CPP program on write() function for writing string.

DESCRIPTION:

1. This binary function is used to perform file output operation i.e, to write the objects
into the file, which is stored in the computer memory in the binary form.
2. Only the data member of the object are written and not its member function.
3. It writes the data from a buffer declared by the user to a given device such as a file.
4. This is a primary way to output data from a file.

Syntax :

cout.write(line,size);

1. The first argument, line represents the name of the string to be displayed.
2. Second argument, size represents no.of characters to be displayed.

SOURCE CODE:

#include <iostream.h>

#include <string.h>

#include <conio.h>

int main() {

int i;

const char *str1 = "C++";

const char *str2 = "programming";

int m = strlen(str1);

int n = strlen(str2);

for (i = 1; i <= n; i++){

cout.write(str2, i);

cout << "\n";

for (i = n; i > 0; i--){

cout.write(str2, i);

cout << "\n";

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 165
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
}

cout.write(str1, m);

cout.write(str2, n);

cout << "\n";

getch();

return 0;

SAVING: F2 ---> FILE9.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 166
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
66.AIM: Write a CPP program on width() ios class function.

DESCRIPTION:

The `std::ostream::width` function is a member function provided by the C++ standard


library as part of the output formatting capabilities for streams. It is typically used with
output streams such as `std::cout` or `std::cerr` to control the formatting of data when it
is written to the stream.

The `std::ostream::width` function allows you to specify the minimum width of the output
field. If the data being output is narrower than the specified width, the stream will pad the
output with fill characters (by default, spaces) to reach the specified width.

You can also reset the width to its default by calling `std::ostream::width(0)`, or by using
the `std::setw(0)` manipulator.

The `width` function is particularly useful when you want to control the alignment and
padding of data in formatted output, such as when displaying tables or columns of data
in a user-friendly manner.

SOURCE CODE:

#include<iostream.h>

using namespace std;

int main()

int items[4]={10,8,12,15};

int cost[4]={75,100,60,99};

cout.width(5);

cout<<"ITEMS";

cout.width(8);

cout<<"COST";

cout.width(15);

cout<<"TOTAL VALUE"<<"\n";

int sum =0;

for(int i=0;i<4;i++)

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 167
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
{

cout.width(5);

cout<<items[i];

cout.width(8);

cout<<cost[i];

cout.width(15);

cout<<items[i]*cost[i];

sum+=items[i]*cost[i];

cout<<endl;

cout<<"\n Greand Total = ";

cout.width(2);

cout<<sum<<"\n";

return 0;

SAVING: F2 ---> FILE12.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 168
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
67.AIM: Write a CPP program on precision() ios class function.

DESCRIPTION:

The precision function is a member function of the std::ostream class that allows you to
control the formatting of floating-point numbers when they are output to the stream. It is
used in conjunction with the insertion operator (<<) to specify the number of decimal
places to be displayed for floating-point values. By default, floating-point values are
displayed with a certain level of precision (usually a few decimal places), but you can use
the precision function to override this default and specify your own precision.

Syntax:

std::ostream& precision(int n);

Parameters:

n: An integer that represents the new precision setting. It specifies the number of decimal
places to display for floating-point values. The default precision is typically set to 6.

Return Value:

The precision function returns a reference to the std::ostream object itself, which allows
for chaining multiple output manipulations.

SOURCE CODE:

#include<iostream>

#include<math.h>

using namespace std;

int main()

int a;

cout<<"pression set to 3 digits\n\n";

cout.precision(3);

cout.width(10);

cout<<"VALUE";

cout.width(15);

cout<<"SQRT_OF_VALURE\n";

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 169
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
for(int n=1;n<=5;n++)

cout.width(8);

cout<<n;

cout.width(13);

cout<<sqrt(n)<<"\n";

cout<<"\n\npression set to 5 digits\n\n";

cout.precision(5);

for(int n=1;n<=5;n++)

cout.width(8);

cout<<n;

cout.width(15);

cout<<sqrt(n)<<"\n";

cout<<"\nDefault Setting:\n";

cout.precision(0);

cout<<sqrt(10);

return 0;

SAVING: F2 ---> FILE13.CPP

EXECUTING: CTRL+F9

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 170
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 171
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
68.AIM: Write a CPP program on padding with fill().

DESCRIPTION:

In C++, the fill function is a member of the std::basic_ostream class, which serves as the
foundation for output streams like std::ostream. Its primary purpose is to control the fill
character used for padding when formatting output. Padding is a technique to ensure that
output data is displayed in fields of a specified width, and the fill character is used to
occupy any extra space.

The fill function is utilized by setting the desired fill character, often using a specific
character like '*', and is then combined with other stream manipulators, such as std::setw,
which establishes the field width. This combination enables precise control over how data
is presented. For instance:

std::cout.fill('*'); // Set the fill character to '*'

std::cout.width(10); // Set the width for padding

std::cout << "Hello" << std::endl;

In this example, we have set the fill character to '', and the width to 10. Consequently, the
string "Hello" is padded with '' characters to ensure it occupies a field of 10 characters.
The output will appear as "*****Hello."

The fill function is commonly employed when the formatting of text or data in fixed-width
fields is necessary, as it contributes to organized and neatly presented information. Its
flexibility to define the padding character makes it valuable in generating structured tables
and ensuring a consistent appearance in output displays.

SOURCE CODE:

#include<iostream>

using namespace std;

int main()

cout.fill('<');

cout.precision(3);

for(int n=1;n<=6;n++)

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 172
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
{

cout.width(5);

cout<<n;

cout.width(1);

cout<<1.0/float(n)<<"\n";

if(n==3)

cout.fill('>');

cout<<"\npaddng cahnged\n\n";

cout.fill('#');

cout.width(15);

cout<<12.3456789<<"\n" ;

return 0;

SAVING: F2 ---> FILE13.CPP


EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 173
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
69.AIM: Write a CPP program on formatting flags in setf().

DESCRIPTION:

The std::ios_base::setf function is a member function of the C++ Standard Library's


input/output stream classes, and it is used to set various formatting flags for these
streams. These flags control how data is formatted and displayed when it is read from or
written to the streams.

Syntax:

void setf(std::ios_base::fmtflags fmtflags);

Flags and bit field of setf() function

Format required Flag (arg1) Bit-field(arg2)

Left-justified output ios::left ios::adjustfield

Right-justified output ios::right ios::adjustfield

Padding afier sign or base ios:: internal ios::adjustfield

Scientific Notation ios::scientific ios::floatfield

Fixed point notation ios::fixed ios::floatfield

Decimal Base ios::dec ios::basefield

Octal Base ios::oct ios::basefield

Hexadecimal Base ios::hex ios::basefield

SOURCE CODE:

#include<iostream>

#include<math.h>

using namespace std;

int main()

cout.fill('*');

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 174
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
cout.setf(ios::left,ios::adjustfield);

cout.width(10);

cout<<"Value";

cout.setf(ios::right,ios::adjustfield);

for(int n=1;n<=10;n++)

cout.setf(ios::internal,ios::adjustfield);

cout.width(20);

cout<<sqrt(n)<<"\n";

cout.setf(ios::scientific,ios::floatfield);

cout<<"\nSQRT(100) = "<<sqrt(100)<<"\n";

return 0;

SAVING: F2 ---> FILE14.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 175
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
70.AIM: Write a CPP program on unsetf() ios class function.

DESCRIPTION:

In C++, unsetf is a member function of the std::ios_base class, used for clearing specific
formatting flags that have been set for input or output streams. This function allows you
to selectively remove one or more formatting flags previously set using the setf function,
restoring the default formatting behavior.

Here's a description of unsetf:

Syntax:

std::ios_base& unsetf(std::ios_base::fmtflags flags);

Parameters:

flags: An integer value representing the formatting flags you want to clear. It can be a
single flag or a combination of flags obtained using bitwise OR (|).

Return Value:

unsetf returns a reference to the stream object (e.g., std::ios or std::ostream) on which it
was called. This allows for method chaining.

SOURCE CODE:

#include <iostream>

#include<conio.h>

#include<iomanip.h>

using namespace std;

int main() {

int number = 42;

float p=6.67676765;

cout << "Hexadecimal (with base): ";

cout.setf(ios::hex,ios::basefield);

cout.setf(ios::right,ios::adjustfield);

cout.setf(ios::scientific,ios::adjustfield);

cout << number << endl<<p<<endl;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 176
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
cout.unsetf(ios::hex);

cout.unsetf(ios::scientific);

cout.unsetf(ios::right);

cout << "Default: " << number << endl;

return 0;

SAVING: F2 ---> FILE15.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 177
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 178
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
71.AIM: Write a CPP program on using all ios class functions & flags.

DESCRIPTION:

This program uses the following ios class functions and flags:
Functions:
width(int): Used to set the required field width.
fill(char): Used to fill the blank spaces in output with given character.
precision(int): Used to set the number of decimal points to a float value.
setf(format flags): Used to set various flags for formatting output like showbase,
showpos, oct, hex, etc.
unsetf(format flags): Used to clear the format flag setting.
Flags:
showbase: Turns on showbase flag.
showpoint: Turns on showpoint flag.
left: Left-justifies the output.
right: Right-justifies the output.
SOURCE CODE:

#include <iostream>

#include <iomanip>

using namespace std;

int main() {

// Using ios class functions

cout << "Using ios class functions:" << endl;

cout.width(10);

cout << "Hello" << endl;

cout.fill('*');

cout.width(10);

cout << "Hello" << endl;

cout.precision(4);

cout << fixed << 3.14159265358979323846 << endl;

cout.setf(ios::showpos);

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 179
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
cout << 200.0 << endl;

cout.unsetf(ios::showpos);

cout << 200.0 << endl;

// Using ios flags

cout << "\nUsing ios flags:" << endl;

cout << setiosflags(ios::showbase);

cout << hex << 100 << endl;

cout << setiosflags(ios::showpoint);

cout << fixed << 3.14159265358979323846 << endl;

cout << setiosflags(ios::left);

cout.width(10);

cout << "Hello" << endl;

cout << setiosflags(ios::right);

cout.width(10);

cout << "Hello" << endl;

return 0;

SAVING: IOS_FUNCTIONS_FLAGS.CPP

EXECUTiING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 180
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
72.AIM: Write a CPP program on manipulators.

DESCRIPTION:

Manipulators in C++ are special functions or objects that can modify the output
behavior of standard stream objects, such as cout and cin. They are used to modify the
formatting of data including field width, precision, alignment, padding, and more.
Manipulators can be applied directly to the output stream using the insertion operator
(<<) to modify the formatting of subsequent output.

This program uses the following manipulators:

setw(int): Used to set the field width in output operations.

setfill(char): Used to fill the blank spaces in output with given character.

setprecision(int): Used to set the number of decimal points to a float value.

fixed: Used to set the float value to fixed-point notation.

hex: Used to set the base of the output to hexadecimal.

oct: Used to set the base of the output to octal.

SOURCE CODE:

#include <iostream>

#include <iomanip>

using namespace std;

int main() {

int num = 123;

float pi = 3.14159265358979323846;

// Using manipulators to format output

cout << "Using manipulators:" << endl;

cout << "Num: " << setw(6) << setfill('0') << num << endl;

cout << "Pi: " << setprecision(4) << fixed << pi << endl;

cout << "Hex: " << hex << num << endl;

cout << "Oct: " << oct << num << endl;

return 0;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 181
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
SAVING: MANIPULATOR.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 182
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
73.AIM: Write a CPP program on user defined manipulators.

DESCRIPTION:

To create a user-defined manipulator in C++, we need to define a function that takes an


ostream object as an argument and returns the same object. The function should
perform the desired formatting operation on the output stream. The function can then be
used as a manipulator by inserting it into the output stream using the insertion operator
(<<).

This program defines a user-defined manipulator format that displays a float value in a
predefined format with two decimal places. The manipulator is defined as a function that
takes an ostream object as an argument and returns the same object. The manipulator
is then used to format the output of a float value.

SOURCE CODE:

#include <iostream>

#include <iomanip>

#include <ostream>

using namespace std;

// User-defined manipulator to display a float value in scientific notation

ostream& fall(ostream & output) {

output.setf(ios::showpoint);

output<< setprecision(4);

output<< setfill('#');

output.width(10);

return output;

int main() {

// Using user-defined manipulators to format output

cout << "Using user-defined manipulators:" << endl;

cout << "Num1: "<< fall << 69.663 << endl;

cout << "Num2: "<< fall << 12.2215 <<endl;

return 0;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 183
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
SAVING: DEFAULTCONST.CPP

EXECUTING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 184
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
74.AIM: Write a CPP program on creating a file.

DESCRIPTION:

To create a file in C++, we can use the ofstream or fstream class and specify the name of
the file. We can then write to the file using the insertion operator (<<).

This program creates a file named filename.txt and writes a line of text to it. The
ofstream class is used to create and open the file, and the insertion operator (<<) is used
to write to the file. The close() function is used to close the file.

SOURCE CODE:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

// Create and open a text file

ofstream MyFile("filename.txt");

// Write to the file

MyFile << "\n \tThis File is created through a program\n .";

// Close the file

MyFile.close();

return 0;

SAVING: FILECREATION.CPP

EXECUTING: CTRL+F9

FILE CONTENT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 185
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
75.AIM: Write a CPP program to read the files one after another.

DESCRIPTION:

Here the program explains about reading the files one after another. Here two text files
are created 1. state.txt and 2. capital.txt in the first text file content called Goa,
TamilNadu and Arunachal Pradesh are written by the user and in the second text file
content called Patna, Chennai and Itanagar are written by the user. And then reading
the files one after another and saving into the text files

SOURCE CODE:

#include <iostream>

#include <fstream>

using namespace std;

int main()

ifstream file1("state.txt");

ifstream file("capital.txt");

ofstream kout;

kout.open("state.txt");

kout<<"Goa";

kout<<"TamilNadu";

kout<<"Arunachal Pradhesh";

kout.close();

kout.open("capital.txt");

kout<<"Patna";

kout<<"Chennai";

kout<<"Itanagar";

kout.close();

const int size=80;

char word[size];

ifstream kin;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 186
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
kin.open("state.txt");

cout<<"Content in the state file";

while(kin)

kin.getline(word,size);

cout<<word<<endl;

kin.close();

kin.open("capital.txt");

cout<<"\nContent in the capital file"<<endl;

while(kin)

kin.getline(word,size);

coutt<<word<<endl;

kin.close();

return 0;

SAVING: READINGFILE.CPP

EXECUTING: CTRL+F9

FILE CONTENT:

STATE FILE:

CAPITAL FILE:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 187
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 188
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
76.AIM: Write a CPP program on reading two files simultaneously.

DESCRIPTION:

Two files can be read simultaneously.The function getline() reads characters from input
stream and appends it to the string object until the delimiting character is encountered.

syntax:

istream &getline(char *buf,int num,char delim=’\n’);

SOURCE CODE:

#include<iostream>

#include<fstream>

#include<stdlib.h>

using namespace std;

int main()

const int size=20;

char line[size];

ifstream fin1,fin2;

fin1.open("state.cpp");

fin2.open("capital.cpp");

for(int i=0;i<3;i++){

if(fin1.eof()!=0)

cout<<"exit from state\n";

exit(1);

fin1.getline(line,size);

cout<<"capital of "<<line;

if(fin2.eof()!=0)

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 189
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
{

cout<<"exit from capital\n";

exit(1);

fin2.getline(line,size);

cout<<"-"<<line<<endl;

return 0;

SAVING: CAPITAL.CPP

EXECUTiING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 190
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
77.AIM: Write a CPP program to perform i/o operations on file using get() and

put().

DESCRIPTION:

The functions get() and put() are byte-oriented (single character at a time ).That is, get()
will read a byte of data and put() will write a byte of data.The get has many forms,but the
most commonly used version along with put() is

istream &get(char &ch);

ostream &put(char &ch);

SOURCE CODE:

#include<iostream>

#include<fstream>

#include<string.h>

using namespace std;

int main()

int i,len;

char string[50],ch;

cout<<"enter a string: ";

cin.get(string,50);

len=strlen(string);

ofstream fout;

fout.open("info.txt",ios::out);

for(i=0;i<len;i++)

fout.put(string[i]);

cout<<"content written into file using put()\n";

fout.close();

ifstream fin;

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 191
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
fin.open("info.txt",ios::in);

cout<<"content read from the file using get():\n";

while(fin.get(ch))

cout<<ch;

fin.close();

return 0;

SAVING: I/O_MODE.CPP

EXECUTiING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 192
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
78.AIM: Write a CPP program to perform i/o operations on binary files.

DESCRIPTION:

To write blocks of binary data, we use c++’s read() and write() functions.

Their prototypes are:

istream &read((char*)&buf,int sizeof(buf));

ostream &write((char*)&buf,int sizeof(buf));

Funtion takes two arguments.The first is address of variable buf and second is the length
of the variable in bytes.

SOURCE CODE:

#include<iostream>

#include<fstream>

using namespace std;

int main()

int arr[30],i,n,a,arr2[30];

cout<<"Enter size of array";

cin>>n;

cout<<"Enter array elements";

for(i=0;i<n;i++)

cin>>arr[i];

ofstream fout;

fout.open("array.bin",ios::binary);

fout.write((char*)(arr),sizeof(arr));

fout.close();

cout<<"elements written into file\n";

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 193
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
ifstream fin;

fin.open("array.bin",ios::binary);

cout<<"reading elements from the file:\n";

fin.read((char*)arr2,sizeof(arr2));

for(i=0;i<n;i++)

cout<<arr2[i]<<" ";

fin.close();

return 0;

SAVING: BINARY_FILES.CPP

EXECUTiING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 194
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
79.AIM: Write a CPP program to read and write a class object.

DESCRIPTION:

The functions read() and write() can also be used for reading and writing class objects.

These functions handle the entire structure of an object as a single unit.

Syntax:

read((char*)&obj,sizeof(obj));

write((char*)&obj,sizeof(obj));

SOURCE CODE:

#include <iostream>

#include <fstream>

using namespace std;

const int size=50;

class Student {

public:

char name[size];

int rollNumber;

Student() {}

Student(char n[size], int rn){

for(int i=0;i<size;i++)

name[i]=n[i];

rollNumber=rn;

void display() {

cout << "Name: " << name << "\n";

cout << "Roll Number: " << rollNumber << "\n";

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 195
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
};

int main() {

char name[size];

int rll;

cout<<"enter name of the student: ";

cin.get(name,size);

cout<<"enter roll number: ";

cin>>rll;

Student student1(name,rll);

ofstream outFile;

outFile.open("student.dat", ios::out);

outFile.write((char*)(&student1), sizeof(Student));

outFile.close();

cout << "Student object written to file.\n";

Student student2;

ifstream inFile;

inFile.open("student.dat", ios::in);

inFile.read((char*)(&student2), sizeof(Student));

inFile.close();

cout << "Student object read from file:\n";

student2.display();

return 0;

SAVING: FILEMODE.CPP

EXECUTiING: CTRL+F9

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 196
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 197
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
80.AIM: Write a CPP program on all file modes.

DESCRIPTION:

File can be opened using various modes.The mode can combine two or more parameters

using the bitwise OR operator (symbol |).

Syntax:

stream_obj.open(“file_name.ext”,mode);

SOURCE CODE:

#include<iostream>

#include<fstream>

using namespace std;

int main()

char line[50];

ifstream fin;

fin.open("text.cpp",ios::ate);

cout<<"file pointer is at "<<fin.tellg()<<"(ios::ate)"<<endl;

fin.close();

fin.open("text.cpp",ios::in);

fin.getline(line,50);

cout<<"content of file using (ios::in)\n"<<line<<endl;

fin.close();

ofstream fout;

fout.open("text.cpp",ios::trunc|ios::out);

cout<<"deleted content(ios::trunc)"<<endl;

fout<<"HELLO PROGRAMMER :)"<<endl;

fout.close();

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 198
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
fin.open("text.cpp",ios::in);

fin.getline(line,50);

cout<<"new content added to file using (ios::out)\n"<<line<<endl;

fin.close();

fout.open("text.cpp",ios::out|ios::nocreate);

cout<<"opened file using (ios::nocreate)\n";

fout.close();

fout.open("text.cpp",ios::noreplace);

fin.getline(line,50);

cout<<"opening of file failed as file already exits(ios::noreplace)";

cout<<line<<endl;

fout.close();

fin.close();

return 0;

SAVING: FILEMODE.CPP

EXECUTiING: CTRL+F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 199
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
81.AIM: Write a CPP program on updating a file (random access).

DESCRIPTION:

Random access of files in C++ refers to the ability to directly access and modify specific
locations within a file, rather than just reading or writing sequentially from the beginning
to the end. It allows you to efficiently work with large files or update specific portions of a
file without processing the entire file. Random access is especially useful for tasks like
updating records in a database file, managing binary data, or implementing custom file
formats.
Here are some key points about random access of files in C++:
File Opening Modes:

To perform random access, you need to open the file in both input (std::ios::in) and output
(std::ios::out) modes using an std::fstream object. This combination enables both reading
and writing within the same file.

File Pointer Control:

C++ provides functions like seekp() and seekg() for controlling the file pointer. These
functions allow you to move the file pointer to a specific position within the file. For
example, you can set the position based on a byte offset from the beginning of the file or
the end of the file.

Reading and Writing at Arbitrary Positions:

With random access, you can read or write data at any location within the file. This means
you can overwrite or update existing data, append new data, or insert data at specific
positions.

Efficiency:

Random access can be more efficient than reading the entire file sequentially when you
only need to modify or retrieve a small portion of the data. It can save both time and
system resources.

Binary Data Handling:

Random access is commonly used when working with binary files that store complex data
structures or custom file formats. You can directly access and manipulate binary data
within the file.

Syntax:

seekp(offset,reference_position);

tellp();

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 200
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
SOURCE CODE:

#include<iostream>

#include<fstream>

#include<cstring>

using namespace std;

int main()

char ch[150],str;

int i,pos,length,len;

cout<<"\n enter a string=";

cin.get(ch,150);

length=strlen(ch);

fstream file;

file.open("text.cpp",ios::out|ios::trunc);

for(i=0;i<length;i++)

file.put(ch[i]);

cout<<"\n current position of the pointer in the file="<<file.tellp();

file.seekp(-5,ios::end);

cout<<"\n position ="<<file.tellp()<<endl;

file<<"hardware";

file.close();

ifstream file1;

file1.open("text.cpp");

cout<<"\n position ="<<file1.tellg();

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 201
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
cout<<"\n position after moving the pointer =";

file1.seekg(5,ios::beg);

cout<<"\n position="<<file1.tellg();

while(file1)

file1.get(str);

if(file1.eof())

break;

cout<<str<<endl;

file1.close();

return 0;

SAVING: F2 --> RANDOM.CPP

EXECUTING: CTRL + F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 202
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
FILE CONTENT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 203
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
82.AIM: Write a CPP program on manipulation of file pointer.

DESCRIPTION:

In C++, file pointer manipulation is a fundamental aspect of working with files. File
pointers are used to navigate and read or write data within a file. Here's a brief description
of how file pointer manipulation works in C++.File pointer manipulation is essential for
various file operations, such as reading and writing data at specific locations, appending
to existing files, or updating file contents. Proper handling of file pointers helps you control
the flow of data in your file operations.

Syntax:

seekg(offset,reference_position);

seekp(offset,reference_position);

tellg();

tellp();

SOURCE CODE:

#include<iostream>

#include<fstream>

#include<cstring>

using namespace std;

int main()

char ch[100];

int i,pos,length;

cout<<"\n enter a string=";

cin.get(ch,100);

length=strlen(ch);

fstream file;

file.open("text.cpp",ios::in|ios::out|ios::trunc);

for(i=0;i<length;i++)

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 204
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
{

file.put(ch[i]);

cout<<"\n current position of the pointer in the file=";

file.tellg();

cout<<"\n specify the position to change the file pointer=";

cin>>pos;

file.seekg(pos,ios::beg);

cout<<"\n the position of file pointer is=";

file.tellg();

file.getline(ch,50);

cout<<ch<<endl;

file.close();

return 0;

SAVING: F2 --> FILE_POINTER.CPP

EXECUTING: CTRL + F9

OUTPUT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 205
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
FILE CONTENT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 206
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
83.AIM: Write a CPP program on all seek actions.

DESCRIPTION:

In C++, the seekg and seekp functions are used to set the cursor position within a file.
These functions are typically used with file stream objects (ifstream and ofstream) for input
and output operations, respectively. Here's a description of seek actions in C++:

seekg for Input Streams:

seekg stands for "seek get" and is used with input file streams (e.g., ifstream).

It allows you to set the position of the file cursor for reading (getting) data from a file.

The seekg function takes two arguments: an offset and a seek direction (from the current
position, from the beginning, or from the end).

Common seek directions include:

Syntax:

ios::beg (beginning): Seek from the beginning of the file.

ios::cur (current): Seek from the current position.

ios::end (end): Seek from the end of the file.

The tellg function can be used to determine the current cursor position within the file.

SOURCE CODE:

#include <iostream>

#include <fstream>

#include <cstring>

using namespace std;

int main() {

char str[80];

cout << "\nEnter the string: ";

cin.getline(str, 80);

int len = strlen(str);

ofstream file1("hello.cpp");

if (!file1) {

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 207
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
cout << "Error opening file1" << endl;

return 1;

for (int i = 0; i < len; i++) {

file1.put(str[i]);

file1.close();

ifstream file("hello.cpp");

if (!file) {

cout << "Error opening file" << endl;

return 1;

file.seekg(0, ios::beg);

cout << "Position after seeking to the beginning: " << file.tellg() << endl;

file.seekg(4, ios::cur);

cout << "Position after seeking forward by 4 characters: " << file.tellg() << endl;

file.seekg(0, ios::cur);

cout << "Position after seeking 0 characters: " << file.tellg() << endl;

file.seekg(-1, ios::cur);

cout << "Position after seeking back by 1 character: " << file.tellg() << endl;

file.seekg(0, ios::end);

cout << "Position after seeking to the end: " << file.tellg() << endl;

file.seekg(-3, ios::end);

cout << "Position after seeking back by 3 characters from the end: " << file.tellg()
<< endl;

file.close();

return 0; }

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 208
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
SAVING: F2 --> SEEK_ACTIONS.CPP

EXECUTING: CTRL + F9

OUTPUT:

FILE CONTENT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 209
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
84.AIM: Write a CPP program on sequential access of a file.

DESCRIPTION: Sequential access of a file in C++ involves reading or writing data in a


linear, sequential order, one item after another. It means that you access the file
sequentially from the beginning to the end, and you cannot skip directly to a specific
location within the file as you would with random access.

SOURCE CODE:

#include <iostream.h>

#include <fstream.h>

#include<string.h>

#include<conio.h>

int main()

char string[100], c;

int i, length;

clrscr();

cout << "\nEnter a string: ";

cin.get(string, 100);

length = strlen(string);

fstream file;

file.open("cme.txt", ios::out | ios::app|ios::trunc);

cout<<”\n successfully opened the file“;

for (i = 0; i < length; i++)

file.put(string[i]);

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 210
SUBJECT TITLE: C++ LAB BRANCH: DCSE
SUBJECT CODE: CS-307 YEAR/SEM: IInd YEAR 3rd SEM
}

file.close();

file.open("cme.txt", ios::in);

while (file.get(c)) // Read characters from the file

cout << c;

file.close();

getch();

return 0;

SAVING: F2 --> SEQUENTIONAL_ACCESS.CPP

EXECUTING: CTRL + F9

OUTPUT:

FILE CONTENT:

NAME: N.P.SRIKANTH VARMA PIN: 22001-CS-121


SUBJECT EXPERT: R.BHARAT KUMAR L - CME PAGE NO: 211

You might also like