You are on page 1of 60

All C++ Programs

 001. Write a program to print a string in C language

#include <iostream>
using namespace std;

// program begins from here


int main() {
cout << "www.kodegod.com"; // prints www.kodegod.com
return 0;
}

 002. Commenting in c++

#include <iostream>
using namespace std;

// program begins from here


int main() {
/*
This is a multiline comment.
Hence here is another line commented.
*/
cout << "www.kodegod.com"; // prints www.kodegod.com

return 0;
}

 003. Enums

#include <iostream>
using namespace std;

//program begines from here


int main() {

/*
typedef type newname;
typedef int wheels;
wheels carwheels;
car_wheels = 4;

sizeof(float);
sizeof(car_wheels);
sizeof(days);
*/

/* syntax */
enum enum_name { list of names } variable_list;

/* example 1 */
enum gender {
female, // 0
male // 1
}G1;

gender G2;
G1 = female;
G2 = male;

/* example 2 */
enum fruits
{
apple, // 3
banana = 4, // 4
orange // 5
};
}

 004. Write a program to accept values of two numbers and print their multiplication in C language

#include <iostream>
using namespace std;

int i;
int print_extern();

int main() {
i = 10;
print_extern();
}

 005. Extern

#include <iostream>
using namespace std;

extern int i;

void print_extern()
{
cout << i << endl;
}

 006. Using Class

#include <iostream>
using namespace std;

class vehicle{
public:
int total_wheels;
float mileage;
};

int main(int argc, char const *argv[])


{
/* code */

vehicle v1,v2;

v1.total_wheels = 4;
v1.mileage = 110;

v2.total_wheels = 2;
v2.mileage = 80;

cout << v1.total_wheels << " wheeler with " << v1.mileage << " mileage" << endl;
cout << v2.total_wheels << " wheeler with " << v2.mileage << " mileage" << endl;

return 0;
}
 007. Scope resolution operator

#include<iostream>
using namespace std;

int x = 10;

int main()
{
int x = 20;
cout << "Global x = " << ::x;
cout << "\nLocal x = " << x;
return 0;
}

 008. Inline member functions

#include<iostream>
using namespace std;

class X
{
public:
void foo()
{
cout << "Hello from foo()";
}
};

int main()
{
X a;
a.foo();
return 0;
}

 009. Scope resolution operator classes

#include<iostream>
using namespace std;

class X
{
public:
void foo();
};

void X::foo()
{
cout << "Hello from foo()";
}

int main()
{
X a;
a.foo();
return 0;
}

 010. Parameterizing member functions

#include<iostream>
using namespace std;

class Maths{

public:
int a, b;

int add(int a, int b);


};

int Maths::add(int a, int b)


{
int c = a + b;
return c;
}

int main (){


Maths m1;
m1.a = 10;
m1.b = 20;

cout << "Addition of " << m1.a << " and "
<< m1.b << " is.. "
<< m1.add(m1.a, m1.b);
return 0;
}

 011. Inline returns

#include <iostream>
using namespace std;

class Maths
{

public:
int a,b;
int add(int a, int b);
};

int Maths :: add(int a, int b)


{
return a + b;
}

int main()
{
Maths m1;
m1.a = 10;
m1.b = 20;

cout << "Addition of " << m1.a << " and "
<< m1.b << " is "
<< m1.add(m1.a, m1.b);

return 0;
}

 012. Private member functions

#include <iostream>
using namespace std;

class Maths
{

private:
int c;
int add(int a, int b)
{
c = a + b;
}

public:
int a,b;
void show(int a, int b)
{
add(a, b);
cout << "Addition of " << a << " and "
<< b << " is " << c;
}
};

int main()
{
Maths m1;
m1.a = 10;
m1.b = 20;

m1.show(m1.a, m1.b);

return 0;
}

 013. Arrays within class

#include <iostream>
using namespace std;

class ArrayDemo
{
int a[6];
public:
void getElements()
{
cout << "Enter 6 numbers in the array: " << endl;
for(int i=0; i<6;i++)
{
cin >> a[i];
}
}
void show()
{
cout << "\nArray elements are " << endl;
for(int i=0; i<6;i++)
{
cout << a[i] << endl;
}
}
};

int main()
{
ArrayDemo obj;
obj.getElements();
obj.show();

return 0;
}

 014. Call by value

#include<iostream>
using namespace std;

class Math
{
public:
void change(float);
};

void Math :: change(float y)


{
y = 5.5;
}

int main()
{
Math m1;
float y = 3.5;
m1.change(y);

cout << "Value of variable: " << y;


return 0;
}

 015. Call by reference

#include<iostream>
using namespace std;

void swap(int &x, int &y)


{
int temp;
temp = x;
x = y;
y = temp;
}

int main()
{
int x = 10;
int y = 20;
swap(x, y);

cout << "Value of variable x: " << x << "\n";


cout << "Value of variable y: " << y;

return 0;
}

 016. Return by reference

