OOPS SMALL PROGRAMS

Prepared by M. Rameshkumar,Lect(CSE)

Structure of a program #include <iostream.h> int main () { cout << "Hello World!"; return 0; } O/P Hello World! operating with variables #include <iostream.h> int main () { // declaring variables: int a, b; int result; // process: a = 5; b = 2; a = a + 1; result = a - b; cout << result; return 0; } O/P 4 Initialization of variables #include <iostream.h> int main () { int a=5; int b(2); int result; a = a + 3; result = a - b; cout << result; return 0; } O/P 6 STRINGS #include <iostream.h> #include <string.h> int main ()
{ string mystring; mystring = "This is the initial string content"; cout << mystring << endl; mystring = "This is a different string content"; cout << mystring << endl; return 0; } O/P

This is the initial string content This is a different string content

Assignment operator #include <iostream.h> int main () { int a, b; // a:?, b:? a = 10; // a:10, b:? b = 4; // a:10, b:4 a = b; // a:4, b:4 b = 7; // a:4, b:7 cout << "a:"; cout << a; cout << " b:"; cout << b; return 0; } O/P a:4 b:7
Compound assignment operators #include <iostream.h> int main () { int a, b=3; a = b; a+=2; // equivalent to a=a+2 cout << a; return 0; } O/P 5 Conditional operator #include <iostream.h> int main () { int a,b,c; a=2; b=7; c = (a>b) ? a : b; cout << c; return 0; } O/P 7 I/O(cout and cin) example #include <iostream.h> int main () { int i; cout << "Please enter an integer value: ";

cin >> i; cout << "The value you entered is " << i; cout << " and its double is " << i*2 << ".\n"; return 0; } O/P Please enter an integer value: 702 The value you entered is 702 and its double is 1404.

statement1 elseif statement2 else statement3 #include <iostream.h> int main () { int x; cout << "Enter the number "; cin >> x; if (x > 0) cout << "x is positive"; else if (x < 0) cout << "x is negative"; else cout << "x is 0"; } O/P Enter the number 25 x is positive

Conditional structure Syntax If condition if (condition) statement Ex: #include <iostream.h> int main () { int x; cout << "Enter the number "; cin >> x;
if (x == 100) { cout << "x is "; cout << x; } } O/P Enter the number 100 X is 100

Iteration structures (loops)
while loop while (expression) statement Ex: #include <iostream.h> int main () { int n; cout << "Enter the starting number "; cin >> n; while (n>0) { cout << n << ", "; --n; } cout << "FIRE!\n"; return 0; } O/P Enter the starting number 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

If ...else condition
if (condition) statement1 else statement2 #include <iostream.h> int main () { int x; cout << "Enter the number "; cin >> x; if (x == 100) cout << "x is 100"; else cout << "x is not 100"; } O/P Enter the number 200 x is not 100

do-while loop
do statement while (condition);

Else...if condition if (condition)

#include <iostream.h> int main () { unsigned long n; do { cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: " << n << "\n"; } while (n != 0); return 0; } O/P Enter number (0 to end): 12345 You entered: 12345 Enter number (0 to end): 160277 You entered: 160277 Enter number (0 to end): 0 You entered: 0

O/P 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!

continue statement #include <iostream.h> int main () { for (int n=10; n>0; n--) { if (n==5) continue; cout << n << ", "; } cout << "FIRE!\n"; return 0; } O/P 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE! goto statement
#include <iostream.h>

for loop
for (initialization; condition; increase) statement; #include <iostream.h> int main () { for (int n=10; n>0; n--) { cout << n << ", "; } cout << "FIRE!\n"; return 0; } O/P 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! int main () { int n=10; loop: cout << n << ", "; n--; if (n>0) goto loop; cout << "FIRE!\n"; return 0; } O/P 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

selective structure: switch.
switch (expression) { case constant1: group of statements 1; break; case constant2: group of statements 2; break; default: default group of statements } Ex: #include <iostream.h> int main () { int x; cout << "Enter the number "; cin >> x;

Jump statements
break statement #include <iostream.h> int main () { int n; for (n=10; n>0; n--) { cout << n << ", "; if (n==3) { cout << "countdown aborted!"; break; } } return 0; }

switch (x) { case 1: case 2: case 3: cout << "x is 1, 2 or 3"; break; default: cout << "x is not 1, 2 nor 3"; }

