The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by , 2016-03-04 02:40:15

eBook XI-XII CS-05022016

eBook XI-XII CS-05022016

http://KVSeContents.in http://eTeacher.KVSeContents.in

Functions with parameters and no return value

The function Display() is now changed to the function
DisplayValues which has to parameters a and b:

void DisplayValues(int a,int b)

{

cout << endl<<" a = "<<a <<endl <<" b = "<<b;

}

As before this function does not return a value hence
it is declared as having type void. It now takes two
parameters a and b. The parameter list consists of Data
type and a name for these formal parameters. Inside the
body of the function their values are displayed.

The function is called in the same manner as Display(),
but values must be given for the parameters a and b as
shown below.

int main()

{
int a = 2, b=4;

DisplayValues(a,b);

DisplayValues(2,4); /* Values can be given directly

with variables*/

return 0;

}

Note : Make sure that actual parameters data type must
match the formal parameters data type given in the
definition of the function.

While defining the function prototype for a function

with parameters it is not necessary to specify the

parameters names, we can simply write the Data types of

each parameter separated by comma. Thus a suitable

function prototype for the parameterised version of

DispalyValues would be:

Page 51 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

void DisplayValues(int,int); // No need to give name
for parameters

Example
#include <iostream.h>

// Function prototypes Only Data type of parameters
is specified

void DisplayValues(int,int);

int main()

{

int a,b;

cout<<"Inside Main- Enter Two Values"<<endl;

cin>>a>>b;
cout<<"Call to DisplayValues Function";

DisplayValues(a,b);
return 0;

}

void DisplayValues(int a,int b) // Function Definition

{

cout << endl<<" a = "<<a <<endl <<" b = "<<b;
}

Functions that return values

One of the most useful forms of function is one that
returns a value . In this case the return type given in
the function prototype is that of the value to be
returned.

int CalSum(int a ,int b) // Here return type is integer
which will Returns the sum of two integers

{

int c; //local variable

c = a+b;
return c; // return statement
}

The function prototype for this function is:

Page 52 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

int distance(int, int); // function prototype

Some points to note:

 The function has been given the return type int
because it is going to return a integer value.

 The parameter-list has two parameters, namely,
a and b of integer type.

 Inside the definition of CalSum there is a
return statement.

Because this function returns a value it includes a
return statement which returns the value. Return value
may be a constant, a variable or an expression. Return
statement cab be written as

return (a+b);
Example of function that will return a value
#include <iostream.h>
//Function prototypes Only Data type of parameters is
specified
int CalSum(int ,int );int main()
{

int a,b,SUM;

cout<<"Inside Main- Enter Two Values"<<endl;
cin>>a>>b;

SUM=CalSum(a,b);

//Here the value return by CalSum will be assigned to
SUM

cout<<endl<<"The Sum of a and b is = "<<SUM;

return 0;

}

int CalSum(int a ,int b)

{

int c; //local variable

c = a+b;

return c; // return statement

Page 53 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

}

Output

Inside Main- Enter Two Values

23

The Sum of a and b is = 5

Default Arguments

C++ allows a function to assign default values to
parameters. The default value is assigned when no
argument corresponding to that parameter is specified
in the call to that function. For Example :

int calSum(int a = 10, int b = 20)

{
return a+b;

}
In the above code segment, if the CalSum() function is
invoked without arguments, then the default values of
10 and 20 are assigned to a and b respectively. If
values are passed to the function, then corresponding
values are assigned to a and b.

Example of Default Arguments

//This program illustrates the use of default arguments

#include<iostream.h>
void CalSum(int a = 10, int b = 20)

{
cout<<"Sum is "<<a+b<<endl;

}
void main()

{
int a = 2, b = 4;

CalSum(); // Without Arguments Call will use Default
Arguments

CalSum(a,b); // With Arguments Call will not use
Default Arguments

Page 54 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

} Output:
Sum is 30

Sum is 6

Use of One default arguments

//This program illustrates the use of ONE default
arguments

#include<iostream.h>
void CalSum(int a , int b = 20)

{
cout<<"Sum is "<<a+b<<endl;

}
void main()

{
int a = 2, b = 4;

CalSum(a); // With one Argument Call will use ONE
Default Argument

CalSum(a,b); // With Arguments Call will not use
Default Arguments

} Output:
Sum is 22

Sum is 6
Some points to remember when using default arguments:
Default arguments must be the last argument(s)(Right to
Left). Therefore, the following code is illegal:

int CalSum(int a=20 ,int b,int c); // Wrong
int CalSum(int a ,int b=20 , int c); // Wrong
int CalSum(int a =10 ,int b=20 , int c); // Wrong
Right method to specify Default Arguments is
int CalSum(int a ,int b=10 , int c=20); // Right
int CalSum(int a =5 ,int b=10 , int c=20); // Right

Page 55 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

Call by value and Call by Reference

When C++ passes arguments to functions it passes them
by value. There are many cases when we may want to
alter a passed argument in the function and receive the
new value back to the calling function. C++ uses
pointers explicitly to do this. The best way to study
this is to look at an example where we must be able to
receive changed parameters. Let us try and write a
function to swap variables:

// Call by Value Example
#include<iostream.h>
int main()

{
void swap(int m,int m);
int a=10 ,b=20;
swap(a,b); // Call by value
cout<<"After interchanging the values ";

cout<<" a = "<<a<<endl<<"b = "<<b;
return 0;
}
void swap(int m ,int n)

{
int a;
a=m;
m=n;
n=a;
cout<<"Inside swap function the values are ";
cout<<endl<<" m = "<<m<<endl<<" n= "<<n;

}
output:
Inside swap function the values are
m=20
n=10;
After interchanging the values
a=10
b=20

Note: No change to the values of a and b inside the
calling function .Because when we pass values to the
function only the copies of those values get passed not
the original data value .Any change made inside the
called function to these data value is not reflected to

Page 56 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

the calling function. That is why we call it call by
value.
swap(a, b) WON'T WORK.

Pointers provide the solution: Pass the address of the
variables to the functions and access address of
function.

Thus our function call in our program would look like
this:

swap(&a, &b)

// Call by Reference Example

#include<iostream.h>
int main()

{

void swap(int *m,int *m);

int a=10 ,b=20;

swap(&a,&b); // Call by reference

cout<<"After interchanding the values ";

cout<<" a = "<<a<<endl<<"b = "<<b;

return 0;

}
void swap(int *m ,int *n)

{
int a;

a=*m;

*m=*n;

*n=a;

cout<<"Inside swap function the values are ";

cout<<endl<<" *m = "<<m<<endl<<" *n= "<<n;

}
output:
Inside swap function the values are

Page 57 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

*m=20
*n=10;
After interchanging the values

a=20
b=10

Note: The values of a and b changed .Because when we
pass reference of the values to the function orginal
data value are passed .Any change made inside the
called function to these data value is reflected to the
calling function. That is why we call it call by
Reference.

Page 58 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in
Array

An array is a series of elements of the same type
placed in contiguous memory locations that can be
individually referenced by adding an index to a unique
identifier.

That means that, for example, we can store 5 values of
type int in an array without having to declare 5
different variables, each one with a different
identifier. Instead of that, using an array we can
store 5 different values of the same type, int for
example, with a unique identifier.

Arrays come in two flavors: one dimensional and
dimensional arrays.

Declaring an Array

Just like any variable ,an array has to be declared
before being used. Yet the difference this time is that
you need to tell the compiler what kind of array you
are defining. This is because, once more, the compiler
wants to know how much space your array is going to
occupy in the computer memory. This is because when you
declare an array of items, the compiler puts each one
of the items in an appropriate location.
Like any other variable, the syntax of declaring an
array is:

DataType ArrayName[size]

Page 59 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

The array is first identified by its kind, which could
be a char, an int, a float, etc; followed by its name.
The name is then followed by square brackets that
specify the size of the array.

Here are examples of declaring arrays:

int a[4];

float f[100];

double d[100];

int a[4]; declares a group or array of 4 values, each
one being an integer.

float f[100]; declares an array of 100 floating-point
values.

double d[100]; declares an array of double-precision
numbers. There are 100 of these items in the group.

float f[100]; declares an array of 100 floating-point
values.
double d[100]; declares an array of double-precision
numbers. There are 100 of these items in the group.

Initializing an Array

Just like any variable can be initialized, an array
also can be initialized. To accomplish this, for a one-
dimensional array, the syntax used is:

DataType ArrayName[size] = { element1, element2, …,
elementn};

Here are examples of declaring an initializing arrays:

int num[5] = {1,2,3,4,5};

Page 60 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

If you have decided to initialize the array while you
are declaring it, you can omit the size. Therefore,
array can be declared as follows:

int num[] = {1,2,3,4,5};

Processing the Elements of an Array

After initializing an array, its elements are counted
from left to right. Each element of the array, also
called a member of the array, has a specific and
constant position. The position of an item is also
called its index. The first member of the array, the
most left, has an index of 0. The second member of the
array has an index of 1. Since each array has a number
of items which can be specified as n, the last member
of the array has an index of n-1

Based on this system of indexing, to locate a member of
an array, use its index in the group. Imagine you
declare and initialize an array as follows:

double weight[] = {20.2,24.5,34.7};

To locate the value of the 3rd member of the array, you
would type weight[2]. In the same way, the 1st member
of the array can be located with weight[0].

Once you can locate a member of the array, you can
display its value. Here is an example:

#include <iostream.h>

int main()
{

double weight[] = {20.2,24.5,34.7};

cout << "2nd member = " << weight[1] << endl;
cout << "3rd member = " << weight[2] << endl;
return 0;
}

This would produce:

2nd member = 24.5
3rd member = 34.7

The Size of an Array

Page 61 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

When declaring an array, we saw that you must specify
the number of items that the array is made of. Here is
an example:

float price[5];