#include<iostream>
using namespace std;

// Global variable
int num;

// Function declaration
int& show();

int& show()
{
return num;
}

int main()
{
show() = 5;
cout << "Output is: " << num;
return 0;
}

 017. Inline functions

#include <iostream>
using namespace std;

inline int Min(int a, int b) {


return (a < b)? a : b;
}

// Main function for the program


int main() {
cout << "Min (10, 20): " << Min(10, 20) << "\n";
cout << "Min (100, 0): " << Min(100, 0) << "\n";
cout << "Min (15, 16): " << Min(15, 16) << "\n";

return 0;
}

 018. Friend function

#include <iostream>
using namespace std;

class Math
{
private:
int weight;
public:
//friend function
friend int print(Math);
};

int print(Math m)
{
m.weight += 10;
return m.weight;
}

int main()
{
Math m;
cout << "Weight: " << print(m);
return 0;
}

 019. Function overloading

#include<iostream>
using namespace std;

class Maths
{
public:
int a, b, c;
int add(int a, int b);
int add(int a, int b, int c);
};

int Maths :: add(int a, int b)


{
return a + b;
}

int Maths :: add(int a, int b, int c)


{
return a + b + c;
}

int main()
{
Maths m1;
m1.a = 10;
m1.b = 20;
m1.c = 30;

cout << "Addition of " << m1.a << " and "
<< m1.b << " is "
<< m1.add(m1.a, m1.b);

cout << "\nAddition of " << m1.a << " and "
<< m1.b << " and " << m1.c << " is "
<< m1.add(m1.a, m1.b, m1.c);

return 0;
}

 020. Parameterized constructor

#include <iostream>
using namespace std;

class Numbers
{
int a,b;
public:
// constructor declaration
Numbers(int, int);

void display(void)
{
count << "a = " << a
<< "\nb = " << b << endl;
}
};

Numbers :: Numbers(int x, int y)


{
a = x;
b = y;
}

int main()
{
// explicit call
Numbers n1 = Numbers(10, 20);

// implicit call
Numbers n2(20, 30);

cout << "Explicit call \n";


n1.display();

cout << "Implicit call \n";


n2.display();

return 0;
}

 021. Inline parameterized constructor

#include <iostream>
using namespace std;

class Numbers
{
int a,b;
public:
// inline constructor declaration
Numbers(int x, int y)
{
a = x;
b = y;
}

void display(void)
{
count << "a = " << a
<< "\nb = " << b << endl;
}
};

int main()
{
// explicit call
Numbers n1 = Numbers(10, 20);

cout << "Explicit call \n";


n1.display();

return 0;
}
022. Multiple constructors

#include<iostream>
using namespace std;

class Numbers{
int a, b;
public:
Numbers(){ // no arguments
a = 0; b = 0;
}

Numbers(int x, int y){


a = x; b = y;
}

void display(void){
cout << "a= " << a
<< "\nb= " << b << endl;
}
};

int main()
{
Numbers n1;
Numbers n2 = Numbers(10, 20);

cout << "Without arguments \n";


n1.display();

cout << "Explicit call \n";


n2.display();

return 0;
}

 023. Default argument constructor

#include <iostream>
using namespace std;

class Numbers
{
int a,b;
public:
// constructor with default argument
Numbers(int x, int y = 2)
{
a = x;
b = y;
}

void display(void)
{
count << "a = " << a
<< "\nb = " << b << endl;
}
};

int main()
{
Numbers n1 = Numbers(10);

Numbers n2 = Numbers(10, 20);

cout << "With default argument \n";


n1.display();

cout << "Updating default argument \n";


n2.display();

return 0;
}

 024. Copy constructor

#include <iostream>
using namespace std;

class Numbers
{
int a,b;
public:
Numbers()
{
a = 0;
b = 0;
}

Numbers(int x, int y = 2)
{
a = x;
b = y;
}

Numbers(Numbers &i)
{
a = i.a;
b = i.b;
}

void display(void)
{
count << "a = " << a
<< "\nb = " << b << endl;
}
};

int main()
{
Numbers n1(10, 20);

Numbers n2(n1);

cout << "Copy constructor values \n";


n2.display();

return 0;
}

 025. Destructors

#include<iostream>
using namespace std;

class Text
{
int a, b;
public:

Text()
{
cout << "Constructor called" << endl;
}

~Text()
{
cout << "Destructor called" << endl;
}
};

int main()
{
Text t1;

cout << "Main terminating" << endl;

return 0;
}

 026. Pointer to member declarator

#include <iostream>
using namespace std;

class Math{
public:
int a;
};

int main()
{
int Math::*pA = &Math::a;

Math m1;
m1.a = 1; // direct access
cout << "Value of a is " << m1.a << endl;
m1.*pA = 2; // access via pointer to member
cout << "Value of a is " << m1.a << endl;

return 0;
}

 027. Pointer to member operator