int r; r=a+b; return (r); } int main () { int z; z = addition (5,3); cout << "The result is " << z; return 0; } O/P The result is 8

Functions
Return_type name( parameter1, parameter2, ...) { statements }

Function example #include <iostream.h> int addition (int a, int b) { int r; r=a+b; return (r); }
int main () { int z; z = addition (5,3); cout << "The result is " << z; return 0; } O/P The result is 8

Arguments passed by reference #include <iostream.h> void duplicate (int& a, int& b, int& c) { a*=2; b*=2; c*=2; } int main () { int x=1, y=3, z=7; duplicate (x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z; return 0; } O/P x=2, y=6, z=14 Function with Default values in parameters
#include <iostream.h> int divide (int a, int b=2) { int r; r=a/b; return (r); } int main () { cout << divide (12); cout << endl; cout << divide (20,4); return 0; } O/P 6 5 Function Overloading #include <iostream.h> int operate (int a, int b) { return (a*b);

Functions with no type. The use of void
void function example #include <iostream.h> void printmessage () { cout << "I'm a function!"; } int main () { printmessage (); return 0; } O/P I'm a function!

Arguments passed by value #include <iostream.h> int addition (int a, int b) {

} float operate (float a, float b) { return (a/b); } int main () { int x=5,y=2; float n=5.0,m=2.0; cout << operate (x,y); cout << "\n"; cout << operate (n,m); cout << "\n"; return 0; } O/P 10 2.5 inline functions inline type name ( arguments ... ) { instructions ... } #include <iostream.h> inline int average(int a, int b) { return (a + b) / 2; } void main() { cout << "The average of number 12, 14 is " << average(12, 14) ; } O/P The average of number 12, 14 is 13 Declaring functions declaring functions prototypes #include <iostream.h> void odd (int a);//prototype int main () { int i; cout << "ENTER A NUMBER "; cin >> i; odd (i); return 0; } void odd (int a) { if ((a%2)!=0) cout << "Number is odd.\n"; } O/P ENTER A NUMBER 12 Number is odd

Arrays #include <iostream.h> int billy [] = {16, 2, 77, 40, 12071}; int n, result=0; int main () { for ( n=0 ; n<5 ; n++ ) { result += billy[n]; } cout << result; return 0; } O/P 12206

Multidimensional arrays #include <iostream.h> #define WIDTH 5 #define HEIGHT 3
int jimmy [HEIGHT][WIDTH]; int n,m; int main () { for (n=0;n<HEIGHT;n++) for (m=0;m<WIDTH;m++) { jimmy[n][m]=(n+1)*(m+1); } return 0; } O/P 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 Arrays as parameters #include <iostream.h> void printarray (int arg[], int length) { for (int n=0; n<length; n++) cout << arg[n] << " "; cout << "\n"; } int main () { int firstarray[] = {5, 10, 15}; int secondarray[] = {2, 4, 6, 8, 10}; printarray (firstarray,3); printarray (secondarray,5);

return 0; } O/P 5 10 15 2 4 6 8 10 Pointers #include <iostream.h> int main () { int value; int * mypointer; mypointer = &value; *mypointer = 10; cout << "value is " << value << endl; return 0; } O/P firstvalue is 10

}; void CRectangle::set_values (int a, int b) { x = a; y = b; } int main () { CRectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); return 0; } O/P area: 12 Constructors and destructors #include <iostream.h> class CRectangle { int width, height; public: CRectangle (int a,int b) { width = a; height = b; } int area () {return (width*height);} }; int main () { CRectangle rect (3,4); cout << "rect area: " << rect.area() << endl; return 0; } Overloading Constructors with default Constructor #include <iostream.h> class CRectangle { int width, height; public: CRectangle() //Default Constructor { width = 5; height = 5; } CRectangle (int a,int b) { width = a; height = b; }

Pointers and arrays
#include <iostream.h> int main () { int numbers[5]; int * p; p = numbers; *p = 10; p++; *p = 20; p = &numbers[2]; for (int n=0; n<2; n++) cout << numbers[n] << ", "; return 0; } O/P 10, 20 Class Syntax class class_name { access_specifier_1: member1; access_specifier_2: member2; ... } object_names; SCOPE RESOLUTION OPERATOR(::) #include <iostream.h> class CRectangle { int x, y; public: void set_values (int,int); int area () {return (x*y);}

