You are on page 1of 75

Introduction to OOPS

Semester – I I

Copyright@ Amity University


A function can be invoked in two manners :

 Call By Value

 Call By Reference

Copyright@ Amity University


Terms To Know

 The parameter that appears in a function call statement are actual


parameter

 The parameter that appears in a function definition are formal


parameters

Copyright@ Amity University


The call by value method copies the values of actual parameters
into the formal parameters, that is, the function creates its own
copy of
argument values and then uses them.

Copyright@ Amity University


The main benefit of call by value

method is that you cannot alter the variable that are used to call

the function because any change that occurs inside function is on

the function’s copy of the argument value. The original copy of

the arguments value remains intact.

Copyright@ Amity University


The call by reference method in place copies the values of
actual parameters into the formal parameters, a reference to
the original variable is passed. (reference is an alias (i.e. a
different name) for the predefined variable)That is, the same
variable’s value can be accessed by any of the two names.
When a function is called by reference , then the formal
parameters become references (or alias) to the actual
parameter in the calling function.

Copyright@ Amity University


This means that in the call by reference method, the called
function does not create its own copy of original values,
rather , it refers to the original values only by different
names. Thus the called function works with the original data
and any change in the values gets reflected to the data.

Copyright@ Amity University


Function overloading allows you to have multiple
functions with the
same name. The compiler identifies the function
based on the parameters
to the functions.

Copyright@ Amity University


Overloading is possible if a function has Different set of parameters
in terms of :

• sequence { void add(int,char) & void add(char.int) }

• number { void add(int,int) & void add(int,int,int) }

• type { void add(int,int) & void add(float,float) }

Function overloading is used for the ease of the programmer.


The programmer does not have to remember multiple function names.
Copyright@ Amity University
Function overloading is used for the ease of the programmer.

The programmer does not have to remember multiple function names.

Copyright@ Amity University


ARRAY AND FUNCTIONS
Examples

Copyright@ Amity University