#include <iostream>
using namespace std;

class Math{
public:
int a;
void add()
{
cout << "add()\n";
}
};

void (Math::*pAdd)() = &Math::add;


int Math::*pA = &Math::a;

int main(){
Math m1;
Math *pM1 = new Math;

(m1.*pAdd)(); // Access the member function


(pM1->*pAdd)();

m1.*pA = 1; // access member data


pM1->*pA = 2;
cout << m1.*pA << endl
<< pM1->*pA << endl;

return 0;
}

 028. Memory management operators

#include <iostream>
using namespace std;

int main()
{
int *x;
x = new int[10];
if(x == NULL)
cout << "Memory is not allocated";
else
cout << "Memory is allocated";

delete x;
return 0;
}

 029. Manipulators

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
int a, b;
a = 100;
b = 200;

cout << setw(4) << a << setw(4) << b << endl;


cout << setw(5) << a << setw(5) << b << endl;
cout << setw(6) << a << setw(6) << b << endl;

return 0;
}

 030. Unary operator overloading

#include <iostream>
using namespace std;

class Math {
public:
int a, b, c;
void operator+(){
a = ++a;
b = ++b;
}

void operator-(){
a = --a;
b = --b;
}

void display(){
cout << "a= " << a << "\tb= " << b << endl;
}
};

int main()
{
Math m1;
m1.a = 10;
m1.b = 20;

+m1;
cout << "Increment number\n";
m1.display();
-m1;
cout << "Decrement number\n";
m1.display();

return 0;
}

 031. Binary operator overloading

#include <iostream>
using namespace std;

class Math {
public:
int a, b, c;

Math(){
this->a = 0;
this->b = 0;
}

Math(int x, int y){


this->a = x;
this->b = y;
}
Math operator+(Math& m2){
Math m3;
m3.a = this->a + m2.a;
m3.b = this->b + m2.b;
return m3;
}
};

int main()
{
Math m1(10, 20);
Math m2(20, 30);

Math m3;
m3 = m1+ m2;
cout << "Total a & b: " << m3.a
<< " & " << m3.b;

return 0;
}

 032. Single inheritance

#include <iostream>
using namespace std;

class Maths{
int a;
public:
int b;
void get_val();
int get_a(void);
};

class addition : public Maths{


int c;
public:
void add(void);
void display(void);
};

void Maths :: get_val(void)


{
a=10; b=15;
}

int Maths :: get_a(void){


return a;
}
void addition :: add(void){
c = get_a() + b;
}

void addition :: display(void){


cout << "a= " << get_a() << endl;
cout << "b= " << b << endl;
cout << "c= " << c << endl;
}

int main(){
addition a1;
a1.get_val();
a1.add();
a1.display();

a1.b=20;
a1.add();
a1.display();

return 0;
}

 033. Multilevel inheritance

#include <iostream>
using namespace std;

class Vehicle{
protected:
int int_id;
public:
int b;
void get_id(int);
int put_id(void);
};

void Vehicle :: get_id(int a)


{
int_id = a;
}

int Vehicle :: put_id(){


cout << "Vehicle Id: " << int_id << endl;
}

class Car : public Vehicle{


protected:
float version;
public:
void get_version(float);
void put_version(void);
};

void Car :: get_version(float a){


version = a;
}

void Car :: put_version(){


cout << "Car version: " << version << endl;
}

class Show : public Car


{
char new_model;
public:
void display(void);
};

void Show :: display(void){


put_id();
put_version();
}

int main(){
Show s1;
s1.get_id(1);
s1.get_version(1.3);
s1.display();

return 0;
}

 034. Multiple inheritance

#include <iostream>
using namespace std;

class A{
protected:
int a;
public:
void get_a(int);
};

class B{
protected:
int b;
public:
void get_b(int);
};

class C : public A, public B


{
public:
void display(void);
};

void A :: get_a(int x)
{
a = x;
}

void B :: get_b(int y){


b = y;
}

void C :: display(){
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << a + b << endl;
}

int main(){
C c1;
c1.get_a(15);
c1.get_b(16);
c1.display();

return 0;
}

 035. Hierarchical inheritance

#include <iostream>
using namespace std;

class Maths{
public:
int a, b;
void get_val(int, int);
};

void Maths :: get_val(int x, int y){


a = x; b = y;
}

class Addition : public Maths{


public:
void add(){
cout << "a + b = "
<< a + b << endl;
}
};

class Multiplication : public Maths{


public:
void mul(){
cout << "a * b = " << a * b;
}
};

int main(){
Addition a1;
Multiplication m1;

a1.get_val(15, 16);
a1.add();
m1.get_val(15, 16);
m1.mul();

return 0;
}

 036. Hybrid inheritance

#include <iostream>
using namespace std;