int area (void) {return (width*height);} }; int main () { CRectangle rect (3,4); CRectangle rectb; cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } O/P rect area: 12 rectb area: 25 Destructors #include <iostream.h> class CRectangle { int width; public: CRectangle (int a) { Width=a; } ~CRectangle () { delete width; } int area () {return width;} }; int main () { CRectangle rect (3); cout << "rect width: " << rect.area() << endl; return 0; } O/P rect width:3 Overloading operators overloading operators Binary Operator(+) #include <iostream.h> class CVector { public: int x,y; CVector (int a, int b) { x = a; y = b; } CVector operator+ (CVector param) { CVector temp; temp.x = x + param.x; temp.y = y + param.y;

return (temp); } }; int main () { CVector a (3,1); CVector b (1,2); CVector c; c = a + b; cout << c.x << "," << c.y; return 0; } O/P 4,3 Overloading operators Unary Operator(++) #include <iostream.h> class CVector { public: int x; CVector (int a) { x = a; } void operator++() { a++; } Void disp() { Cout<<a; } }; void main () { CVector o(3) o.disp(); o++; o.disp(); } O/P 3 4 Static members #include <iostream.h>

class CDummy { public: static int n; CDummy () { n++; }; Void disp() { Cout<<n; } }; int CDummy::n=0;

void main () { CDummy a; a.disp(); CDummy b; b.disp(); CDummy c; c.disp(); } O/P 1 2 3 Friend functions #include <iostream.h> class CRectangle { int w; public: void set_values (int a, int b) { w = a; } int print () {return w;} friend CRectangle duplicate (CRectangle); }; CRectangle duplicate (CRectangle rectparam) { CRectangle rectres; rectres.w = rectparam.w*2; return (rectres); } int main () { CRectangle rect, rectb; rect.set_values (2); rectb = duplicate (rect); cout << rectb.print(); return 0; } O/P 6 Friend classes #include <iostream.h> class CSquare; class CRectangle { int w; public: int print() {return (w);} void convert (CSquare a); };

class CSquare { private: int side; public: void set_side (int a) {side=a;} friend class CRectangle; }; void CRectangle::convert (CSquare a) { w = a.side*4; } void main () { CSquare sqr; CRectangle rect; sqr.set_side(4); rect.convert(sqr); cout << rect.print(); } O/P 16

Different types of inheritance
1.Single inheritance #include<iostream.h> class baseClass { protected: void disp() { cout<<”Base Class” } }; class derivedClass { public: void print(); { Cout<<”Derived Class”; } }; void main() { derivedClass o; o.disp(); o.print(); } O/P Base Class Derived Class 2. Multilevel Inheritance #include<iostream.h> class A

{ protected: int a void geta(int x) { a=x; } void printa() { cout<<a; } }; class B : protected A { protected : int b; void getb(int y) { b=y; } void printb() { cout<<b; } }; Class C:B { public: void calculate(int x, int y) { geta(x); printa(); getb(y) printb(); cout<<”Result :”<<a+b; } }; void main() { C o; o.calculate(10,20); } O/P A 10 B 20 Result :30 3. Hierarchical Inheritance #include<iostream.h> class Data { protected:

int a,b; Data() { a=20; b=10; } }; class Addin:Data { void add() { cout<<”Addition :”; cout<<a<<”\t”<<b<<”\n”; cout<<a+b; } }; class Subtract:Data { void sub() { cout<<”Subtract :”; cout<<a<<”\t”<<b<<”\n”; cout<<a-b; } }; class Multiply:Data { void mul() { cout<<”Multiply :”; cout<<a<<”\t”<<b<<”\n”; cout<<a*b; } }; void main() { Addin a; Subtract s; Multiply m; a.add(); s.sub(); m.mul(); } O/P Addition 20 10 30 Subtract 20 10 10 Multiply 20 10 200 4.Multple Inheritance

#include<iostream.h> class Base1 { protected: int a; public: Base1( int Value ) { a = Value; } int getData() { return value; } }; class Base2 { protected: int b; public: Base2( int value2 ) { b = value2; } char getData() { return letter; } }; class Derived : public Base1, public Base2 { private: int c; public: Derived( int val1, int val2) : Base1( val1 ), Base2( val2) { } } void display() { c=a+b; cout << a << "\n” << b << "\n: " << c; } }; int main() { Base1 *base1Ptr; Base2 *base2Ptr; Derived derived( 7,5 ); base1Ptr = &derived; cout << base1Ptr->getData() << '\n'; base2Ptr = &derived; cout << base2Ptr->getData() << endl;