Depending on how you want to deal with your array, you
may sometimes need to increase or decrease its
dimension. To do this, you would need to locate the
declaration of the array and change its dimension. If
the program is long and the array is declared in some
unusual place, this could take some time. The
alternative is to define a constant prior to declaring
the array and use that constant to hold the dimension
of the array. Here is an example:

#include <iostream.h>

int main()
{
const int SIZE = 5;
int weight[SIZE] = {20,30,40,50,60};

cout << "weight 1: " << weight[0] << endl;
cout << "weight 2: " << weight[1] << endl;
cout << "weight 3: " << weight[2] << endl;
cout << "weight 4: " << weight[3] << endl;
cout << "weight 5: " << weight[4] << endl;

return 0;
}
We knew the dimensions of the arrays we have used so
far, because we could count the number of members of
the array. Imagine you declare a large array, possibly
made of 50 or 100 members, you wouldn't start counting
the number of members. C++ provides the sizeof operator
that can be used to get the dimension of an array. The
syntax you would use is:

sizeof(NameofArray)

If we declare an array as follows:

int number[] = {1,2,3,4,5};

Instead of counting the number of members of this array
we can use the sizeof operator as follows:

int NumberOfElements = sizeof(Number)/sizeof(int);

Page 62 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

Accessing Array Members

int items[5];

Each member of the array can be located using its
index, as we have seen so far. In the same way, you can
request the value of any member of the array using its
index. In the following example, we declare an array of
5 integers and then we request the values of the 2nd
and the 4th members:

#include <iostream.h>

int main()

{
const int count = 5;

int items[count];

cout << "Enter the values of two items\n";
cout << "Item 1: ";
cin >> items[0];
cout << "item 4: ";
cin >> items[3];
cout << "\nYou have Entered following values";
cout << "\nItem 1: " << items[0] ;
cout << "\nItem 4: " << items[3] ;
return 0;
}

Here is an example of running the program:
Enter the values of two items
Item 1: 45
Item 4: 66
You have Entered following values
item 1: 45
item 4: 66

Operations on Arrays

You can add the values of two members of the
array(Number[2]+Number[0]), you can subtract the value
of one of the members from another member(member[1]-
Number[4]). In the same way, you can perform
multiplication, division, or remainder operations on
members of an array.

Sum of all the Elements of an Array

Page 63 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

#include <iostream.h>
#define N 3
int main()
{

int a1[N];
int sum=0;
int i;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)

cin>>a1[i];
// Now we will find Sum
for(i=0;i<N;i++)

sum=sum+a1[i];
cout<<endl<<"Sum of all The elements is "<<sum;
return 0;
}
Product of all the Elements of an Array
#include <iostream.h>
#define N 3
int main()
{
int a1[N];
int pro=1;
int i;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)

cin>>a1[i];
// Now we will find Product

Page 64 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

for(i=0;i<N;i++)
pro=pro*a1[i];

cout<<endl<<"Product of all The elements is "<<pro;
return 0;
}
Average of all the Elements of an Array
#include <iostream.h>
#define N 3
int main()
{

int a1[N];
int sum=0;float avg=0.0;
int i;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)

cin>>a1[i];
// Now we will find Average
for(i=0;i<N;i++)

sum=sum+a1[i];
avg=(float)sum/N;
cout<<endl<<"Average of all The elements is "<<avg;
return 0;
}
Maximum Element of an Array
#include <iostream.h>
#define N 3
int main()

Page 65 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

{
int a1[N];

int max=0;

int i;

cout<<"Enter Elements of Array";

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

cin>>a1[i];

// Now we will find Max element

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

if(max<a1[i])

max=a1[i];

cout<<endl<<"Max elements is "<<max;

cin>>i;

return 0;

}
Minimum Element of an Array

#include <iostream.h>
#define N 3
int main()
{

int a1[N];
int min=9999;
int i;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)

cin>>a1[i];
// Now we will find Min element
for(i=0;i<N;i++)

if(min>a1[i])
min=a1[i];;

cout<<endl<<"Max elements is "<<min;
return 0;
}

Page 66 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

Linear Search

Another type of operation regularly performed on an
array consists of looking for a value held by one of
its members. For example, you can try to know if one of
the members holds a particular value you are looking
for. Here is an example:

#include <iostream.h>

int main()

{
// Declare the members of the array

int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};

int find;

int i, m = 8;

cout << "Enter a number to search: ";

cin >> find;

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

if(numbers[i]==find)

cout << find << "Found" << endl;

// Find whether the number typed is a member of the
array

if (i == m)

cout << find << " Not Found"<< endl;

return 0;

}

This would produce:
Enter a number to search: 44
44 Found

Page 67 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

Counting vowels,consonants, digits, white space and
total number of characters in a String