class Maths{
public:
int a;
};

class B : public Maths{


public:
B(){
a = 20;
}
};

class C{
public:
int b;
C(){
b = 10;
}
};

class Sum : public B, public C{


public:
void sum(){
cout << "Sum = " << a + b;
}
};

int main(){
Sum s1;
s1.sum();
return 0;
}

 037. Virtual base class

#include<iostream>
using namespace std;

class Math
{
public:
int a, b;
void show()
{
cout << "a = " << a << "\n";
cout << "b = " << b << "\n";
}
};

class B: virtual public Math


{
public:
void get_a(int x)
{
a = x;
}
};

class C: virtual public Math


{
public:
void get_b(int y)
{
b = y;
}
};

class D: public B, public C


{

};

int main()
{
D d1;
d1.get_a(10);
d1.get_b(20);
d1.show();

return 0;
}

 038. Pointers

#include <iostream>
using namespace std;

int main() {
int *a, b;

b = 10;
cout << "Address of b (&b): "
<< &b << endl;
cout << "Value of b (b): "
<< b << endl << endl;

// Pointer a holds address of b


a = &b;
cout << "Address of b in pointer a (a): "
<< a << endl;
cout << "Content of b in pointer a (*a): "
<< *a << endl << endl;

b = 20;

cout << "Address of b in "


<< "pointer a (a): "
<< a << endl;
cout << "Content of b in "
<< "pointer a (*a): "
<< *a << endl << endl;

*a = 30;
cout << "Address of b (&b): "
<< &b << endl;
cout << "Value of b (b): "
<< b << endl << endl;

return 0;
}

 039. Pointers arithmetic operations

#include<iostream>
using namespace std;

main()
{
//Array Declaration
int intArray[5] = {10,20,30,40,50};
int *ptr; //pointer point to int.
int sum = 0;
ptr = intArray;

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


{
cout << "\nAddress of var[" << i << "] = "
<< ptr <<endl; //show the Address
cout << "Value of var[" << i << "] = "
<< *ptr << endl; //show the value
sum = sum + *ptr;
ptr++;
}

cout << "Sum of array = "<< sum << endl;

return 0;
}

 040. Arrays of pointer

#include <iostream>
using namespace std;

int main () {
int intArray[5] = {10, 20, 30, 40, 50};
int *ptr[5];

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


// assign the address of integer
ptr[i] = &intArray[i];
}

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


cout << "Value of intArray[" << i << "] = ";
cout << *ptr[i] << endl;
}

return 0;
}

 041. String pointers

#include <iostream>
using namespace std;

int main()
{
int cnt;
char str[8] = "kodegod";
char *ptr;

ptr = str;
cout << "\nValue of string in variable ptr : "
<< ptr;

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


{
cout << "\nValue of string in pointer ptr: "
<< *ptr;
*ptr++;
}
return 0;
}

 042. Object pointer

#include <iostream>
using namespace std;

class Math {
private:
int a;
int b;
int c;

public:
Math(int x = 15, int y = 20, int z = 30) {
a = x;
b = y;
c = z;
}

int addition() {
return a + b + c;
}
};

int main() {
Math m1(30, 12, 15);
Math m2(5, 60, 20);
// Declare pointer to a class
Math *ptrMath;

// Save the address of first object


ptrMath = &m1;

cout << "Addition of m1: "


<< ptrMath->addition() << endl;

// Save the address of second object


ptrMath = &m2;

cout << "Addition of m2: "


<< ptrMath->addition() << endl;

return 0;
}

 043. this pointer

#include <iostream>
using namespace std;

class Math {
public:
private:
int a, b;

public:
Math(int x = 15, int y = 20) {
a = x; b = y;
}

int addition() {
return a + b;
}

int compare(Math math) {


return this->addition() > math.addition();
}
};

int main(void) {
Math m1(5, 60);
Math m2(30, 12);

if(m1.compare(m2)) {
cout << "m1 is greater than m2"
<<endl;
} else {
cout << "m1 is smaller than m2"
<<endl;
}

return 0;
}

 044. Virtual functions

#include <iostream>
using namespace std;

class Parent
{
public:
virtual void show()
{
cout << "This is Base class"
<< endl;
}
};

class Child:public Parent


{
public:
void show()
{
cout << "This is Derived Class"
<< endl;
}
};

int main()
{
Parent* p; //pointer of base class
Child c; //object of derived class
p = &c;
p->show();

return 0;
}

 045. Pure virtual functions

#include <iostream>
using namespace std;

class Shape
{
public:
// pure virtual Function
virtual float calculateArea(float l) = 0;
};

class Square : public Shape


{
public:
float calculateArea(float l)
{
return l*l;
}
};

class Circle : public Shape


{
public:
float calculateArea(float l)
{
return 3.14*l*l;
}
};