derived.display(); return 0; } O/P 7 5 12 Hybrid Inheritance #include <iostream.h> class mm { protected: int rollno; public: void get_num(int a) { rollno = a; } void put_num() { cout << "Roll Number Is:"<< rollno << “\n"; } }; class marks : public mm { protected: int sub1; int sub2; public: void get_marks(int x,int y) { sub1 = x; sub2 = y; } void put_marks(void) { cout << "Subject 1:" << sub1 << "\n"; cout << "Subject 2:" << sub2 << "\n"; } }; class extra { protected: float e; public: void get_extra(float s) {e=s;} void put_extra(void) { cout << "Extra Score::" << e << "\n";} }; class res : public marks, public extra{ protected: float tot; public: void disp(void) {

tot = sub1+sub2+e; put_num(); put_marks(); put_extra(); cout << "Total:"<< tot; } }; int main() { res std1; std1.get_num(10); std1.get_marks(10,20); std1.get_extra(33.12); std1.disp(); return 0; } O/P Roll Number Is: 10 Subject 1: 10 Subject 2: 20 Extra score:33.12 Total: 63.12 }

p = &Derived1_obj; p->print(); p = &Derived2_obj; p->print(); return 0;

O/P Base First derivation Second derivation

Virtual base class
#include <iostream.h> class Base { public: virtual void print() = 0; // pure virtual }; class Derived1 : virtual public Base { public: void print() { cout << "Derived1\n"; } }; class Derived2 : virtual public Base { public: void print() { cout << "Derived2\n"; } }; class Multiple : public Derived1, public Derived2 { public: void print() { Derived2::print(); } }; int main() { Multiple both; Derived1 one; Derived2 two; Base *bptr bptr = &both; bptr->print(); bptr = &one;

Virtual Function #include <iostream.h> class Base { public: virtual void print() { cout << "Base\n"; } };
class Derived1 : public Base { public: void print() { cout << "First derivation\n"; } }; class Derived2 : public BaseClass { public: void print() { cout << "Second derivation\n"; } }; int main() { Base base; Base *p; Derived1 Derived1_obj; Derived2 Derived2_obj; p = &base; p->print();

bptr->print(); bptr = &two; bptr->print(); return 0; } O/P Derived2 Derived1 Derived2 Templates The format for declaring function templates with type parameters is: Syntax template <class identifier> function_declaration; template <typename identifier> function_declaration; Function template #include <iostream.h> template <class T> T GetMax (T a, T b) { T result; result = (a>b)? a : b; return (result); } int main () { int i=5, j=6, k; long l=10, m=5, n; k=GetMax<int>(i,j); n=GetMax<long>(l,m); cout << k << endl; cout << n << endl; return 0; } O/P 6 10 Class templates #include <iostream.h> template <class T> class mypair { T a, b; public: mypair (T first, T second) {a=first; b=second;} T getmax (); }; template <class T> T mypair<T>::getmax () {

T retval; retval = a>b? a : b; return retval; } int main () { mypair <int> myobject (100, 75); cout << myobject.getmax(); return 0; } O/P 100 Exceptions #include <iostream.h> int main () { try { throw 20; } catch (int e) { cout << "An exception occurred. Exception Nr. " << e << endl; } return 0; } O/P An exception occurred. Exception Nr. 20 Standard exceptions #include <iostream> #include <exception> using namespace std; class myexception: public exception { virtual const char* what() const throw() { return "My exception happened"; } } myex; int main () { try { throw myex; } catch (exception& e) { cout << e.what() << endl; } return 0; } O/P My exception happened.

Input/Output with files • ofstream: Stream class to write on files • ifstream: Stream class to read from files • fstream: Stream class to both read and write from/to files. Basic file operations #include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; } O/P [file example.txt] Writing this to a file. Open a file ofstream myfile; myfile.open ("example.bin", ios::out | ios::app | ios::binary); Closing a file myfile.close(); Text files Writing on a text file #include <iostream.h> #include <fstream.h> int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0; } O/P [file example.txt] This is a line. This is another line.

Reading a text file #include <iostream.h> #include <fstream.h> #include <string.h> int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( myfile.good() ) { getline (myfile,line); cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; return 0; } O/P This is a line. This is another line.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.