#include<iostream.h>
int main(){

char line[150];
int i,v,c,ch,d,s;
v=c=ch=d=s=0;
cout<<"Enter a line of string:\n";
gets(line);
for(i=0;line[i]!='\0';++i)

if(line[i]=='a'||line[i]=='e'||line[i]=='i'
||line[i]=='o'||line[i]=='u')
++v;

else if(line[i]>='a'&&line[i]<='z')
++c;

else if(line[i]>='0'&&c<='9')
++d;

else if (line[i]==' ')
++s;

cout<<"Total vowels: "<<v;
cout<<"\nTotal consonants: "<<c;
cout<<"\nTotal digits: "<<d;
cout<<"\nTotal white spaces: "<<s;
cout<<"\nTotal characters: "<<i;
return 0;
}

C++ program to reverse string without using strrev

library function

#include<iostream.h>
#include<string.h>

void Reverse(char str[]);
int main(){

char str[100];
cout<<"Enter a string to reverse: ";

gets(str);

Reverse(str);

cout<<"String after reversing: ";
puts(str);

return 0;
}

void Reverse(char str[]){
int i,j;

Page 68 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

char temp[100];
for(i=strlen(str),j=0;i!=0;--i,++j){

temp[j]=str[i];
} temp[j]='\0';

strcpy(str,temp);
}

Page 69 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

Two-Dimensional Arrays

A 2-dimensional array is an array of arrays. In other
words, it is an array where each member of the array is
also an array.

Declaring and Initializing a 2-Dimensional Array

Two-dimensional array is made of rows and columns. Each
column represents one category of data that everyone of
the rows shares with the other rows. To declare it, use
double pair of a opening and closing square brackets.

Data_Type NameOfArray[ROWS][COLUMNS];

int TwoDArray[5][5];

This declarations creates 5 rows and each row contains
5 elements.

You can initialize an array the same way you would
proceed the a one-dimensional array: simply provide a
list of values in the curly brackets.

A multidimensional array is represented as an algebraic
matrix as MxN. This means that the array is made of M
rows and N columns. Total number of elements of a
multidimensional array can be calculated by multiply
the number of rows by the number of columns. Therefore
a 2x3 array contains 2*3=6 elements.

Based on this, when initializing a 2-dimensional array,
make sure you provide a number of values that is less
than or equal to the total number of elements.

Here is an example:

double age[2][3] = {12,14,16,17,17,19};

Page 70 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

To locate a member of the array, this time, each must
be identified by its double index. The first member is
indexed at [0][0]. The second is at [0][1]. For a 2x3
array as this one, the 5th member is at [1][1]. You can
use this same approach to display the values of the
members of the array. Here is an example:

#include <iostream.h>

int main()

{
// A 2-Dimensional array

int TwoDArray[2][3] = {1,2,3,4,5,6};

// Display the array

cout << "Elements of the array";
cout << "\nTwoDArray [0][0]" << ": "
<< TwoDArray[0][0];
cout << "\nTwoDArray [0][1]" << ": "
<< TwoDArray[0][1];
cout << "\nTwoDArray [0][2]" << ": "
<< TwoDArray[0][2];
cout << "\nTwoDArray [1][0]" << ": "
<< TwoDArray[1][0];
cout << "\nTwoDArray [1][1]" << ": "
<< TwoDArray[1][1];
cout << "\nTwoDArray [1][2]" << ": "
<< TwoDArray[1][2];
cout << endl;
return 0;
}

Output:

Elements of the array
TwoDArray [0][0]: 1
TwoDArray [0][1]: 2
TwoDArray [0][2]: 3
TwoDArray [1][0]: 4
TwoDArray [1][1]: 5
TwoDArray [1][2]: 6

Page 71 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

C++ also allows you to include each row in its own pair
of curly brackets. You must separate each row from the
next with a comma. Here is an example:

int items[2][3] = {

{ 1,2,3},{4,5,6}

};

Processing a 2-Dimensional Array
To process a 2D array, we should know how many columns
the array contains. We can use two for loops to process
the array. Here is an example:

#include <iostream.h>

int main()
{

// A 2-Dimensional array
int items[2][3] = {

{ 1,2,3},
{ 4,5,6}

};

// Display all elements
cout << "Elements of the array";
for(int i = 0; i < 2; ++i)

for(int j = 0; j < 3; ++j)
cout << "\nItems[" << i << "][" << j << "]: "

<< items[i][j];
cout << endl;

return 0;
}

Sum of Diagonal elements of an Two Dimensional Array

#include <iostream.h>
#define N 3
#define M 3
int main()
{

int a1[N][M],s;
int i,j;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)

for(j=0;j<M;j++)
cin>>a1[i][j];

// Now we will find sum of diagonal elements

Page 72 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

for(i=0;i<N;i++)
for(j=0;j<M;j++)
{
if(i==j)
s=s+ a1[i][j];
}

cout<<endl<<"Sum of diagonal elements of a1 and a2
is "<<s;
return 0;
}

Finding Maximum element in MXN Array

// Max Element in a two Dimensional Array

#include <iostream.h>

#define N 3

#define M 3

int main()

