http://KVSeContents.in http://eTeacher.KVSeContents.in
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);
Accessing Array Members
int items[5];
Page 151 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
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
We 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.
Deletion from an Array
#include <iostream.h>
Page 152 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
int main()
{
int array[100], position, c, n;
cout<<"Enter number of elements in array\n";
cin>>n;
for ( c = 0 ; c < n ; c++ )
cin>>array[c];
cout<<"Enter the location where you wish to delete \n";
cin>>position;
if ( position >= n+1 )
cout<<"Deletion not possible.\n";
else
{
for ( c = position - 1 ; c < n - 1 ; c++ )
array[c] = array[c+1];
cout<<"Resultant array is\n";
for( c = 0 ; c < n - 1 ; c++ )
cout<<array[c]<<endl;
}
return 0;
}
Concatenation of two Linear Arrays
#include<iostream.h>
#define N 5
int main()
{
int a1[N],a2[N],a3[N+N];
int i,j;
cout<<"Enter Elements of First Array:";
for(i=0;i<N;i++)
Page 153 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
cin>>a1[i];
cout<<"Enter Elements of Second Array:";
for(i=0;i<N;i++)
cin>>a2[i];
// Now we will Concatenate These two Arrays
for(i=0;i<N;i++)
a3[i]=a1[i];
k=i;
for(i=0;i<N;i++)
a3[k++]=a2[i];
cout<<"After Concatenation The third Array Contain:";
for(i=0;i<N+N;i++)
cout<<a3[i]<<endl;
return 0;
}
Merging of Two sorted Arrays
#include <iostream.h>
void merge(int [], int, int [], int, int []);
int main()
{
int a[100], b[100], m, n, c, sorted[200];
cout<<"Input number of elements in first array\n";
cin>>m;
for (c = 0; c < m; c++)
cin>>a[c];
cout<<"Input number of elements in second array\n";
cin>>n;
for (c = 0; c < n; c++)
cin>>b[c];
merge(a, m, b, n, sorted);
cout<<"Sorted array:\n";
for (c = 0; c < m + n; c++)
cout<<sorted[c];
return 0;
}
void merge(int a[], int m, int b[], int n, int
sorted[])
{
int i, j, k;
Page 154 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
j = k = 0;
for (i = 0; i < m + n;)
{
if (j < m && k < n)
{
if (a[j] < b[k])
{
sorted[i] = a[j];
j++;
}
else
{
sorted[i] = b[k];
k++;
}
i++;
}
else if (j == m)
{
for (; i < m + n;)
{
sorted[i] = b[k];
k++;
i++;
}
}
else {
for (; i < m + n;)
{
sorted[i] = a[j];
j++;
i++;
}
}
}
}
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>
Page 155 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
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
Binary Search
Another type of search in an Array is Binary search.
Binary search can work only on sorted array.
Page 156 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
#include <iostream.h>
int main()
{ // Declare the members of the array
int numbers[] = {12, 17, 23, 45, 50, 71, 80, 93};
int find;
int mid,low=0,high=7;
cout << "Enter a number to search: ";
cin >> find;
while(low<=high)
{
mid= (low+high)/2;
if( find==numbers[mid])
{
cout<<"Element Found";
break;
}
else if( find >numbers[mid])
low=mid+1;
Page 157 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
else
high=mid-1;
}
if(low>high)
cout<<"Element not Found";
return 0;
}
This would produce:
Enter a number to search: 23
Element Found
Bubble Sort
The basic idea of Bubble sort is to compare two
adjoining values and exchanged then if are not in
proper order.
// Example of Bubble Sort
#include <iostream.h>
int main()
{ // The members of the array
int numbers[] = {43, 36, 25, 89, 20, 52, 75, 10};
int minimum = numbers[0];
int a = 8,temp;
// Compare the members
for (int i = 0; i < 7; ++i)
for(int j=i+1;j<7;j++)
if (number[i] > number[j])
Page 158 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{ temp=number[i];
number[i]=number[j];
number[j]=temp;
}
cout << "After Sorting The Array elements are ";
for(i=0;i<7;i++)
cout<<number[i]<<endl;
return 0;
}
This would produce:
10,20,25,36,43,52,75,89.
Selection Sort
The algorithm works as follows:
Find the minimum value in the array
Swap it with the value in the first position
Repeat the steps above for the remainder of the
array (starting at the second position and
advancing each time)
Effectively, the array is divided into two parts: the
sublist of items already sorted, which is built up from
left to right and is found at the beginning, and the
sublist of items remaining to be sorted, occupying the
remainder of the array.
Here is an example of this sort algorithm sorting five
elements:
64 25 12 22 11
11 25 12 22 64
11 12 25 22 64
11 12 22 25 64
11 12 22 25 64
// Example of Selection Sort
Page 159 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
#include<iostream.h>
#define n 10
int main()
{
int a[n];
int i,j,k,temp;
int iMin;
cout<<"Enter Array Elements "<<endl;
for(k=0;k<n;k++)
cin>>a[k];
for (j = 0; j < n-1; j++)
{ /* find the min element in the unsorted a[j .. n-
1]
assume the min is the first element */
iMin = j;
// test against elements after j to find the
smallest
for ( i = j+1; i < n; i++)
{
// if this element is less, then it is the new
minimum
if (a[i] < a[iMin])
iMin = i;
}
// iMin is the index of the minimum element. Swap it
with the current position
if ( iMin != j )
{ temp=a[j];
a[j]=a[iMin];
a[iMin]=temp;
}
}
cout<<"After Selection Sort Array Elements are
"<<endl;
for(k=0;k<n;k++)
cout<<a[k]<<endl;
return 0;
}
Insertion Sort
Insertion sort is a simple sorting algorithm: a
comparison sort in which the sorted array (or list) is
built one entry at a time.
Page 160 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
How it works:
In insertion sort,elements are entered into the array
1-by-1.
When the first element is entered, it is placed at the
1st position in the array.
When a new element is entered, it is compared to our
already entered element and is decided whether to place
before or after it in the array.
Now when the third element is entered is entered, it is
compared with the greater element of the 2 already
existing elements. If smaller, then it is swapped. If
not, then the array can be considered sorted.
If swapped, then is compared with the smaller element
of the 2 already existing elements and swapped again
with it if it is even smaller.
Similarly, all the the numbers to be placed in the
array are entered 1-by-1 and placed into the correct
position right when they’re entered.
Example:
The following table shows the steps for sorting the
sequence 5 7 0 3 4 2 6 1. On the left side the sorted
part of the sequence is shown. For each iteration, the
number of positions the inserted element has moved is
shown in brackets. Altogether this amounts to 17 steps.
57034261 (0)
57034261 (0)
05734261 (2)
03574261 (2)
03457261 (2)
02345761 (4)
02345671 (1)
01234567 (6)
#include<iostream.h>
int main()
Page 161 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{
double arr[8],temp;
cout<<"Insertion sort Demonstration."<<endl<<endl;
for (int i=0;i<8;i++)
{
cout<<"Enter element number "<<i+1<<": ";
cin>>arr[i];
//Runs until the new number has been placed in its
correct place
while(j>0 && arr[j]<arr[j-1])
{
//Swap if the elements are out of order.
temp=arr[j];
arr[j]=arr[j-1];
arr[j-1]=temp;
j--; //decrease array index
}
}
cout<<endl<<"Array After Sorting = ";
for(i=0;i<8;i++)
cout<<arr[i]<<endl;
return 0;
}
Arrays and Functions
An array can be passed to a function as argument. An
array can also be returned by a function. To declare
and define that a function takes an array as argument,
declare the function as you would do for any regular
Page 162 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
function and, in its parentheses, specify that the
argument is an array. Here is an example:
You don't have to specify the dimension of the array.
This means that you can leave the square brackets
empty:
#include <iostream.h>
int main()
{
void Display(char items[]);
const int NumberOfItems = 5;
char items[NumberOfItems] = {'A','B','C','D','E'};
Display(items); //The compiler only needs the name of
the array to process it
return 0;
}
void Display(char items[])
{
for(int i = 0; i < 5; ++i)
cout << "\nItmem " << i + 1 << ": " << items[i];
cout << endl;
}
When we call a function that has an array as argument,
the compiler only needs the name of the array to
process it.
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.
Page 163 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
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,18,19};
Page 164 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
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} };
Page 165 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Representation of 2D array in memory
Let’s assume Arr is an two dimensional 2 X 2 array .The
array may be stored in memory one of the following
way :-
1. Column by column i.e column major order
2. Row by row i.e row major order.
Both representations of the above array.
Column Major Order-Column fixed for each row
Row major Order-Row fixed for each column
We know that computer keeps track of only the base
address. So the address of any specified location of an
array , for example Arr[j,k] of a 2 d array Arr[m,n]
can be calculated by using the following formula :
Column major order
Address(Arr[j][k])= base(Arr)+w[m(k-1)+(j-1)]
Row major order
Address(Arr[j][k])=base(Arr)+w[n(j-1)+(k-1)]
For example Arr[25][4] is an array with base value
200,w=4 for this array. The address of Arr[12][3] can
be calculated using
Row-major order as
Address(Arr[12][3] )= 200+4[4(12-1)+(3-1)]
Page 166 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
=200+4[4*11+2]
=200+4[44+2]
=200+4[46]
=200+184
=384
Column-major order as
Address(Arr[12][3] )= 200+4[25(3-1)+(12-1)]
=200+4[25*2+11]
=200+4[50+11]
=200+4[61]
=200+244
=444
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;
}
Finding Sum and Difference of two N X M Arrays
#include <iostream.h>
#define N 3
#define M 3
int main()
Page 167 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
{
int a1[N][M],a2[N][M],s[N][M],d[N][M];
int sum=0,i,j;
cout<<"Enter Elelemts of First Array";
for(i=0;i<N;i++)
for(j=0;j<M;j++)
cin>>a1[i][j];
cout<<"Enter Elelemts of Second Array";
for(i=0;i<N;i++)
for(j=0;j<M;j++)
cin>>a2[i][j];
// Mow we will find sum and difference
for(i=0;i<N;i++)
for(j=0;j<M;j++)
{
s[i][j] =a1[i][j]+a2[i][j];
d[i][j] =a1[i][j]-a2[i][j];
}
cout<<"Sum of a1 and a2 is";
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
cout<<s[i][j];
cout<<endl;
}
cout<<"Difference of a1 and a2 is";
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
cout<<d[i][j];
cout<<endl;
}
return 0;
}
Interchanging ROWS and COLUMN of a N X M Arrays
#include <iostream.h>
#define N 3
#define M 3
int main()
{
int a1[N][M],a2[N][M];
int i,j;
cout<<"Enter Elements Array";
for(i=0;i<N;i++)
for(j=0;j<M;j++)
Page 168 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
cin>>a1[i][j];
// Mow we will Interchange row and columns
elements
for(i=0;i<N;i++)
for(j=0;j<M;j++)
a2[j][i] =a1[i][j];
cout<<"Original Array is";
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
cout<<a1[i][j];
cout<<endl;
}
cout<<"After interchanging row and columns ";
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
cout<<a2[i][j];
cout<<endl;
}
return 0;
}
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
Page 169 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
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
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
Page 170 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
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!
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 171 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Stack
Stack is one of the important data structures that
every computer programmer should be aware of. It
follows the simple LIFO (Last In First Out) principle.
Implementation of stack can be done in many ways. One
of the simplest way is using Arrays. Here an array is
initialized to a maximum value first, lets call it
capacity. As and when we push elements onto the array,
its size will get increased. As and when we pop
elements from the array, its size will get decreased
Array Implementation of stack
//Program for Stack implementation through Array
#include <iostream.h>
#include<ctype.h>
#include<conio.h>
#define MAXSIZE 3
int stack[MAXSIZE];
int top; //index pointing to the top of stack
int main()
{
void push(int);
int pop();
int item,num;
cout<<"Enter the data to stack.";
cin>>num;
push(num);
cout<<"Enter the data to stack.";
cin>>num;
Page 172 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
push(num);
cout<<"Enter the data to stack.";// Use to check stack
full condition
cin>>num;
push(num);
cout<<"Enter the data to stack.";
cin>>num;
push(num);
item=pop();
cout<<endl<<"Top Element of the stack is "<<item;
item=pop();
cout<<endl<<"Top Element of the stack is "<<item;
item=pop();
cout<<endl<<"Top Element of the stack is "<<item;
item=pop(); // use to check stack empty condition
return 0;
}
void push(int y)
{
if(top==MAXSIZE)
{
cout<<endl<<"STACK FULL";
return;
}
else
{
top++;
stack[top]=y;
}
}
int pop()
{
int a;
top--;
if(top<0)
{
cout<<endl<<"STACK EMPTY";
return 0;
}
else
{
a=stack[top];
}
return a;
}
Page 173 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Stack implementation as Linked List
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
node *link;
};
node *top;
int main()
{
void push(int);
void pop();
void display();
int wish, num,will,a;
wish = 1;
top = NULL;
clrscr();
cout<<"Program for Stack as Linked List demo.";
while(wish == 1)
{
cout<<endl<<"Main Menu \n1.Enter data in
stack\n2.Delete from stack\n0. for Exit";
cin>>will;
switch(will)
{
case 1:
cout<<endl<<"Enter the data";
cin>>num;
push(num);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 0:
exit(0);
}
cout<<endl<<"Do you want to continue, press 1";
cin>>wish;
}
return 0;
Page 174 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
}
//THIS FUNCTION INSERT NODE IN THE TOP OF THE STACK
void push(int y)
{
node *x = new node;
x->data = y;
x->link = top;
top = x;
}
//THIS FUNCTION REMOVES TOP NODE FROM THE STACK AND
RETURNS ITS VALUE
void pop()
{
int a;
if(top==NULL)
{
cout<<"STACK EMPTY...";
return ;
}
else
{
a=top->data;
cout<<endl<<"The value at the top of stack is "<<a;
top=top->link;
}
}
//THIS FUNCTION DISPLAY ELEMENTS OF STACK
void display()
{
int i =0;
struct node * temp;
temp = top;
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp=temp->link;
}
}
Page 175 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Queue
Queue is a linear data structure in which data can be
added to one end and retrieved from the other. Just
like the queue of the real world, the data that goes
first into the queue is the first one to be retrieved.
That is why queues are sometimes called as First-In-
First-Out data structure.
In case of stack, we saw that data is inserted both
from one end but in case of Queues; data is added to
one end (known as REAR) and retrieved from the other
end (known as FRONT).
The data first added is the first one to be retrieved
while in case of queues the data last added is the
first one to be retrieved.
A few points regarding Queues:
1.Queues: It is a linear data structure; linked lists
and arrays can represent it.
2.Rear: A variable stores the index number in the array
at which the new data will be added (in the queue).
3.Front: It is a variable storing the index number in
the array where the data will be retrieved.
// Array Implementation of Queue
#include <iostream.h>
#define MAX 5
#include <stdlib.h>
int queue[MAX];
int front , rear;
void insertQ();
Page 176 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
void deleteQ();
void insertQ()
{
int value;
cout<<endl<<"Enter the element to be inserted in
queue\n";
cin>>value;
if(rear < MAX-1)
{
rear= rear +1;
queue[rear] = value;
}
else
{
cout<<"The queue is full \n";
exit(1);
}
}
void deleteQ()
{ int value;
if(front == rear)
{
cout<<"The queue is empty \n";
exit(1);
}
front = front + 1;
value = queue[front];
cout<<endl<<"The value deleted is "<<value;
}
int main()
{
int n;
front=rear=-1;
do
{
do
{
insertQ();
cout<<"Enter 1 to continue and 0 for exit\n";
cin>>n;
}while(n == 1);
cout<<endl<<"Enter 1 to delete an element and 0 for
exit" ;
Page 177 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
cin>>n;
while( n == 1)
{
deleteQ();
cout<<endl<<"Enter 1 to delete an element and 0 for
exit";
cin>>n;
}
cout<<endl<<"Enter 1 to continue and 0 for exit\n";
cin>>n;
} while(n == 1);
return 0;
}
// Linked Implementation of Queue data Structure
#include<iostream.h>
#include<stdlib.h>
struct node
{
int data;
node *link;
};
node *front=NULL;
node *rear=NULL;
void insertQ();
void deleteQ();
void display();
int main()
{
int n;
do
{
cout<<"\tMENU\n1.INSERT\n2.DELETE\n3.DISPLAY\n4.EXIT\n";
cout<<"\nEnter your choice\n";
cin>>n;
switch(n)
{
case 1:
insertQ();
break;
case 2:
deleteQ();
Page 178 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
break;
case 3:
display();
break;
case 4:
break;
default:
cout<<"Invalid choice\n";
break;
}
}while(n!=4);
return 0;
}
void insertQ()
{
int item;
node *temp = new node;
cout<<"Enter the item\n";
cin>>item;
temp->data=item;
temp->link=NULL;
if(rear==NULL)
{
front=temp;
rear=temp;
}
else
{
rear->link=temp;
rear=temp;
}
}
void deleteQ()
{
int item;
if(front==NULL)
cout<<"Queue is empty\n";
else
{
item=front->data;
cout<<"The element deleted = \n"<<item;
}
if(front==rear)
{
Page 179 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
front=NULL;
rear=NULL;
}
else
front=front->link;
}
void display()
{
n *ptr;
if(front==NULL)
cout<<"Queue is empty\n";
else
{
ptr=front;
cout<<"The elements of the queue are :";
while(ptr!=NULL)
{
cout<<ptr->data<<endl;
ptr=ptr->link;
}
}
}
Circular Queue
In circular queue, the insertion of a new element is
performed at the very first location of the queue if
the last location of the queue is full, in which the
first element comes just after the last element.
Advantages :
It overcomes the problem of unutilized space in leaner
queues, when it is implemented as arrays.
Insertion :
Rear = (rear+1)%Maxsize
Algorithm Steps:
Step 1:
create and set the variables front,rear,MAXSIZE,cq[]
step 2:
Read the circular queue operation type.
Page 180 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
step 3:
If operation type is Insertion below steps are
executed.
Assign rear=rear%MAXSIZE.
if front equal to (rear+1)%MAXSIZE then display queue
is overflow.
if front equal to -1 then assign front=rear=0.
Otherwise assign rear=(rear+1)%MAXSIZE and read queue
data
Assign cq[rear] as data.(i.e. cq[rear]=data).
step 4:
If operation type is Deletion below steps are executed.
Check front=-1 then display queue is underflow.
Set temp as cq[front] (i.e. temp=ca[front]).
Check front equal to rear if it is true then assign
front=rear=-1(Move the front to beginning)
Assign front=(front+1)%MAXSIZE.
Page 181 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
//Program for Circular Queue implementation through
Array
#include <iostream.h>
#include<ctype.h>
#include<stdlib.h>
#include<conio.h>
#define MAXSIZE 5
int cq[MAXSIZE];
int front,rear;
int main()
{
void add(int);
void del();
int will=1,i,num;
front = -1;
rear = -1;
//clrscr();
cout<<"\nProgram for Circular Queue through array";
while(1)
{
cout<<"\n\nMENU\n1.INSERTION\n2.DELETION\n3.EXIT";
cout<<"\n\nENTER YOUR CHOICE : ";
cin>>will;
switch(will)
{
case 1:
cout<<"\n\nENTER THE QUEUE ELEMENT : ";
cin>>num;
add(num);
break;
case 2:
del();
break;
case 3:
exit(0);
default:
cout<<"\n\nInvalid Choice . ";
}
} //end of outer while
return 0;
} //end of main
void add(int item)
{
//rear++;
Page 182 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
//rear= (rear%MAXSIZE);
if(front ==(rear+1)%MAXSIZE)
{
cout<<"\n\nCIRCULAR QUEUE IS OVERFLOW";
}
else
{
if(front==-1)
front=rear=0;
else
rear=(rear+1)%MAXSIZE;
cq[rear]=item;
cout<<"\n\nRear = "<<rear<<" Front = "<<front;
}
}
void del()
{
int a;
if(front == -1)
{
cout<<"\nCIRCULAR QUEUE IS UNDERFLOW";
}
else
{
a=cq[front];
if(front==rear)
front=rear=-1;
else
front = (front+1)%MAXSIZE;
cout<<"\n\nDELETED ELEMENT FROM QUEUE IS : "<<a;
cout<<"\n\nRear = "<<rear<<" Front = "<<rear;
}
}
Page 183 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
XII – COMPUTER SCIENCE UNIT–III MYSQL
Page 184 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Database
Databases are designed to offer an organized mechanism
for storing, managing and retrieving information. They
do so through the use of tables. In simple terms we can
say that in a Database the data is stored in Rows and
Columns.
If you’re familiar with spreadsheets like Open Office
Calc, you can easily understand the concept of Database
Storage.
Database Tables
Database tables consist of columns and rows. Each
column contains a different type of attribute and each
row corresponds to a single record. For example,
imagine that we are building a database table that
contained student's details. We will probably set up
columns named “Rollno”, “Name” , “Class” and
"Address" .Then we simply start by adding rows those
contains our data.
If we are building a table of student's information for
our school that has 550 students, then this table will
have 550 rows.
DBMS (Database Management System)
Page 185 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
A Database Management System (DBMS) is a set of
computer programs that controls the creation,
maintenance, and the use of a database. A DBMS is a
system software package that helps the use of
integrated collection of data records and files known
as databases. It allows different application programs
to easily access the same database. A DBMS also
provides the ability to logically present database
information to the users.
Example of Commonly used DBMS
MYSQL,Oracle ,SQL SERVER 2000,MS Access
Advantages and disadvantages of DBMS
Advantages:
Reduced data redundancy (Duplication of data)
Reduced updating errors and increased consistency
Greater data integrity and independence from
applications programs
Improved data security
Reduced data entry, storage, and retrieval costs
Disadvantages
Database systems are complex, difficult, and time-
consuming to design
Page 186 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Damage to database affects virtually all applications
programs
Initial training required for all programmers and
users.
Relational database
Relational database was proposed by Edgar Codd around
1969. It has since become the dominant database model
for commercial applications. Today, there are many
commercial Relational Database Management System
(RDBMS), such as Oracle, IBM DB2 and Microsoft SQL
Server and many free and open-source RDBMS, such as
MySQL, PostgreSQL are available.
A relational database organizes data in tables (or
relations). A table is made up of rows and columns. A
row is also called a record (or tuple). A column is
also called a field (or attribute). A database table is
similar to a spreadsheet. However, the relationships
that can be created among the tables enable a
relational database to efficiently store huge amount of
data, and effectively retrieve selected data.
Relational Model Concepts
Relation - table of values. Row is collection of
related data values corresponding to real-world entity
Tuple – Row in a relation
Page 187 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Attribute - Column header or Column name of the
Relation
Domain - Set of atomic values permissible for a Column
or an attribute. If the data type of a particular
column in a relation is Number then the domain of that
attribute is a number formed from the digit 0-9 e.g
123,398 etc.
Atomic - Value is indivisible, as far as relational
model is concerned
Degree - Number of attributes in a relation
Cardinality -Number of rows/tuples in a relation
A language called SQL (Structured Query Language) was
developed to work with relational databases.
Page 188 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Example Table
Relational Algebra
Algebra is a formal structure consisting of sets and
operations on those sets. Relational algebra is a
formal system for manipulating relations.
Operands of this Algebra are relations. set
Operations of this Algebra include the usual for
operations and special operations defined
relations such as :
selection
projection
join
Set Operations on Relations
For the set operations on relations, both operands must
have the same schema, and the result has that same
schema.
R1 U R2 (union) is the relation containing all
tuples that appear in R1, R2, or both.
R1 n R2 (intersection) is the relation containing
all tuples that appear in both R1 and R2.
R1 - R2 (set difference) is the relation containing
all tuples of R1 that do not appear in R2.
Selection
Selects tuples from a relation whose attributes meet
the selection criteria, which is normally expressed as
a predicate.
R2 = select(R1,P)
Page 189 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
That is, from R1 we create a new relation R2 containing
those tuples from R1 that satisfy the predicate P.
A predicate is a Boolean expression whose operators are
and, or, not and arithmetic comparisons (LT, LE, GT,
GE, EQ, NE), and whose operands are either domain names
or domain constants.
select(students,Class=XII)
Projection
Chooses a subset of the columns in a relation, and
discards the rest.
R2 = project(R1,D1,D2,...Dn)
That is, from the tuples in R1 we create a new relation
R2 containing only the domains D1,D2,..Dn.
project(Students,Name,Address)
Union
R UNION S
Includes all tuples that are in either R or S.
Duplicate tuples are removed.
For a union operation r U s to be valid, two conditions
must hold:
Page 190 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
The relation r and s must be of the same arity, i.e.
they must have the same number of attributes.
The domains of the ith attribute of r and the ith
attribute of s must be the same for all i.
Example:
Join
Combines attributes of two relations into one.
R3 = join(R1,D1,R2,D2)
Given a domain from each relation, join considers all
possible pairs of tuples from the two relations, and if
their values for the chosen domains are equal, it adds
a tuple to the result containing all the attributes of
both tuples (discarding the duplicate domain D2).
Natural join: If the two relations being joined have
exactly one attribute (domain) name in common, then we
assume that the single attribute in common is the one
being compared to see if a new tuple will be inserted
in the result.
Page 191 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
OUTER JOIN
Notice that much of the data is lost when applying a
join to two relations. In some cases this lost data
might hold useful information. An outer join retains
the information that would have been lost from the
tables, replacing missing data with nulls. There are
three forms of the outer join, depending on which data
is to be kept.
LEFT OUTER JOIN - keep data from the left-hand table
RIGHT OUTER JOIN - keep data from the right-hand table
FULL OUTER JOIN - keep data from both tables
Page 192 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Cartesian Product
The Cartesian Product is also an operator which works
on two sets. It is sometimes called the CROSS PRODUCT
or CROSS JOIN. It combines the tuples of one relation
with all the tuples of the other relation.
Example
RXS=
Set Operations on Relations
For the set operations on relations, both operands must
have the same schema, and the result has that same
schema.
R1 U R2 (union) is the relation containing all tu-
ples that appear in R1, R2, or both.
R1 n R2 (intersection) is the relation containing
all tuples that appear in both R1 and R2.
R1 - R2 (set difference) is the relation containing
all tuples of R1 that do not appear in R2.
Page 193 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL is an ANSI (American National Standards
Institute) standard
Note: SQL is not case sensitive. SELECT is the same
as select.
What Can SQL do?
1.SQL can retrieve data from a database/table
2.SQL can insert records in a database/table
3.SQL can update records in a database/table
4.SQL can delete records from a database/table
5.SQL can create new databases/table
6.SQL can create new tables in a database/table
SQL DML and DDL
SQL can be divided into two parts:The Data Manipulation
Language (DML) and the Data Definition Language (DDL).
DML Commands:
SELECT - extracts data from a table
UPDATE - updates data in a table
DELETE - deletes data from a table
INSERT INTO - inserts new data into a table
DDL Commands:
1. CREATE DATABASE - creates a new database
2. CREATE TABLE - creates a new table
3. ALTER TABLE - modifies a table
4. DROP TABLE - delete a table
5. CREATE INDEX - creates an index
6. DROP INDEX - deletes an index
Page 194 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
Data Types
Max Size:
Data type Description
VARCHAR2(size) Variable length character 32767 bytes
string having maximum minimum is 1
length size bytes.
You must specify size
CHAR(size) Fixed length character
data of length size bytes. 32767
Integer/INT Integer Number.
DECIMAL(p,s)
Number having Magnitude
DATETIME precision p and scale s.
1E-130 ..
10E125
A date and time
combination in YYYY-MM-DD
HH:MM:SS format
DATE A date in YYYY-MM-DD
format
The CREATE DATABASE Command
The CREATE DATABASE statement is used to create a
Database.
SQL CREATE DATABASE Syntax
CREATE DATABASE database_name
CREATE DATABASE Example
CREATE DATABASE KVPALAMPUR ;
This command will create a Database with the name
KVPALAMPUR
Page 195 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
The CREATE TABLE Command
The CREATE TABLE statement is used to create a table in
a database.
SQL CREATE TABLE Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
....
)
The data type specifies what type of data the column
can hold.
CREATE TABLE Example
Now we want to create a table called "Student" that
contains four columns: Roll_No, Name, Class, City.
We use the following CREATE TABLE statement:
CREATE TABLE Student
(
Roll_No integer,
Name varchar(30),
Class varchar(5),
City varchar(30)
)
The Roll_No column is of type integer and will hold a
number. The Name, Class and City columns are of type
varchar and will hold character data. The empty
"Student" table will now look like this:
Page 196 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
The DROP TABLE Command
The DROP TABLE statement is used to delete a table .
Syntax:
DROP TABLE table_name
Example:
Suppose if we want to drop table student, we can use
DROP TABLE command like this
Drop Table Student ;
Note: Before using Drop Command make sure that table
has no records exist. Drop command will not work on a
table if it has has some records.
The ALTER TABLE Command
The ALTER TABLE statement is used to add, delete, or
modify columns in an existing table.
SQL ALTER TABLE Syntax
To add a column in a table, use the following syntax:
ALTER TABLE table_name ADD column_name data-type
To delete a column in a table, use the following
syntax
ALTER TABLE table_name DROP COLUMN column_name
To change the data type of a column in a table, use the
following syntax:
ALTER TABLE table_name MODIFY column_name data-type
Page 197 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
SQL ALTER TABLE Example
Look at the "Student" table:
Now we want to add a column named "DateOfBirth" in the
"Student" table.
We use the following SQL statement:
ALTER TABLE Student ADD DateOfBirth date
The "Student" table will now like this:
Change Data Type Example
Now we want to change the data type of the column named
"Class" in the "Student" table.
We use the following SQL statement:
ALTER TABLE Student ALTER COLUMN Class integer
Notice that the "Class" column is now of type integer.
DROP COLUMN Example
Next, we want to delete the column named "DateOfBirth"
in the "Student" table.
We use the following SQL statement:
ALTER TABLE Student DROP COLUMN DateOfBirth
The "Student" table will now like this:
Page 198 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
DML Commands:
Quotes Around Text Fields
SQL uses single quotes around text values (most
database systems will also accept double quotes).
However, numeric values should not be enclosed in
quotes.
For text values:
This is correct:
SELECT * FROM Student WHERE Name='Abhey'
This is wrong:
SELECT * FROM Student WHERE Name=Abhey
For numeric values:
This is correct:
SELECT * FROM Student WHERE Roll_No=2
This is wrong:
SELECT * FROM Student WHERE Roll_No='2'
The INSERT INTO Command
The INSERT INTO Command is used to insert a new record
in a table.
INSERT INTO Syntax
We can write INSERT INTO command in two forms.
The first form doesn't specify the column names where
the data will be inserted, only their values:
Page 199 of 232
http://KVSeContents.in http://eTeacher.KVSeContents.in
INSERT INTO table_name VALUES (value1, value2,
value3,...)
The second form specifies both the column names and the
values to be inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
SQL INSERT INTO Example
We have the following "Persons" table:
Now we want to insert some records in the "Student"
table.
We use the following SQL statement:
INSERT INTO Student VALUES (1,'Amisha', 'XII',
'Palampur')
INSERT INTO Student VALUES (2,'Usha', 'XII', 'Holta')
INSERT INTO Student VALUES (3,'Sneh', 'XII',
'Palampur)
INSERT INTO Student VALUES (4,'Nishant', 'XI',
'Baijnath')
INSERT INTO Student VALUES (5,'Gaurav', 'XI',
'Paprola')
The "Student" table will now look like this:
Page 200 of 232