int main()
{
Square s;
Circle c;

cout <<"Area of square: " <<


s.calculateArea(6) << endl;
cout << "Area of circle: "
<< c.calculateArea(7);

return 0;
}

 046. istream

#include <iostream>
using namespace std;

int main()
{
char x;

cin.get(x);

cout << x;
}

 047. ostream
#include <iostream>
using namespace std;

int main()
{
char x;

cin.get(x);

// used to put a single char onto the screen


cout.put(x);
}

 048. iostream

#include <iostream>
using namespace std;

int main()
{
// this function display
// ncount character from array
cout.write("kodegod", 5);
}

 049. istream with assign

#include <iostream>
using namespace std;

class Stream {
public:
int x, y;

// operator overloading using friend function


friend void operator>>(Stream& s, istream& scin)
{
// cin assigned to another object scin
scin >> s.x >> s.y;
}
};

int main()
{
Stream s;
cout << "Enter two numbers x and y\n";

s >> cin;

cout << "x = " << s.x << "\ty = " << s.y;
}

 050. ostream with assign

#include <iostream>
using namespace std;

class Stream {
public:
int x, y;
Stream()
{
x = 10; y = 20;
}
// using friend function
friend void operator<< (Stream& s, ostream& scout)
{
// cout assigned to another object scout
scout << "Value of x and y are \n";
scout << s.x << " " << s.y;
}
};

int main()
{
Stream s;
s << cout;
return 0;
}

 051. Reading stream with getline

#include <iostream>
using namespace std;

int main()
{
int size = 10;
char country[10];

cout << "Enter country name: \n";


cin.getline(country, size);
cout << "Entered country name: " << country;
}

 052. Formatted console width

#include <iostream>
#include <math.h>
using namespace std;

int main()
{
cout << "Kode";
cout.width(5);
cout << "God";
cout.width(10);
cout << ".com";
}

 053. Formatted console precision

#include <iostream>
#include <math.h>
using namespace std;

int main()
{
cout.precision(3);
cout << "Square root of 54:\n" << sqrt(54);
}

 054. Formatted console fill

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
cout.fill('*');
cout << "Kode";
cout.width(5);
cout << "God";
cout.width(10);
cout << ".com";
}

 055. Formatted console setf

#include <iostream>
#include <math.h>
using namespace std;

int main()
{
cout.fill('*');
cout.setf(ios::left, ios::adjustfield);
cout.width(15);
cout << "KodeGod.com";
}

 056. Formatted console all

#include <iostream>
#include <math.h>
using namespace std;

int main()
{
cout.fill('*');
cout.precision(2);
cout.width(20);
cout.setf(ios::showpoint);
cout.setf(ios::showpos);
cout.setf(ios::scientific, ios::floatfield);
cout << "Square root of 54:\n";
cout.width(10);
cout << sqrt(54);
}
 057. Formatted console unsetf

#include <iostream>
using namespace std;

int main () {
cout.setf(ios::hex, ios::basefield);
cout.setf(ios::showbase);
cout << 80 << '\n';

cout.unsetf (ios::showbase);
cout << 80 << '\n';

return 0;
}

 058. Formatted console manipulators

#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;

int main()
{
cout.setf(ios::showpoint);
cout << setfill('#')
<< setw(4) << "k"
<< setw(25) << "Square root of 54: "
<< setprecision(3) << sqrt(54)
<< setw(10) << "Kodegod\n";

return 0;
}

 059. Formatted console user-defined manipulators

#include <iostream>
#include <iomanip>
using namespace std;

ostream & sign (ostream & o)


{
o << "@#";
return o;
}

int main()
{
cout << "kode" << sign << "God" << sign << "com";

return 0;
}

 060. Working with single file

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
// Creation of ofstream class object
ofstream fout;

string line;

// by default ios::out mode


fout.open("kode.txt");

cout << "Enter text to write in file:\n";

// Execute a loop If file successfully opened


while (fout) {

// Read a Line from standard input


getline(cin, line);

// Press -1 to exit
if (line == "-1")
break;

// Write line in file


fout << line << endl;
}
// Close the File
fout.close();

// Creation of ifstream class object to read the file


ifstream fin;

// by default open mode = ios::in mode


fin.open("kode.txt");
cout << "Text in file:\n";
// Execute a loop until EOF (End of File)
while (fin) {

// Read a Line from File


getline(fin, line);

// Print line in Console


cout << line << endl;
}

// Close the file


fin.close();

return 0;
}

 061. Working with multiple files

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
const int N = 100;
char line[N];

ofstream fout;

fout.open("kode.txt");
fout << "Kodegod";
fout.close();

fout.open("kodegod.txt");
fout << "Kodegod.com";
fout.close();

ifstream fin;

fin.open("kode.txt");
cout << "Text in file kode.txt:\n";
while(fin)
{
fin.getline(line, N);
cout << line << endl;
}
fin.close();