1St Program
(Matrix Example)
#include <iostream.h>
const int ROW=4;
const int COLUMN =3;
void main()
{
int i,j;
int Exforsys[ROW][COLUMN];
for(i=0;i<ROWS;i++)
for(j=0;j<COLUMN;J++)
{
cout << "Enter value of Row "<<i+1;
cout<<",Column "<<j+1<<":";
cin>>Exforsys[i][j];
}

Copyright@ Amity University


Contd…

cout<<"\n\n\n";
cout<< " COLUMN\n";
cout<< " 1 2 3";
for(i=0;i<ROW;i++)
{
cout<<"\nROW "<<i+1;
for(j=0;j<COLUMN;J++)
cout<<Exforsys[i][j];
}

Copyright@ Amity University


FIBONACCI Series
#include <iostream.h>
// sequence is 0, 1, 1, 2, 3, 5, 8, 13, ...
int fib (int i) {
Int pred, result, temp;

pred = 1;
result = 0;
while (i > 0) {
temp = pred + result;
result = pred;
pred = temp;
i = i-1;
}
return(result);
}

Copyright@ Amity University


Contd.
int main () {
int n;
cout << "Enter a natural number: ";
cin >> n;
while (n < 0) {
cout << "Please re-enter: ";
cin >> n;
}
cout << "fib(" << n << ") = " << fib(n) << endl;
return(0);
}

Copyright@ Amity University


(Exponential Functions
Example)
#include <iostream.h>
#include <stdlib.h>
int exp (int,int);
void readnums (int&, int&);
void main ()
{
int b, e;
readnums(b,e);
cout << b << " to the " << e << " = " << exp(b,e) << endl;
}
void readnums (int& b, int& e) {
Copyright@ Amity University
Contd.

int correctInput;
cout << "Enter the base and the exponent:";
cin >> b >> e;
if (!cin) {
cout << "Disaster! Terminating program." <<
endl;
exit(-1);
}

Copyright@ Amity University


Contd.
correctInput = (b >= 0) && (e >= 0);
while (!correctInput) {
cout << "Something wrong! Try again ..." << endl;
cout << "Re-enter base and exponent: "; cin >> b >>
e;
if (!cin) { cout << "Disaster! Terminating program."
<< endl;
exit(-1);
}
correctInput = (b >= 0) && (e >= 0);
}
}

Copyright@ Amity University


Contd.
int exp (int b, int e)
{ int result;
result = 1;
while (e != 0) {
result = result * b;
e = e - 1;
}
return(result);
}

Copyright@ Amity University


Programme 4th
(File Handling Example)
#include <fstream.h>
#include <iostream.h>
int main ()

{ ifstream f1, f2;


ofstream f3;
int i,j;
f1.open("n1");
f2.open("n2");
f3.open("n1n2");
Copyright@ Amity University
Contd.
f1 >> i;
f2 >> j;
while (f1 && f2) {
if (i < j) {
while (i < j && f1 && f3)
{ f3 << i << endl;
f1 >> i;
}
}
else {
while (j <= i && f2 && f3)
{ f3 << j << endl;
f2 >> j;
}

Copyright@ Amity University


Contd.
}
} while (f1) {
f3 << i << endl ;
f1 >> i;
}
while (f2) {
f3 << j << endl;
f2 >> j;
} return (0);
}

Copyright@ Amity University


Program 5th
(Natural Numbers Multiplication)
#include <iostream.h>
int mult (int x, int y) {
int result;
result = 0;
while (y != 0) {
result = result + x;
y = y - 1;
}
return(result);
}
int main ()
{ int x, y; cout << "Enter two natural numbers: ";
cin >> x >> y;
cout << x << " * " << y << " = " << mult(x,y) << endl;
return(0);
}
Copyright@ Amity University
Program 6th
(Prime Number)

#include <iostream.h>
int smalldiv (int n){
int count;
count = 2;
while (count < n && n % count != 0)
{ count = count + 1;
}
return(count);
}

Copyright@ Amity University


Contd
int main () {
int n;
cout << "Enter a natural number: ";
cin >> n;
if (n == smalldiv(n))
{
cout << n << " is a prime number" << endl;
} else
{ cout << n << " is not a prime number" << endl;
} return(0);
}

Copyright@ Amity University


Program 6th

#include <iostream.h>
typedef int Bool;
const Bool TRUE = 1;
const Bool FALSE = 0;
Bool even (int);
Bool odd (int);
int readPosNum();
void testOneNum();
void panic();

Copyright@ Amity University


Contd..
void main ()
{ int i;
char c;
Bool more = TRUE;
while (cin && more) {
testOneNum();
cout << "More? [y = Yes, anything else No]: "; cin >> c;
if (cin) more = (c == 'y');
}
}

Copyright@ Amity University


Contd..
void testOneNum () {
int i;
i = readPosNum();
if (even(i)) cout << "The number " << i << " is even." << endl;
else cout << "The number " << i << " is odd." << endl;
}
int readPosNum () {
int j;
cout << "Enter a number >= 0: ";
cin >> j;
while (cin && j < 0)
{ cout << "Unacceptable, reenter: ";
cin >> j;
} if (cin) return(j);
else panic();

Copyright@ Amity University


Contd..
Bool even (int i) {
if (i == 0) return(TRUE);
else return(odd(i-1));
}
Bool odd (int i)
{ if (i == 0) return(FALSE);
else return(even(i-1));
}
void panic()
{ cout << "Disaster! Exiting ..." << endl;
exit(-1);
}

Copyright@ Amity University


Program 7th
(Understanding call-by-value vs
call-by-reference)
#include <iostream.h>
int f1 (int, int, int);
int f2 (int&, int&, int&);
int f3 (int, int&, int);

Copyright@ Amity University


Contd..

void main ()
{ int i, j, k; i=1; j=2; k=3; cout << endl; cout <<
"Initial values of i, j, and k are: "
<< i << ", " << j << ", and " << k <<
endl << endl;
cout << "f1(i,j,k) = " << f1(i,j,k) << endl; cout <<
"Values of i, j, and k after the call to f1 are: “
<< i << ", " << j << ", and " << k << endl <<
endl;

Copyright@ Amity University


Contd..

cout << "f2(i,j,k) = " << f2(i,j,k) << endl;


cout << "Values of i, j, and k after the call
to f2 are: "
<< i << ", " << j << ", and " << k <<
endl << endl;
cout << "f3(i,j,k) = " << f3(i,j,k) << endl;
cout << "Values of i, j, and k after the call
to f3 are: "
<< i << ", " << j << ", and " << k << endl;}
Copyright@ Amity University
Contd…
int f1 (int x, int y, int z) {
x=x+5;
y=y+5;
z=z+5;
return(x+y+z);
}
int f2 (int& x, int& y, int& z)
{
x=x+5;
y=y+5;
z=z+5;

Copyright@ Amity University


Contd..

return(x+y+z);
}
int f3 (int x, int& y, int z) {
x=x+5;
y=y+5;
z=z+5;
return(x+y+z);
}

Copyright@ Amity University


ARRAY

Copyright@ Amity University


• Accessing Array’s Element
• The following program example declares and
initializes the array named y of type int. It uses a
for loop with index i to access the successive
elements in y. For each loop iteration, the value
accessed is added to the variable total, which is
finally displayed. Note that the loop index i run
from 0 to 6, not 1 to 7. Also, note that the array
size n is declared in the #define statement.

Copyright@ Amity University


A program to find the
total of all the elements in array

#include <iostream.h>
using namespace std;
// replace every n occurrences with 7
#define n 7

int main()
{
Copyright@ Amity University
int i, total = 0, y[n] = {6,9,2,4,5,23,12};
for (i=0; i<n; i++)
{
// display the array contents...
cout<<y[i]<<" ";
// do the summing up...
total = total + y[i];
}

Copyright@ Amity University


// display the result...
cout<<"\nSum of 7 numbers in an array is
= "<<total<<endl;
return 0;
}

Copyright@ Amity University


• You can see that the for loop is very useful when
you wish to loop or iterate through every
element of an array.
• The next program example, accomplishes the
same task as the previous one. By using
get_total() function, the main() passes the first
memory address (pointed by the pointer) of an
array, y and its size, n to the function get_total()
which then computes and returns the total,
total. Note the function prototype:
• int get_total(int*, int)

Copyright@ Amity University


• Study the following source code and the output.
// a program to find the total values of an
// array y by passing an array to a function using pointer
#include <iostream>
using namespace std;
#define n 7

// function prototype
int get_total(int*, int);

int main()

Copyright@ Amity University


{
int total, y[n]={6,9,2,4,5,23,12};
cout<<"\nCalling function get_total(y, n),";
cout<<"\nBy bringing along the value of y, an array";
cout<<"\nfirst address and n = 7, an array size.";
cout<<"\nAn array name, is the pointer to the";
cout<<"\n1st element of an array\n\n";
// a function call, pass along the pointer to the first
// array element and the array size, and the
// return result assign to variable total

Copyright@ Amity University


total = get_total(y, n);
cout<<"\nSum of the 7 array elements is
"<<total<<endl;
return 0;
}

Copyright@ Amity University


// function definition
int get_total(int *ptr, int x)
{
int i, total = 0;
// do the looping for array elements...
for(i=0; i<x; i++)
{
// displays the array content, pointed by
pointer...

Copyright@ Amity University


cout<<*(ptr+i)<<" ";
// do the summing up of the array
elements...
total += *(ptr+i); // total=total + *(ptr+i);
}
// return the result to the calling program...
return total;
}

Copyright@ Amity University


Structures

Copyright@ Amity University


Structure

• A Structure is a container, it can hold a


bunch of things.
– These things can be of any type.

• Structures are used to organize related


data (variables) in to a nice neat package.

Copyright@ Amity University


Example - Student Record

• Student Record:
– Name a string
– HW Grades an array of 3 doubles
– Test Grades an array of 2 doubles
– Final Average a double

Copyright@ Amity University


Structure Members
• Each thing in a structure is called member.

• Each member has a name, a type and a value.

• Names follow the rules for variable names.

• Types can be any defined type.

Copyright@ Amity University


Example Structure Definition
struct StudentRecord {
char *name; // student name
double hw[3]; // homework grades
double test[2]; // test grades
double ave; // final average
};

Copyright@ Amity University


Using a struct

• By defining a structure you create a new


data type.
• Once a struct is defined, you can create
variables of the new type.

StudentRecord stu;

Copyright@ Amity University


Accessing Members
• You can treat the members of a struct
just like variables.
• You need to use the member access
operator '.' (pronounced "dot"):

cout << stu.name << endl;


stu.hw[2] = 82.3;
stu.ave = total/100;

Copyright@ Amity University


Structure Assignment

• You can use structures just like variables:

StudentRecord s1,s2;
s1.name = "Joe Student";

s2 = s1;
Copies the entire structure

Copyright@ Amity University


Structure Assignment
StudentRecord s1,s2;
s1.name = "Joe Student";

s2 = s1;
s2.name = “Teena";

// now s1.name and s2.name are both


// “Teena"

Copyright@ Amity University


Problems with structs

• Need a different struct for each different


data type to be pushed onto or popped off
the stack
• Overflow (although it can be fixed, using
dynamic data allocation)
• The overall structure does not convey a
tight coupling between the stack data and
the stack operations

Copyright@ Amity University


Classes and Objects

• A new data type defined with struct (where the


data and functions are together) is called a
class.
– Example: the data type stack is a class
• Indeed, C++ has a new reserved word, class,
that is synonymous to struct (except for a minor
difference explained later)
• Any variable of the type defined by struct or
class is called an object or instance of that class

Copyright@ Amity University


Definition of Members

• The declared variables inside structs are


called the data fields in C.
• In C++, the declared variables and
functions inside structs/classes are called
members:
– member variables
– member functions (also called methods)

Copyright@ Amity University


Data Hiding:
Private and Public sections
• C++, and other object-oriented programming
languages, allow the programmer to designate
certain members of a class as private, and other
members as public.
• Private members cannot be accessed from
outside the class, while public members can
• Private members are hidden (thus the term data
hiding)

Copyright@ Amity University


Initialization of Variables
• In C, initialization of variables is left to the
user.

• C++ considers initialization too important to


leave to the users’ unreliable memory to
remember to initialize.

Copyright@ Amity University


Initialization and
Constructors
• C++ requires that every class have a constructor
• The constructor is responsible for initializing
objects automatically whenever they are
declared.
• The programmer has the option to provide
his/her own constructors, which get called
whenever a new object is declared
• Otherwise, the compiler provides a default
constructor
• But what is a constructor?
Copyright@ Amity University
Constructors
• The constructor is like any other method (i.e.,
member function) in that
– it takes arguments
– it can be overloaded
– its arguments can be defaulted
• But with one big difference: It has no return
value, not even void.
• One other very important characteristic: the
constructor’s name is the same as the class
name

Copyright@ Amity University


Overloading Constructors

• Like any other function, a constructor can also


be overloaded with more than one function that
have the same name but different types or
number of parameters.
• Remember that for overloaded functions the
compiler will call the one whose parameters
match the arguments used in the function call.
• In the case of constructors, which are
automatically called when an object is created,
the one executed is the one that matches the
arguments passed on the object declaration:
Copyright@ Amity University
Class Example 1
// classes example
#include <iostream>
using namespace std;
class CRectangle
{ int x, y; public: void set_values (int,int);
int area () {return (x*y);
}
};
void CRectangle::set_values (int a, int b)
{
x = a; y = b;
}
Copyright@ Amity University
Class Example

int main ()
{
CRectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}

Copyright@ Amity University


Example 2
// example: one class, two objects
#include <iostream>
using namespace std;
class CRectangle
{
int x, y; public: void set_values (int,int);
int area ()
{
return (x*y);
}
};
void CRectangle::set_values (int a, int b)
{
x = a; y = b;
}
Copyright@ Amity University
Example 2
int main ()
{
CRectangle rect, rectb;
rect.set_values (3,4);
rectb.set_values (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() <<
endl;
return 0;
}
Copyright@ Amity University
Example 3
// example: class constructor
#include <iostream>
using namespace std;
class CRectangle
{
int width, height;
public: CRectangle (int,int);
int area ()
{
return (width*height);
}
};
CRectangle::CRectangle (int a, int b)
{
width = a;
height = b;
}
Copyright@ Amity University
Example 3

int main ()
{
CRectangle rect (3,4);
CRectangle rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}

Copyright@ Amity University


Example 4
// overloading class constructors
#include <iostream>
using namespace std;
class CRectangle
{ int width, height;
public: CRectangle ();
CRectangle (int,int);
int area (void) {return (width*height);
}
};

Copyright@ Amity University


Example 4
CRectangle::CRectangle ()
{
width = 5;
height = 5;
}
CRectangle::CRectangle (int a, int b)
{
width = a;
height = b;
}

Copyright@ Amity University


Example 4
int main ()
{
CRectangle rect (3,4);
CRectangle rectb;
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}

Copyright@ Amity University


Assignment

• Write a program to print largest


even and largest odd number
from a list of numbers entered
through keyboard. The list
terminates as soon as one enters
0.

Copyright@ Amity University


Assignment

• Write. a C++ function that


compares two strings and returns
0 if the two strings are equal and -
1 if that strings are unequal

Copyright@ Amity University


Assignment

• Write a program that reads a


password and prints “OK” if the
correct password is entered,
otherwise print “SORRY!”. The
user should be given three
chances to type the password.

Copyright@ Amity University


Thank You

Copyright@ Amity University

You might also like