{
int a1[N][M];

int max=0;

int i,j;

cout<<"Enter Elements of Array";

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

for(j=0;j<M;j++)

cin>>a1[i][j];

// Now we will find Max element

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

for(j=0;j<M;j++)

{

if(max<a1[i][j])

max=a1[i][j];

}

Page 73 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

cout<<endl<<"Maximum element is "<<max;
return 0;
}
Finding Minimum element in MXN Array
// Min Element in a two Dimensional Array
#include <iostream.h>
#define N 3
#define M 3
int main()
{

int a1[N][M];
int min=9999;
int i,j;
cout<<"Enter Elements of Array";
for(i=0;i<N;i++)

for(j=0;j<M;j++)
cin>>a1[i][j];

// Now we will find Min element
for(i=0;i<N;i++)

for(j=0;j<M;j++)
{ if(min>a1[i][j])
min=a1[i][j];
}

cout<<endl<<"Minimum element is "<<min;
cin>>min;
return 0;
}

Page 74 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

2D Array and String

Because strings are in fact sequences of characters, we
can represent them also as plain arrays of char
elements.

For example, the following array:

char Ayan[20];

is an array that can store up to 20 elements of type
char. In this array, we can store sequences of
characters up to 20 characters long. But we can also
store shorter sequences. For example, Ayan could store
at some point in a program either the sequence "Hello"
or the sequence "Happy Diwali", since both are shorter
than 20 characters.

Therefore, since the array of characters can store
shorter sequences than its total length, a special
character is used to signal the end of the valid
sequence: the null character, whose literal constant
can be written as '\0' (backslash, zero).

Our array of 20 elements of type char, called Ayan, can
be represented storing the characters sequences "Hello"
and "Happy Diwali" as:

Notice how after the valid content a null character
('\0') has been included in order to indicate the end
of the sequence.

Initialization of null-terminated character sequences
If we want to initialize an array of characters with
some predetermined sequence of characters we can do it
just like any other array:

char Ayan[] = { 'H', 'e', 'l', 'l', 'o', '\0' };

In this case we would have declared an array of 6
elements of type char initialized with the characters

Page 75 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

that form the word "Hello" plus a null character '\0'
at the end.

Arrays of char elements have an additional method to
initialize their values: using string literals.String
literals enclosed between double quotes always have a
null character ('\0') automatically appended at the end
by the compiler. Therefore we can initialize the array
of char elements called Ayan with a null-terminated
sequence of characters by either one of these two
methods:

char Ayan[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char Ayan[] = "Hello";

In both cases the array of characters Ayan is declared
with a size of 6 elements of type char: the 5
characters that compose the word "Hello" plus a final
null character ('\0') which specifies the end of the
sequence and that, in the second case, when using
double quotes (") it is appended automatically.

Using null-terminated sequences of characters

Null-terminated sequences of characters are the natural
way of treating strings in C++.For example, cin and
cout support null-terminated sequences as valid
containers for sequences of characters, so they can be
used directly to extract strings of characters from cin
or to insert them into cout. For example:

// null-terminated sequences of characters
#include <iostream.h>
int main ()
{

char yourname[] = "Please, enter your first name: ";
char message [] = "Hello, ";
char name [80];
cout << yourname;
cin >> name;
cout << message << name << "!";
return 0;
}

Please, enter your first name: Sanjeev
Hello, Sanjeev!

Page 76 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

As you can see, we have declared three arrays of char
elements. The first two were initialized with string
literal constants, while the third one was left
uninitialized. In the first two arrays the size was
implicitly defined by the length of the literal
constant they were initialized to. While for name we
have explicitly specified that it has a size of 80
chars.

Page 77 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

User Defined Data Types

The C++ language allows you to create and use data
types other than the fundamental data types. These
types are called user-defined data types. There are two
ways by which a user-defined data type can be created.
The first is by using the keyword struct, and the
second is by using the keyword class. Data types
defined using the keyword struct are called structures.

Structures

In C++, a structure is a collection of variables that
are referenced by a single name. The variable can be of
different data types. They provide a convenient means
of keeping related information together. Structure
definition forms a template which is then used to
create structure variables. The variables that make up
the structure are called structure members.

The following code segment shows how a structure that
defines an roll_no and name can be created. The keyword
struct tells the compiler that a structure is being
declared.
struct student

{
int roll_no;

char name[20];

};
Notice that the structure declaration is terminated by
a semi-colon. Also, the structure name student
identifies this particular data structure. In this
structure no structure variable has been declared.

To declare a variable, you need to use the following
statement:

student stu;

This defines a structure's variable of type 'student',
called stu. When we declare a structure, we are, in
essence, defining a data type. Memory is not allocated
for a structure until a variable of that type is
created.

Page 78 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

The compiler automatically allocates sufficient memory
to accommodate all the elements that make up the
structure. We can declare structure's variables at the
time of declaring a structure.

For example:

struct student

{
int roll_no;

char name[20];

}stu;

will declare a structure type called student and
declare the variable stu.

The general form of a structure declaration is:
struct <structure_name>

{
<type> <variable1>;

<type> <variable2>;

...
...
<type> <variableN>;

}<structure vars>;

where <structure_name> is the name of the structure.
The structure name is then used to declare structure
variables. <structure vars> are the names of structure
variables.

The .(dot) Operator

Individual structure elements can be referenced by
combining the .(dot) operator and the name of the
structure variable. For example, the following
statement assigns a value of 10 to the element roll_no
of the structure variable stu declared earlier.

stu.roll_no=10;

The general form to access a structure element is:
<structure variable>.<element name>

Page 79 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

The following program illustrates input and output
operations using structures:

//structure example

#include<iostream.h>
struct student

{
int roll_no;

char name[20];

}stu;

int main()

{
cout<<"Enter Roll No:";

cin>>stu.roll_no;
cout<<"Enter Name:";

cin>>stu.name;
cout<<endl<<"Roll NO = "<< stu.roll_no<<endl<<"Name = "

<<stu.name;

return 0;

}

Enter Roll No: 11

Enter Name : Sample

Roll No = 11

Name = Sample

Passing structure variable to a function

(call by-value)
#include <iostream.h>
struct temp

{
int a, b;

};

Page 80 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

void StructPass(temp var);

int main(void)
{

temp arg;
arg.a = 123;

arg.b = 321;

StructPass(arg); // Passing structure variable
return 0;
}
void StructPass(temp var)
{
cout<<var.a;

cout<<var.b;

}

Passing structure variable to function using
(call-by-reference)

#include <iostream.h>
struct temp

{
int a, b;

};

void StructPass(temp *var);

int main(void)
{

temp arg;

// Here the name of ".(dot)" is Direct Member
Selector Operator

arg.a = 123;

arg.b = 321;

StructPass(&arg); // Passing structure variable
address

cout<<"\nInside Main ";

cout<<"\n arg.a = "<<arg.a;

Page 81 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

cout<<"\n arg.b = "<<arg.b;

return 0;
}
void StructPass(temp *var) // Pointer to structure temp
{

/* The -> (Indirect Member Selector) operator is used
when a structure element has to be accessed through
pointer. */

var->a=888;

var->b=999;

cout<<"\nInside StrutPass ";

cout<<"\nvar->a = "<<var->a;

cout<<"\nvar->b = "<<var->b;

}

Output

Inside StrutPass

var->a =888

var->b =999

Inside Main

arg.a =888

arg.b =999;

The -> Operator

The -> (Indirect Member Selector) operator is used
when a structure element has to be accessed through a
pointer.

Arrays of Structure

#include <iostream.h>
struct student
{

int age;
int roll_no;
char name[20];

Page 82 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

};
int main()
{

student data[3];// Array of 3 Structure variables
int i = 0;
cout<<endl<<"Enter age,roll no and name of three
students:";
for(i = 0; i<3 ;i++)
{ cin>>data[i].age;
cin>>data[i].roll_no;
cin>>data[i].name;
}
cout<<endl<<"Your have Entered:";
for(i = 0; i<3 ;i++)
{
cout<<data[i].age<<"\t";
cout<<data[i].roll_no<<"\t";
cout<<data[i].name<<endl;
}
return 0;
}

Passing Array of Structure to a Function

#include <iostream.h>
struct student
{

int age;
int roll_no;
char name[20];
};
int main()
{
void PassArrayStruct(student data[]);

student data[3];// Array of 3 Structure variables
int i = 0;
cout<<endl<<"Enter age,roll no and name of three
students:";
for(i = 0; i<3 ;i++)
{
cin>>data[i].age;
cin>>data[i].roll_no;
cin>>data[i].name;
}

Page 83 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

PassArrayStruct(data); // Passing Array of
Structure variables

return 0;
}
void PassArrayStruct(student data[])

{ int i;

cout<<endl<<"Accessing Values Inside PassArrayStruct
Function:";

for(i = 0; i<3 ;i++)
{ cout<<data[i].age<<"\t";
cout<<data[i].roll_no<<"\t";
cout<<data[i].name<<endl;

}

}
typedef keyword in C++

In C++, we can declare a variable using one of the
built-in data types. In the same way, we can declare an
array or a pointer. If we want to use the same data
type for many declarations of variables, we can
customize its name. The typedef keyword allows us to
create an alias for a data type. The syntax to use
typedef is:

typedef DataType AliasName;

The typedef keyword is required. The typedef keyword
can be followed by any C++ built-in data type, like
int, char, double etc. On the right side of the data
type, type the name(alias) that will be used to
represent the data type. Here is the example:

#include <iostream.h>

typedef short SmallInt;

typedef unsigned long Lint;

int main()

{ SmallInt tdef = 123;

Lint LI = 321;

Page 84 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

cout << endl <<"Use of typedef short SmallInt" <<tdef;

cout<<endl<<"Use of typedef unsigned long Lint" <<LI;

return 0;

}

Output:

Use of typedef short SmallInt 123

Use of typedef unsigned long Lint 321

With typedef short SmallInt and unsigned long Lint can
now be used as a data type to declare variables of type
small integer and unsigned long integer.

Define preprocessor macros .

Syntax:
#define identifier replacement

When the preprocessor encounters this directive, it
replaces any occurrence of identifier in the rest of
the code by replacement. This replacement can be an
expression, a statement or a block. Preprocessor simply
replaces any occurrence of identifier by replacement.
#define SIZE 100

int Number[SIZE];

int Count[SIZE];

After the preprocessor has replaced SIZE, the code
becomes equivalent to:

int Number[100];

int Count[100];

#define can also work with parameters to define
function macros:

#define getmax(a,b) a>b?a:b

This would replace any occurrence of getmax followed by
two arguments by the replacement expression.

Page 85 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

// #Define Macro Example
#include <iostream.h>
#define getmax(a,b) ((a)>(b)?(a):(b))
int main()

{
int x=5, y;

y= getmax(x,2);

cout << y << endl;

cout << getmax(7,x) << endl;

return 0;

}

Output

7

Because preprocessor replacements happen before any C++
syntax check, macro definitions can be a tricky feature
so be careful !!!.

Page 86 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

XII – COMPUTER SCIENCE UNIT –I C++

Page 87 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

Object Oriented Programming

A type of programming in which main concentration is on
DATA rather than on ALGORITHM

Characteristics of Object Oriented Programming

Data encapsulation - Encapsulation is the process of
combining data and methods into a single unit called
class.

Using encapsulation, nobody can directly access the
data. Data is only accessible through the methods
existing inside the class.

Data hiding - Hiding the implementation details of a
class from the user. To ensure this class groups its
members into three sections:

Private, protected and public

In which private and protected are hidden from the
outside world

For example –

class Kangra

{

private:
int m; // m is only accessible within the class

protected:
int n // n is only accessible within the class and

// to the subclass of Kangra
public:

int p; //p is accessible inside and outside the class
Kangra() // constructor

{}

};

Polymorphism – It is the ability for a message or data
to be processed in more than one form. An operation may
exhibit different behaviors in different instances. The
behavior depends on the data types and number of data

Page 88 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

items used in the operation. Polymorphism is
implemented using function overloading.
For example –
class Kangra
{

public:
Kangra()

{}
int area(int a)

{
return a*a;

}
int area( int a,int b); //Overloaded function

{
return a*b;

}

};

Inheritance – Inheritance is the process by which
objects of one class can acquire the properties of
objects of other class.

Inheritance provides code re-usability, like, adding
additional features to an existing class without
modifying it. This is achieved by deriving new class
from the existing one. The new class will have combined
features of both the classes.

For example-

class A

{

Public :

Page 89 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

int a ,b;
void show ()

{
cout<<a<<b;
}
};
class B: private A //Use of Inheritance
{
int c;

void dispdata ()
{
cout<<c;
}

};
Concept of Class and Object in C++
Class -A class is a blue print for creating objects.
Definition:

A class is a group of objects which show a common
property.
OR
A class is a collection of objects of similar type.Once
a class is defined, any number of objects can be
created which belong to that class.For example – Define
a class to print the values of two numbers.
Class HelloWorld
{

int one;
int two;
public:

Page 90 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

void setdata()
{
cout<<”enter two numbers”;
cin>>one>>two;
}

void putdata()
{
cout<<one<<endl<<two;
}

};

int main()
{
HelloWrold obj;
Obj.setdata();
Obj.putdata();
return 0;
}

Classes are generally declared using the keyword class,
with the following format:
class class_name
{
access_specifier_1:

member;
access_specifier_2:

member;
...
};

Page 91 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

Object -It may be defined as identifiable identity with
some characteristics and behavior.

Syntax of creating Object:

Class_name Object_Name;

If we have class named AB then the Object of this class
can be created using above syntax as

AB Obj;

Abstract class

An abstract class is a class that is designed to be
specifically used as a base class. An abstract class
contains at least one pure virtual function.

You declare a pure virtual function by using a pure
Specifier

(= 0) in the declaration of a virtual member function
in the class declaration.

The following is an example of an abstract class:

class AB {
public:

virtual void f() = 0; //Pure virtual

Function

};

Concrete class – It is a derived class that implement
all the missing functionality of a abstract class.

The following is an example of an concrete class:

class CD : public AB //Here class AB is abstract class

{ // Declare Above
public:
CD()

{ // set up the CD }
virtual f() // implementation of f() of class AB

Page 92 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

{
/* do stuff of f() */
}
};

Advantages and disadvantages of Object Oriented
Programming

Advantages –

 Re-usability of code.

 Ease of redesign and extension.

 Data can be divided as public and private.(data
protection)

 Program development becomes easy due to increased
modularity.(abstraction and encapsulation)

Disadvantages –

 The relation among classes become artificial at
times

 The object oriented programming design id
difficult.

 OOP is a high level concept so takes more time to
execute as many routines run behind at the time of
execution.

 Offers less number of functions as compared to low
level programming which interacts directly with
hardware.

Page 93 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

Access Specifiers in C++

Declaration of class:

class CLASS_NAME
{
//Access Specifier
Data Members

Member Functions

};

Data members are data type properties that describe the
characteristics of a class. There may be zero or more
data members of any type in a class.

Member functions are the set of operations that may be
applied to the objects of that class. It is the
interface between the class members and object. It is
always single it doesn’t make any copy. There may be
zero or more member functions in a class.

Program Access Level that control access to members
from within the program. These access levels are
private, protected or public. Depending upon the access
level of a class member , access to it is allowed or
denied.

Class name that serves as a type specifier for the
class using which object of this class type can be
created.

For Example

#include<iostream.h>
#include<conio.h>

class sum // class

{

int a,b,s; //data members

public:

sum() // constructor

{

Page 94 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

a=10;

b=20;

}

void show() //member function
{
s=a+b;

cout<<”sum of numbers is”<<s<<endl;

}

};

int main()
{
sum obj; //object of class
obj.show();

return 0;
}
public, protected and private are three access
specifiers in C++.

IF YOU DON'T SPECIFY ANY ACCESS SPECIFIER WITH A DATA
MEMEBR OR WITH A MEMBER FUNCTION, THE ACCESS SPECIFIER
FOR THOSE MEMBERS WILL BE TREATED AS private BY
DEFAULT.

The general form of class definition is given below.

class class-name{

private:

Data Members/Member Functions

protected:

Data Members/Member Functions

Page 95 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

public:

Data Members/Member Functions

};

The class body contains the declaration of members
(data and functions). There are generally three types
of member in a class: private, protected and public
which are grouped under three sections namely private:
protected: and public:.

The private member can be accessed only from within the
class and public members can be accessed from outside
the class also. If no access specifier (public,
protected or private) is specified then by default,
members are private.

Private variables can only be accessed by the class

Class A

{
private:
int x;
public:
void SetX(int n) { x = n; } //this is ok

};

int main()
{
A aobj;
aobj.x = 0; //error because x is private and not
accessible outside the class
}
Protected is similar to private but can also be
accessed by inherited classes

class A
{
protected:
int x;
public:
void SetX(int n) { x = n; } // this is ok
};
class B : public A
{

Page 96 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

public:
void ShowX() { cout << x << "\n"; }

// this is ok as x is protected member
};

Public member can be accessed from outside the class
Class A
{

public:

int x
void SetX(int n) { x = n; } // <<< this is ok

};
int main()
{

A aobj;

aobj.x = 0;
// Ok because x is public accessible outside the class

}

Page 97 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

Constructor and Destructor Member Functions

Constructor: - Constructor function gets invoked
automatically when an object of a class is constructed
(declared).

Destructor:- A destructor is a automatically called
member function of a class, when an object is destroyed
of that class.

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~)
BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF
THE CLASS IN WHICH THEY ARE DECLARED.

Use of Constructor and Destructor function of a class:
-

 Constructor function is used to initialize member
variables to pre-defined values as soon as an
object of a class is declared.

 Constructor function having parameters is used to
initialize the data members to the values passed
values, upon declaration.

Generally, the destructor function is needed only when
constructor has allocated dynamic memory.

Defining Constructor and Destructor functions

The example below illustrates how constructor and
destructor functions are defined:

class Kangra
{
private:
int n;

public:
Kangra() //constructor
{
n=1;
}
~Kangra() //destructor
{}
};

Page 98 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

A few points to note:

 Both of the functions have the same name as that of
the class, destructor function having (~) before
its name.

 Both constructor and destructor functions should
not be preceded by any data type (not even void).

 These functions do not (and cannot) return any
values.

 We can have only the constructor function in a
class without destructor function or vice-versa.

 Constructor function can take arguments but
destructors cannot.

 Constructor function can be overloaded as usual
functions.

Explicit call to the constructor: - By explicit call to
the constructor,means that the constructor is
explicitly declared by the programmer inside the class.

Implicit call to the constructor: - By implicit call to
the constructor,means that the constructor is
implicitly provided by the Compiler when an Object of
the Class is created and there is no Explicit
Constructor defined inside the Class.

Example 1: Explicit constructor function to initialize
data members to pre-defined values

#include<iostream.h>
class Kangra
{
private:
int a;
int b;

public:
Kangra()
{
//here constructor function is used to initialize data
members to pre-defined values
a=10;
b=10;
}

int add()
{

Page 99 of 232

http://KVSeContents.in http://eTeacher.KVSeContents.in

return a+b;
}
};
int main(void)
{
Kangra obj;
cout<<obj.add();
return 0;
}

Example 2: Explicit constructor function to initialize
data members to values passed as arguments

#include<iostream.h>
class Kangra
{
private:
int a;
int b;

public:
Kangra(int i, int j)//Explicit Constructor with
arguments
{
a=i;
b=j;
}

int add(void)
{
return a+b;
}
};
int main()
{

myclass obj(10,20); //This Can be written as Kangra obj
obj=Kangra(10,20);
cout<<obj.add();
}
Default/Implicit constructor: - These constructors are
inserted automatically by the Compiler into class
declarations that do not have any implicit constructor.

Example:

class Ayan

Page 100 of 232


Click to View FlipBook Version