fin.open("kodegod.txt");
cout << "Text in file kodegod.txt:\n";
while(fin)
{
fin.getline(line, N);
cout << line << endl;
}
fin.close();

return 0;
}

 062. Read from two files

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
const int N = 100;
char line[N];

ifstream fin1, fin2;

fin1.open("kode.txt");
fin2.open("kodegod.txt");

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


{
if(fin1.eof() != 0)
{
cout << "Exit from kode.txt" << endl;
exit(1);
}
fin1.getline(line, N);
cout << "Text from kode.txt: \n" << line << endl;

if(fin2.eof() != 0)
{
cout << "Exit from kodegod.txt" << endl;
exit(1);
}
fin2.getline(line, N);
cout << "Text from kodegod.txt: \n" << line << endl;
}

fin1.close();
fin2.close();

return 0;
}

 063. Read-write binary file

#include<iostream>
#include<fstream>
using namespace std;

struct Employee {
int emp_id;
string name;
};

int main() {
ofstream fout("employee.dat", ios::out | ios::binary);
if(!fout) {
cout << "Cannot open file!" << endl;
return 1;
}
Employee emp[2];
emp[0].emp_id = 1;
emp[0].name = "Prashant";
emp[1].emp_id = 2;
emp[1].name = "Pranit";
for(int i = 0; i < 2; i++)
fout.write((char *) &emp[i], sizeof(Employee));
fout.close();

ifstream fin("employee.dat", ios::out | ios::binary);


if(!fin) {
cout << "Cannot open file!" << endl;
return 1;
}

Employee empr[2];
for(int i = 0; i < 2; i++)
fin.read((char *) &empr[i], sizeof(Employee));
fin.close();

cout<<"Employee Details:"<<endl;
for(int i=0; i < 2; i++) {
cout << "Emp Id: " << emp[i].emp_id << endl;
cout << "Name: " << emp[i].name << endl;
cout << endl;
}
return 0;
}

 064. File error handling

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
ifstream fin;
fin.open("test.txt", ios::in);
while(!fin.fail())
{
// process the file
}
if(fin.eof())
{
// terminate the program
}
else if(fin.bad())
{
// report fatal error
}
else
{
fin.clear(); // clear error-state flags
}
}

 065. Class template

#include <iostream>
using namespace std;

template <class T> class Maths


{
private:
T a, b;

public:
Maths(T x, T y)
{
a = x;
b = y;
}

void display()
{
cout << "Numbers are: " << a
<< " and " << b << endl;
cout << "Addition is: "
<< add() << endl;
cout << "Subtraction is: "
<< subtract() << endl;
}

T add() { return a + b; }

T subtract() { return a - b; }
};
int main()
{
Maths<int> intMath(20, 10);
Maths<float> floatMath(18.8, 9.4);

cout << "Int results:" << endl;


intMath.display();

cout << endl << "Float results:" << endl;


floatMath.display();

return 0;
}

 066. Function template

#include <iostream>
using namespace std;

template <class T> T Compare(T a, T b)


{
return (a > b) ? a : b;
}

int main()
{
int x, y;
float m, n;
char c1, c2;
cout << "Enter two integers:\n";
cin >> x >> y;
cout << Compare(x, y) <<" is larger" << endl;
cout << "\nEnter two floating-point numbers:\n";
cin >> m >> n;
cout << Compare(m, n) <<" is larger" << endl;
cout << "\nEnter two characters:\n";
cin >> c1 >> c2;
cout << Compare(c1, c2) << " has larger ASCII value.";
return 0;
}

 067. Overloading function template


#include <iostream>
using namespace std;

// function template
template <class T> T display(T a, T b)
{
cout << "Template values are : "
<< a << " and " << b << endl;
}

// overloads generic template function


void display(int x, int y)
{
cout << "Overload values are : "
<< x << " and " << y << endl;
}

int main()
{

display(10, 20);
display(20, 10);
display('P', 'K');

return 0;
}

 068. Nontype template argument

#include <iostream>
using namespace std;

template <class T, int N> T addition (T a)


{
return a + N;
}

int main() {
cout << addition<int, 10>(10) << '\n';
cout << addition<int, 20>(10) << '\n';
}

 069. Exception handling


#include <iostream>
using namespace std;

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

int main () {
int a = 10;
int b = 0;
double c = 0;

try {
c = division(a, b);
cout << c << endl;
} catch (const char* msg) {
cerr << msg << endl;
}

return 0;
}

 070. Rethrowing exception

#include <iostream>
using namespace std;

void ExcHandler()
{
try
{
throw "Thrown exception!";
}
catch (const char*)
{
cout << "Exception in function\n";
throw; //rethrow char* out of function
}
}
int main()
{
cout<< "Main function\n";
try
{
ExcHandler();
}
catch(const char*)
{
cout << "Exception in Main\n";
}

return 0;
}

 071. Multiple catch block

#include<iostream>
using namespace std;

void ExcHandler(int a) {
try {
if (a > 0)
throw a;
else
throw 'a';
} catch (int x) {
cout << "Catch a integer: " << a << endl;
} catch (char a) {
cout << "Catch a character: " << a;
}
}

int main() {
cout << "Test multiple catch blocks:\n";
ExcHandler(1);
ExcHandler(0);

return 0;
}

 072. Specifying exception


#include<iostream>
using namespace std;

void ExcHandler(int a)
throw(int, double, char){
if(a == 1)
throw 'a';
else if(a == 2)
throw a;
else if(a == -1)
throw 0;
}

int main() {
try {
cout << "a==1\n";
ExcHandler(1);
cout << "a==2\n";
ExcHandler(2);
cout << "a==-1\n";
ExcHandler(-1);
cout << "a==0\n";
ExcHandler(0);
} catch (char c) {
cout << "Character exception" << endl;
} catch (int a) {
cout << "Integer exception" << endl;
} catch (double d) {
cout << "Double exception" << endl;
}
return 0;
}

 073. Character array to store string

#include<iostream>
#include<cstring>
using namespace std;

int main()
{
char str1[] = "Kode";
char str2[] = "God";

cout << "Concatenated String: "


<< strcat(str1, str2) << endl;

return 0;
}

 074. Using string class

#include<iostream>
#include<string>
using namespace std;

int main()
{
string str1 = "Kode";

string str2 = "God";

cout << "capacity(): " << str1.capacity();


cout << "\nlength(): " << str1.length();
cout << "\nappend(): " << str1.append(str2);
cout << "\nassign(): " << str1.assign(str2);
str1 = "Kode";
cout << "\nat(): " << str1.at(2);
cout << "\nbegin(): " << *str1.begin();
cout << "\ncompare(): " << str1.compare(str2);
cout << "\nerase(): " << str1.erase(1, 2);

cout << "\ninsert(): " << str2.insert(str2.length() - 1, ".com");


cout << "\nfind(): " << str2.find(".com", 2);
str1.swap(str2);
cout << "\nswap(): " << str1;

return 0;
}

 075. Iterators

#include<iostream>
#include<iterator>
#include<vector>
using namespace std;

int main()
{
vector<int> intArray = { 1, 2, 3, 4, 5 };
vector<int> intArray1 = {10, 20, 30};

// Declaring iterator to a vector


vector<int>::iterator ptr = intArray.begin();

// Using advance to set position


advance(ptr, 2);

// copying 1 vector elements


// in other using inserter()
// inserts intArray1 after
// 2nd position in intArray
copy(intArray1.begin(),
intArray1.end(),
inserter(intArray,ptr));

// Displaying new vector elements


cout << "New vector container:\n";
for (int &x : intArray)
cout << x << " ";

return 0;
}

 076. Sequence containers vectors

#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector<int> v1;

for (auto i = 1; i <= 5; i++)


v1.push_back(i);

cout << "Output of begin and end: ";


for (auto i = v1.begin();
i != v1.end(); ++i)
cout << *i << " ";

cout << "\nOutput of cbegin and cend: ";


for (auto i = v1.cbegin();
i != v1.cend(); ++i)
cout << *i << " ";

cout << "\nOutput of rbegin and rend: ";


for (auto ir = v1.rbegin();
ir != v1.rend(); ++ir)
cout << *ir << " ";

cout << "\nOutput of crbegin and crend : ";


for (auto ir = v1.crbegin();
ir != v1.crend(); ++ir)
cout << *ir << " ";

return 0;
}

 077. Sequence containers lists

#include <iostream>
#include <list>
using namespace std;

int main (){


int intArray[] = {55, 23, 69, 10, 56};
list<int> lstNumbers (intArray, intArray + sizeof(intArray) / sizeof(int));

int intArray2[] = {10, 20, 30, 40, 50};


list<int> lstNumbersNew (intArray2, intArray2 + sizeof(intArray2) / sizeof(int));

cout << "List elements before swap: \n";


list<int>::iterator it;
for (it = lstNumbers.begin(); it != lstNumbers.end(); it++)
cout << *it << ' ';

cout << "\n\nList elements after swap: \n";


lstNumbers.swap(lstNumbersNew);
for (it = lstNumbers.begin(); it != lstNumbers.end(); it++)
cout << *it << ' ';

return 0;
}

 078. Sequence containers deque

#include <iostream>
#include <deque>
using namespace std;

void displaydq(deque <int> d)


{
deque <int> :: iterator it;
for (it = d.begin(); it != d.end(); ++it)
cout << '\t' << *it;
cout << '\n';
}

int main()
{
deque <int> dq;
dq.push_back(10);
dq.push_front(20);
dq.push_back(30);
dq.push_front(40);
cout << "The deque is : ";
displaydq(dq);

cout << "\ndq.size() : " << dq.size();


cout << "\ndq.max_size() : " << dq.max_size();

cout << "\ndq.at(2) : " << dq.at(2);

cout << "\ndq.pop_front() : ";


dq.pop_front();
displaydq(dq);

cout << "\ndq.pop_back() : ";


dq.pop_back();
displaydq(dq);

return 0;
}

 079. Associative containers sets

#include <iostream>
#include<set>
using namespace std;

int main(){
set<int> setOfNumbers;

setOfNumbers.insert(1);
setOfNumbers.insert(2);
setOfNumbers.insert(3);
setOfNumbers.insert(2);

cout << "Set Size = " <<setOfNumbers.size() << endl;

set<int>::iterator it;
for (it = setOfNumbers.begin(); it!=setOfNumbers.end(); ++it)
cout << ' ' << *it;
cout<<"\n";
return 0;
}

 080. Associative containers multiset

#include <iostream>
#include <set>
using namespace std;

int main()
{
multiset<int, greater<int>> msSet;

msSet.insert(10);
msSet.insert(20);
msSet.insert(30);
msSet.insert(20);
msSet.insert(40);

multiset<int, greater<int>>::iterator it;


cout << "The multiset elements are: ";
for (it = msSet.begin(); it != msSet.end(); ++it)
{
cout << "\n" << *it;
}
}

 081. Associative containers map

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main()
{
map<int, string> Students;
Students[101] = "Nikhil";
Students[102] = "Alex";
Students[103] = "John";
Students[104] = "Neel";
Students[105] = "Sunny";

cout << "Map size: " << Students.size() << endl;


cout << "Original Order:" << endl;

map<int,string>::iterator it;
for( it=Students.begin(); it!=Students.end(); ++it)
{
cout << (*it).first << ": " << (*it).second << endl;
}

cout << "Reverse Order:" << endl;


map<int,string>::reverse_iterator itN;
for( itN=Students.rbegin(); itN!=Students.rend(); ++itN)
{
cout << (*itN).first << ": " << (*itN).second << endl;
}

return 0;
}

 082. Associative containers multimap


#include <iostream>
#include <map>
#include <string>
using namespace std;

int main()
{
multimap<string, string> mmCountry = {
{"India","Delhi"},
{"India", "Hyderabad"},
{"United Kingdom", "London"},
{"United States", "Texas"}
};

cout << "Size of map: " << mmCountry.size() <<endl;


cout << "Elements in multimap: " << endl;
multimap<string, string>::iterator it;
for (it = mmCountry.begin(); it != mmCountry.end(); ++it)
{
cout << (*it).first << " => " << (*it).second << endl;
}

return 0;
}

 083. Derived container stack

#include <iostream>
#include <stack>
using namespace std;

void displayStack(stack <int> st)


{
while (!st.empty())
{
cout << '\t' << st.top();
st.pop();
}
cout << '\n';
}

int main ()
{
stack <int> st;
st.push(10);
st.push(20);
st.push(30);
st.push(50);
st.push(40);

cout << "The stack is : ";


displayStack(st);

cout << "\nst.size() : " << st.size();


cout << "\nst.top() : " << st.top();

cout << "\nst.pop() : ";


st.pop();
displayStack(st);

return 0;
}

 084. Derived container queue

#include <iostream>
#include <queue>
using namespace std;

void displayQueue(queue <int> q)


{
while (!q.empty())
{
cout << '\t' << q.front();
q.pop();
}
cout << '\n';
}

int main()
{
queue <int> q;
q.push(10);
q.push(20);
q.push(30);
cout << "The queue is : ";
displayQueue(q);

cout << "\nq.size() : " << q.size();


cout << "\nq.front() : " << q.front();
cout << "\nq.back() : " << q.back();

cout << "\nq.pop() : ";


q.pop();
displayQueue(q);

return 0;
}

 085. Derived container priority queue

#include <iostream>
#include <queue>
using namespace std;

void displaypq(priority_queue <int> pq)


{
priority_queue <int> p = pq;
while (!p.empty())
{
cout << '\t' << p.top();
p.pop();
}
cout << '\n';
}

int main ()
{
priority_queue <int> pq;
pq.push(10);
pq.push(30);
pq.push(20);

pq.push(50);
pq.push(40);

cout << "The priority queue is :\n";


displaypq(pq);
cout << "\npq.size() : " << pq.size();
cout << "\npq.top() : " << pq.top();

cout << "\npq.pop() :\n";


pq.pop();
displaypq(pq);

return 0;
}

 086. Class implimentation

#include <iostream>
using namespace std;

class Test{
private:
mutable int a;
public:
explicit Test(int x = 0){
a = x;
}
void change() const{
a = a + 15;
}
int display() const{
return a;
}
};

int main(){
const Test t(200);
cout << "Value of a: " << t.display();
cout << "\n";
t.change();
cout << "Value of a: " << t.display();

return 0;
}

You might also like