Showing posts with label Algorithms. Show all posts
Showing posts with label Algorithms. Show all posts

Swap two variables without using third and in one line

Couple of weeks back I was interviewing a fresh graduate. Even though they are taught programming, I am not sure if they take it seriously and learn or practice it well. One of the questions I asked was to swap 2 numbers without using a temp variable.

Looking back now, I think it may be a bigger challenge to ask to swap numbers without using a temp variable and in one line. Below are my three different approaches but I would advise you to try it yourself before looking at the answer.


//Program to swap 2 numbers without using 3rd variable and in one line
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

void
approach1(int& a, int& b)
{

cout<<"\nApproach 1"<<endl;
a^=b^=a^=b;
}


void
approach2(int& a, int& b)
{

cout<<"\nApproach 2"<<endl;
//b=(a+b)-(a=b); - This should work but doesnt, why?
a =((a = a + b) - (b = a - b));
}


void
approach3(int& a, int& b)
{

cout<<"\nApproach 3"<<endl;
a = ((a = a * b) / (b = a / b));
}




int
main()
{

int
a = 13, b = 29;
cout<<"\nOriginal"<<endl;
cout<<"a = "<<a<<", b = "<<b<<endl;

approach1(a, b);
cout<<"a = "<<a<<", b = "<<b<<endl;

a = 13, b = 29;
approach2(a, b);
cout<<"a = "<<a<<", b = "<<b<<endl;

a = 13, b = 29;
approach3(a, b);
cout<<"a = "<<a<<", b = "<<b<<endl;

return
0;
}


The output is as follows:
Agreed that the above would be applicable only for integers.

Example of Permutations in C++

Example of how you can let the Algorithm class generate permutations of String



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>

using namespace
std;

int
main()
{

string someString="ABC";
vector<string> someVector;

someVector.push_back(someString);

string::iterator itBegin = someString.begin();
string::iterator itEnd = someString.end();

while
(next_permutation(itBegin, itEnd)) //std::next_permutation defined in algorithm
{
someVector.push_back(string(itBegin, itEnd));
}

copy(someVector.begin(), someVector.end(), ostream_iterator<string>(cout, "\n"));

return
0;
}



The output is as follows:


Some Operations on Matrix

A few days back someone asked me a question via email which I thought might
be useful to others too. So I’m listing that question along with its answer
below.


Q. I want to write a program such that users enter the value of matrix
and each operation (listed below) is performed by functions. I want to use switch
structure to call the functions.


1. Rotate the matrix around the diagonal.


Example:


   1 2 3 ---> 1 4 7
4 5 6 2 5 8
7 8 9 3 6 9

2. Rotate the matrix around the middle row.


Example:


   1 2 3 ---> 7 8 9
4 5 6 4 5 6
7 8 9 1 2 3

3. Rotate the matrix around the middle column.


Example:


   1 2 3 ---> 3 2 1
4 5 6 6 5 4
7 8 9 9 8 7

4. Set the upper triangle to zero.


Example:


   1 2 3 ---> 1 0 0
4 5 6 4 5 0
7 8 9 7 8 9

Ans. The following program does it. Please note that the matrix
is declared as global so as to reduce complications in the program. Better way
should have been to pass the matrix (local) to the functions from main().



// Program that does some Rotations
// about certain axes in two
// dimensional arrays
#include <iostream.h>

// change this to hold more
// values in the array
#define MAX 3

// it is declared to be global
// so that every function can access it
int ar[MAX][MAX];

// function prototypes
void EnterVal();
void rDiagonal();
void rMidRow();
void rMidCol();
void sUpperZero();
void Show();

void main()
{
int ch;

// loop until 'quit' is not selected
while(ch!=6)
{
cout<<"1> Enter Values\n";
cout<<"2> Rotate around Diagonal\n";
cout<<"3> Rotate around the Middle row\n";
cout<<"4> Rotate around the Middle column\n";
cout<<"5> Set the Upper triangle to zero\n";
cout<<"6> Quit\n\n";

cin>>ch;

// do as per choice
switch(ch)
{
case 1:
EnterVal();
break;

case 2:
rDiagonal();
Show();
break;

case 3:
rMidRow();
Show();
break;

case 4:
rMidCol();
Show();
break;

case 5:
sUpperZero();
Show();
break;
}
}
}

// --------------------
// Function Definitions
void EnterVal()
{
int i,j;

cout<<"Enter Values\n";

for(i=0;i<MAX;i++)
for(j=0;j<MAX;j++)
cin>>ar[i][j];
}

void rDiagonal()
{
int temp,i,j;

for(i=0;i<MAX;i++)
for(j=i;j<MAX;j++)
{
temp=ar[i][j];
ar[i][j]=ar[j][i];
ar[j][i]=temp;
}
}

void rMidRow()
{
int temp,i,j;

for(i=0;i<(MAX-1)/2;i++)
for(j=0;j<MAX;j++)
{
temp=ar[(MAX-1)-i][j];
ar[(MAX-1)-i][j]=ar[i][j];
ar[i][j]=temp;
}
}

void rMidCol()
{
int temp,i,j;

for(i=0;i<MAX;i++)
for(j=0;j<(MAX-1)/2;j++)
{
temp=ar[i][(MAX-1)-j];
ar[i][(MAX-1)-j]=ar[i][j];
ar[i][j]=temp;
}
}

void sUpperZero()
{
int i,j;

for(i=0;i<(MAX+1)/2;i++)
for(j=i;j<MAX-i;j++)
ar[i][j]=0;
}

void Show()
{
int i,j;

for(i=0;i<MAX;i++)
{
for(j=0;j<MAX;j++)
cout<<ar[i][j]<<" ";

cout<<endl;
}
cout<<"\n\n";
}


Related Articles:


How String Functions (string.h) Work?

In the previous article String
Manipulation Functions (string.h)
, we had a look at some of the commonly
used string manipulation functions. There is no denying the fact that those
functions are useful but have you ever wondered how those functions actually
work or what is the algorithm behind their working?


If yes then read on…


In this article I am going to present you with our own version of the string
manipulation functions that we had discussed, namely strlen(), strcpy(),
strcat() and strcmp()
. Our versions will do the same thing as done
by the original functions but surely they would teach us a lot!


Let's have a look at them one-by-one:


mystrlen


  // mystrlen- function 
#include<iostream.h>

int mystrlen(const char *);

void main(void)
{
char ch[]="This is great!";
cout<<"Length:"<<mystrlen(ch);
}

int mystrlen(const char *str)
{
int len=0;

while(str[len]!='\0')
len++;
return len;
}

mystrcpy


  // mystrcpy- function 
#include<iostream.h>

void mystrcpy(char *,const char *);

void main(void)
{
char ch[]="This is great!";
char ch2[20];

mystrcpy(ch2,ch);

cout<<ch;
cout<<endl;
cout<<ch2;
}

void mystrcpy(char *str1,const char *str2)
{
int i=0;

// copy each character
while(str2[i]!='\0')
{
str1[i]=str2[i];
i++;
}
// put the end of
// string identifier
str1[i]='\0';
}

mystrcat


  // mystrcat- function 
#include<iostream.h>

void mystrcat(char *,const char *);

void main(void)
{
char ch[]="This is great!";
char ch2[25]="Yes ";

mystrcat(ch2,ch);

cout<<ch;
cout<<endl;
cout<<ch2;
}

void mystrcat(char *str1,const char *str2)
{
int i=0;
int len=0;

// skip to the end of the first
// string(target)
while(str1[len]!='\0')
len++;

// start copying characters
// from the start of the
// second string (source)
// to the end of the
// first (target)
while(str2[i]!='\0')
{
str1[len]=str2[i];
i++;len++;
}
str1[len]='\0';
}

mystrcmp


  // mystrcmp- function
#include<iostream.h>

int mystrcmp(char *,const char *);

void main(void)
{
char ch[]="C++";
char ch2[]="C++";

cout<<mystrcmp(ch2,ch);
}

int mystrcmp(char *str1,const char *str2)
{
int i=0,cmp=-1;

while(str1[i]!='\0')
{
if(str1[i]==str2[i])
{
// check one character
// following it, so that
// end of string is also
// compared
if(str1[i+1]==str2[i+1])
cmp=0;
// if not same then check
// to see which string has
// higher ASCII value for the
// non-matching charcter
else if(str1[i+1]<str2[i+1])
{
cmp=-1;
break;
}
else
{
cmp=1;
break;
}
}
else if(str1[i]<str2[i])
{
cmp=-1;
break;
}
else
{
cmp=1;
break;
}
i++;
}
return cmp;
}

Good-Bye!


Related Articles:


Introduction to Linked Lists III

In the article Introduction
to Linked Lists
, we introduced the concept of linked list, the example
program was programmed to be able to add and display the elements in the linked
list. In reality only addition of elements to the linked list is not enough
to take the most out of linked list; we should be able to do other operations
such as insertion, deletion of elements etc.


This article would teach you to do such operation (insertion, addition, deletion
etc).


The program itself is quite big and has enough comments so I won’t discuss
anything here; rather I leave it up to you to understand all the operations
yourself!


  // -- Linked Lists --
// ------------------
// Example program to illustrate
// addition, insertion, deletion
// and display of nodes in the
// linked list

#include<iostream.h>

// node class, this will
// represent the nodes or elements
// of the linked list
class node
{
public:
int info;
node *link;
};

// declare global objects
node *start=NULL;

// function prototypes
void insert(int, int);
void add(int);
void display(void);
void del(int);
void free();

void main(void)
{
int ch,pos,num;

while(ch!=5)
{
cout<<"1> Add";
cout<<"\n2> Insert";
cout<<"\n3> Delete";
cout<<"\n4> Display";
cout<<"\n5> Quit\n";

cin>>ch;

switch(ch)
{
case 1:
cout<<"enter element:";
cin>>num;

add(num);
break;

case 2:
cout<<"enter pos:";
cin>>pos;
cout<<"enter element:";
cin>>num;
insert(pos,num);
break;

case 3:
cout<<"enter element to be deleted:";
cin>>num;
del(num);
break;

case 4:
display();
break;
}
}

// free-up the allocated
// memory
free();
}

// --FUNCTION--
// this function takes two
// arguments, 'loc' is the
// number of elements after
// which the new element having
// value 'inf' has to be inserted
void insert(int loc,int inf)
{
node *temp;
node *temp_new;
int i;

// if invalid, return
if(loc<=0) return;

temp=start;

// skip to the desired
// location where the node
// is to be added
for(i=1;i<loc;i++)
{
temp=temp->link;
if(temp==NULL)
{
cout<<"NOT POSSIBLE!";
return;
}
}

// allocate new node
temp_new=new node;
temp_new->info=inf;
// make it point to the
// respective node
temp_new->link=temp->link;
// make the prev. node where
// the new node is added, to
// point at the new node
temp->link=temp_new;
}

  // --FUNCTION--
// display all the data
// in the linked list
void display(void)
{
node *temp;
temp=start;

// traverse or process
// through each element
// and keep printing
// the information
cout<<"\nelements are...\n";
while(temp!=NULL)
{
cout<<temp->info<<endl;
temp=temp->link;
}
}

// --FUNCTION--
// adds node to the end
// of the linked list
void add(int inf)
{
node *temp1;
node *temp2;

// if the element to be added
// is the first element
if(start==NULL)
{
// allocate a new node
temp1=new node;
temp1->info=inf;
temp1->link=NULL;

// make start point at it
start=temp1;
}
// if not
else
{
temp1=start;

// find out the last element
while(temp1->link!=NULL)
temp1=temp1->link;

// allocate new node
temp2=new node;
temp2->info=inf;
temp2->link=NULL;

// make the last element
// of the list to point
// at the newly created node
temp1->link=temp2;
}
}

// --FUNCTION--
// takes the argument of the
// 'info' part of the node
// to be deleted
void del(int inf)
{
node *temp, *old;

temp=start;

// while list not empty
while(temp!=NULL)
{
// if match is found
if(temp->info==inf)
{
// if it is the
// first node
if(temp==start)
start=temp->link;

else
old->link=temp->link;

delete temp;
return;
}
else
{
// traverse through
// each node
old=temp;
temp=temp->link;
}
}
}

// --FUNCTION--
// free up the allocated memory
// used by the nodes of the
// linked list
void free()
{
// below is a bit confusing
// part.
// here all the nodes that
// we have allocated are
// being freed up
node temp;
while(start!=NULL)
{
// store the next node
// to the one being deleted
temp=*start;

// delete the node
delete start;

// retrieve the next node
// to be deleted
start=temp.link;
}
}

Good-Bye!


Related Articles:


Introduction to Linked Queues

In one of the article Introduction
to Linked Stacks
, I said that representing data structures such as
Stacks and Queues as arrays had one major problem that it can’t have more
than a predefined number of elements. To overcome this we used linked lists
to represent stacks. In this article we’ll use linked lists to represent
queues.


Below are some graphics that illustrate the addition and retrieval of elements
to and from the linked queue.



Addition of elements in the linked queue


FIG.: Addition of data to the linked queue




FIG.: Retrieval of elements from the linked
queue




I don’t think there is anything more that needs to be discussed, so let’s
have a look at the example program:


  // -- Linked Queues --
// C++ Example Program to
// illustrate the representation
// of queues as linked lists
#include<iostream.h>

// node class, this will
// represent the nodes or elements
// of the linked queues
class node
{
public:
int info;
node *link;
};

// declare global objects
node *front=NULL;
node *rear=NULL;

// function prototypes
void add(int);
int retrieve();
void free();

void main(void)
{
int ch=0,num;

while(ch!=3)
{
cout<<"1> Add";
cout<<"\n2> Retrieve";
cout<<"\n3> Quit\n";

cin>>ch;

switch(ch)
{
case 1:
cout<<"enter element:";
cin>>num;

add(num);
break;

case 2:
cout<<"\n\Retrieved: ";
cout<<retrieve();
cout<<"\n\n";
break;
}
}

// free up the memory
free();
}

// function to add new nodes
// to the linked queue
void add(int inf)
{
node *temp;

temp=new node;

temp->info=inf;
temp->link=NULL;

if(front==NULL)
{
rear=front=temp;
return;
}

rear->link=temp;
rear=rear->link;
}

// function to retrieve
// data from the linked
// queue
int retrieve()
{
node *temp;
int inf;

if(front==NULL)
{
cout<<"Queue Empty!\n";
return NULL;
}

inf=front->info;
temp=front;
front=front->link;

delete temp;
return inf;
}

// free the dynamic memory
// allocated in the form of
// nodes of the linked queue
void free(void)
{
// below is a bit confusing
// part.
// here all the nodes that
// we have allocated are
// being freed up
node temp;
while(front!=NULL)
{
// store the next node
// to the one being deleted
temp=*front;
// delete the node
delete front;

// retrieve the next node
// to be deleted
front=temp.link;
}
}

Good-Bye!


Related Articles:


Introduction to Linked Stacks

In the article Data
Structures: Introduction to Stacks
, we saw that there was one major
disadvantage of representing stacks using arrays- the stack like the array could
have a limited number of elements, while stacks should be able to grow up to
any number of elements. Besides this there were other disadvantages too.


In one of the other article about Linked
Lists
, we noticed one useful property of linked lists that they can
grow up to any size to accommodate for the addition of elements and it efficiently
uses the memory too.


So if we combine both of this to from a linked version of the stack then it
won’t have the shortcomings that the array version had.


This is what this article is all about.


pushing and popping


As you know that addition of elements to the stack is known as pushing while
retrieval is known as popping.


The process of pushing and popping in case of linked version of stack is slightly
different from the array version. The following graphics will clear it though!


pushing of elements in the linked stack


FIG: pushing of elements in the linked stack





popping of the elements from the linked stack


FIG: popping of the elements from the linked
stack





Now that you know how the basic operations are performed on linked stacks I
present you with the example program to illustrate this.


As always I would strongly recommend you to read the comments!


  // -- Linked stacks --
// Example program to
// illustrate basic
// push and pop to a
// linked stack
#include<iostream.h>

// node class, this will
// represent the nodes or elements
// of the linked stacks
class node
{
public:
int info;
node *link;
};

// declare global objects
node *start=NULL;

// function prototypes
void push(int);
int pop();

void main(void)
{
int ch=0,num;

while(ch!=3)
{
cout<<"1> Push";
cout<<"\n2> Pop";
cout<<"\n3> Quit\n";

cin>>ch;

switch(ch)
{
case 1:
cout<<"enter element:";
cin>>num;

push(num);
break;

case 2:
cout<<"\n\nPopped: ";
cout<<pop();
cout<<"\n\n";
break;
}
}

// below is a bit confusing
// part.
// here all the nodes that
// we have allocated are
// being freed up
node temp;
while(start!=NULL)
{
// store the next node
// to the one being deleted
temp=*start;
// delete the node
delete start;

// retrieve the next node
// to be deleted
start=temp.link;
}
}

// pushes an element 'inf'
// to the linked stack
void push(int inf)
{
node *temp1;
node temp2;

// if the element to be added
// is the first element of
// linked stack
if(start==NULL)
{
// allocate a new node
temp1=new node;
temp1->info=inf;
temp1->link=NULL;

// make start point at it
start=temp1;
}
// if not
else
{
// store the information
// about the node pointed
// by 'start'
temp2.info=start->info;
temp2.link=start;

temp1=new node;
temp1->info=inf;
// insert the new node
// at the beginning
// and make its link
// point to the prev.
// node pointed by 'start'
temp1->link=temp2.link;

start=temp1;
}
}

// returns an element from the
// linked stack
int pop()
{
node temp;

if(start!=NULL)
{
// store info. about
// the first element
// that has to be pooped
temp=*start;

// delete the node
delete start;
// make start point at the
// next node which had been
// stored
start=temp.link;

return temp.info;
}

return NULL;
}

Good-Bye!


Related Articles:


Introduction to Basic Encryption and Decryption

Encryption is a familiar sounding word which means to convert readable data
in such a form that it becomes un-understandable or un-meaningful. It is employed
almost everywhere where any confidential data is needed to be kept or transferred.


Encryption goes hand in hand with decryption which means to convert un-meaningful
encrypted data to its original meaningful form.


Here in this article we are going to design two functions, one for encryption
and other for decryption, to illustrate the basic concept of encryption and
decryption.


Please note that the example program provided in this article is for illustrative
purpose only, there are a few limitations in the program which limits its practical
use.


How encryption and decryption works?


The main concept behind encryption is to convert the readable data into something
which looks un-meaningful to us. It could be achieved in various ways but the
simplest one is to change the ASCII code of the data.


Ex.


  #include<iostream.h>

void main(void)
{
int i;
char str[20]="I like C++";

for(i=0;str[i]!='\0';i++)
str[i]+=10;

cout<<"Encrypted:\n";
cout<<str;
cout<<endl<<endl;

for(i=0;str[i]!='\0';i++)
str[i]-=10;

cout<<"Decrypted:\n";
cout<<str;
cout<<endl;
}

OUTPUT:


   Encrypted:
S*vsuo*M55

   Decrypted:
I like C++
Press any key to continue

In the above example we increased the ASCII code of each character of the string
by 10, notice how un-meaningful the encrypted data looks!


While decrypting we need to reverse the process by decreasing the ASCII code
of each character by 10, which would give us the original data.


This concept will form the basis of encryption and decryption in for our program
which is listed below:


  // A simple c++ program to
// illustrate basic encryption
// and decryption
#include<iostream.h>

#define FACTOR 95

void encrypt(char *);
void decrypt(char *);

void main(void)
{
char str[20]="I like C++";

cout<<"Original String:\n";
cout<<str;
cout<<endl<<endl;

encrypt(str);

cout<<"After Encryption:\n";
cout<<str;
cout<<endl<<endl;;

cout<<"After Decryption:\n";
decrypt(str);
cout<<str;
cout<<endl;
}

void encrypt(char *str)
{
while(*str!='\0')
{
*str+=FACTOR;
str++;
}
}

void decrypt(char *str)
{
while(*str!='\0')
{
*str-=FACTOR;
str++;
}
}

Good-Bye!


Related Articles:


Changing the case (lower, upper) of Strings

In this article, we will be designing two functions to change the case of strings.
One would change a string from lower case to upper case while the other would
do the opposite.


Although we have pre-defined functions for doing this in a header file, but
this article is for those who dare to know how all these operations are done
internally.


Changing the case: How is it done?


The main theory lies in the way C++ treats character constants and strings.
Have a look at the following code:


  #include<iostream.h>

void main(void)
{
char first='A';
char second=65;

cout<<first;
cout<<endl;

cout<<second;
cout<<endl;
}

whose output is:


   A
A
Press any key to continue

This is because ‘A’ and its ASCII code 65 are equivalent to the
compiler and in c++ we can manipulate it in whatever way we like.


Now look at the following code:


  #include<iostream.h>

void main(void)
{
char arr[4]="ABC";
char arr2[4]={65,66,67};

cout<<arr;
cout<<endl;

cout<<arr2;
cout<<endl;
}

Whose output is (yeah you guessed it right!):


   ABC
ABC
Press any key to continue

So this proves that strings can also be expressed (manipulated) by ASCII codes.


ASCII code of some characters:


   A: 65    a: 97
B: 66 b: 98
C: 67 c: 99
… …
… …

From the above, we can conclude that by increasing or decreasing the ASCII
codes of a character by 32, we can change its case. Just as shown in the following
code:


  #include<iostream.h>

void main(void)
{
char chr='A';
char chr2='b';

cout<<chr;
cout<<endl;

chr=chr + 32;
cout<<chr;
cout<<endl<<endl;

cout<<chr2;
cout<<endl;

chr2=chr2 - 32;
cout<<chr2;
cout<<endl;
}

OUTPUT:


   A
a

b
B
Press any key to continue

This theory can also be applied to strings.


Now, that you know the main theory behind we can jump straight to the example
program to illustrate all this:


Keep reading the comments though!


  // C++ example program to show
// how case(uppercase and lowercase)
// of strings can be changed from
// one to the other
#include<iostream.h>

void to_upper(char *);
void to_lower(char *);

void main(void)
{
char str[50]="I Love C++. The number 1 language!";

to_upper(str);
cout<<str;

to_lower(str);
cout<<endl;
cout<<str;

cout<<endl;
}

// takes a character array
// as argument and changes
// it to upper case
// NOTE: special symbols and
// numbers remains the same
void to_upper(char *str)
{
// while end of the string
// has not been reached
while(*str!='\0')
{
// change only if its a
// lower case character
// intelligent enough not to
// temper with special
// symbols and numbers
if(*str>=97 && *str<=122)
*str-=32;

str++;
}
}

// takes a character array
// as argument and changes
// it to lower case
// NOTE: special symbols and
// numbers remains the same
void to_lower(char *str)
{
while(*str!='\0')
{
// change only if its a
// UPPER case character
// intelligent enough not to
// temper with special
// symbols and numbers
if(*str>=65 && *str<=90)
*str+=32;

str++;
}
}

Good-Bye!

Introduction to Linked Lists Part II

In the previous article Introduction
to Linked Lists
, we introduced the basic concept of linked list. To
make the program (an the article) as simple as possible, we discussed only the
addition and display of nodes in the linked list although necessary we didn't’t
discussed the deletion of node in that article.


In this article we will be discussing about the deletion of nodes from linked
lists.


Deletion of node (elements) from a linked list


The node to be deleted can be represented by many ways but here we will be
representing it by its info. So if we have the following linked list


Linked lists - Deletion of nodes




And we want to delete node1 then we will express it by its info part (i.e. 10).


The main theory behind deletion of nodes is pretty simple. We need to make
the link pointer of the node before the target node (to be deleted) to point
at the node after the target node. Suppose if we wish to delete node having
info as 10 from the above linked list then it will be accomplished as below:


Linked list - Deletion of nodes


Now since node1 is orphan and has no meaning, it can be deleted
to free-up memory as represented below:


Linked lists - node deleted to free-up memory


The following example program illustrates all this. Keep reading
the comments to understand what is happening where!


  // -- Linked Lists --
// ------------------
// Example program in C++
// to illustrate the most simple
// linked list
// NOTE: this program can do three
// operation [adding, deleting,
// and displaying] of data in a
// linked list
#include<iostream.h>

// node class, this will
// represent the nodes or elements
// of the linked list
class node
{
public:
int info;
node *link;
};

// declare global objects
node *start=NULL;

// function prototypes
void add(int inf);
void display(void);
void del(int);

void main(void)
{
int ch;

// input elements
while(ch!=0)
{
cout<<"enter element to be added:";
cout<<"\nenter 0 to stop...\n";
cin>>ch;

if(ch!=0) add(ch);
cout<<"\n\n";
}

ch=-1;

while(ch!=0)
{
cout<<"enter element to be deleted:";
cout<<"\nenter 0 to stop...\n";
cin>>ch;

if(ch!=0) del(ch);
cout<<"\n\n";
}

cout<<"elements are...\n";
display();

// below is a bit confusing
// part.
// here all the nodes that
// we have allocated are
// being freed up
node temp;
while(start!=NULL)
{
// store the next node
// to the one being deleted
temp=*start;
// delete the node
delete start;

// retrieve the next node
// to be deleted
start=temp.link;
}
}

void add(int inf)
{
node *temp1;
node *temp2;

// if the element to be added
// is the first element
if(start==NULL)
{
// allocate a new node
temp1=new node;
temp1->info=inf;
temp1->link=NULL;

// make start point at it
start=temp1;
}
// if not
else
{
temp1=start;

// find out the last element
while(temp1->link!=NULL)
temp1=temp1->link;

// allocate new node
temp2=new node;
temp2->info=inf;
temp2->link=NULL;

// make the last element
// of the list to point
// at the newly created node
temp1->link=temp2;
}
}

void display(void)
{
node *temp;
temp=start;

// traverse or process
// through each element
// and keep printing
// the information
while(temp!=NULL)
{
cout<<temp->info<<endl;
temp=temp->link;
}
}

// this function takes an
// argument which is the info
// of the node to be delted
void del(int num)
{
node *old;
node *target;

target=start;

while(target!=NULL)
{
// if node to be
// delted is found
if(target->info==num)
{
// if node to be deleted
// is the first node
// in the list
if(target==start)
start=target->link;

// if not
else
// then make the node
// prev. to the node
// to be deleted to
// point at the node
// which is after it
old->link=target->link;

// free-up the memory
delete(target);
return;
}
else
{
// traverse through
// each node
old=target;
target=target->link;
}
}
}

Related Articles:


Introduction to Linked Lists

We have been using arrays to store similar data linearly. While arrays are
simple to understand and easy to implement in common situations, they do suffer
from some drawbacks which are listed below:




  • Arrays have fixed dimensions, even if we dynamically allocate the dimension
    it remains constant throughout. So there is a limit to the number of elements
    it can store.




  • Operations such as insertion and deletion are pretty much difficult to
    implement and increases the overhead because these operations require elements
    in the array to be physically shifted.




Linked lists overcome these drawbacks and are commonly used to store linear
data.


Actually elements of linked lists (called as nodes) store two information,
data and the link (pointer) pointing to the next elements (node).


The elements (nodes) are linked sequentially with the help of link pointers.
So we can say that linked lists are collection of nodes which have data and
are linked sequentially so that all the nodes or elements are grouped together.


In programming sense, linked lists are classes whose general form is:


  class node
{
public:
data-type info;
node *link;
};

Here info stores the actual data while link stores the memory
address of the next node, which forms the link between the nodes.


Graphical Representation of a Node of a Linked List

FIG.: Graphical representation of a node


Following figure illustrates the growing of linked lists, the node which has
its link as NULL is the last element in the linked list.


Growing of linked list

FIG.: Linked lists grows like this


Let us now discuss a bit about how a linked list grows:




  1. We have a pointer that stores the memory address of the first element
    in the linked list, represented as the start pointer (of type node). It
    is NULL to begin with as we don’t have any element in the list.




  2. As an element is added, the start pointer is made to point at it and since
    for now the first element is the last element therefore its link is made
    to be NULL




  3. After the addition of each element the link pointer of the previously last
    element is made to point at new last element. This step continues…




In this way the number of nodes in a linked list can grow or shrink over time
as far as memory permits.


Below is the example program that illustrates linked lists. This program is
made as simple as possible and therefore it only performs the basic action (addition
of element) in the linked list.


  // -- Linked Lists --
// ------------------
// Example program in C++
// to illustrate the most simple
// linked list
// NOTE: It is designed so that it
// could only add nodes to the
// list and display them.
#include<iostream.h>

// node class, this will
// represent the nodes or elements
// of the linked list
class node
{
public:
int info;
node *link;
};

// declare global objects
node *start=NULL;

// function prototypes
void add(int inf);
void display(void);

void main(void)
{
int ch;

// input elements
while(ch!=0)
{
cout<<"enter element to be added:";
cout<<"\nenter 0 to stop...\n";
cin>>ch;

if(ch!=0) add(ch);
cout<<"\n\n";
}

cout<<"elements are...\n";
display();

// below is a bit confusing
// part.
// here all the nodes that
// we have allocated are
// being freed up
node temp;
while(start!=NULL)
{
// store the next node
// to the one being deleted
temp=*start;

// delete the node
delete start;

// retrieve the next node
// to be deleted
start=temp.link;
}
}

void add(int inf)
{
node *temp1;
node *temp2;

// if the element to be added
// is the first element
if(start==NULL)
{
// allocate a new node
temp1=new node;
temp1->info=inf;
temp1->link=NULL;

// make start point at it
start=temp1;
}
// if not
else
{
temp1=start;

// find out the last element
while(temp1->link!=NULL)
temp1=temp1->link;

// allocate new node
temp2=new node;
temp2->info=inf;
temp2->link=NULL;

// make the last element
// of the list to point
// at the newly created node
temp1->link=temp2;
}
}

void display(void)
{
node *temp;
temp=start;

// traverse or process
// through each element
// and keep printing
// the information
while(temp!=NULL)
{
cout<<temp->info<<endl;
temp=temp->link;
}
}

Good-Bye!


Related Articles:


Data Structures: Introduction to Queues

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 queues, 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. Although representing queues with arrays have its
    shortcomings but due to simplicity, we will be representing queues with
    arrays in this article.




  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.




Let us have look at the process of adding and retrieving data in the queue
with the help of an example.


Suppose we have a queue represented by an array queue [10], which is empty
to start with. The values of front and rear variable upon different actions
are mentioned in {}.


queue [10]=EMPTY {front=-1, rear=0}


add (5)


Now, queue [10] = 5 {front=0, rear=1}


add (10)


Now, queue [10] = 5, 10 {front=0, rear=2}


retrieve () [It returns 5]


Now, queue [10] = 10 {front=1, rear=2}


retrieve () [now it returns 10]


Now, queue [10] is again empty {front=-1, rear=-1}


In this way, a queue like a stack, can grow and shrink over time.


Now have a look at the following example program that illustrates all this
stuff:


  // -- A Queue Class in C++ --
// example program in C++ to
// illustrate queues represented
// by arrays
#include<iostream.h>

// macro to hold the max
// number of elements
// in the queue
#define MAX 10

// queue class
class queue
{
int arr[MAX];
int front, rear;

public:

void add(int);
int retrieve(void);
queue();
};
// queue class ends

// member functions
queue::queue()
{
// initialize index
// variables
front=-1;
rear=0;
}

void queue::add(int data)
{
if(rear==MAX-1)
{
cout<<"QUEUE FULL!";
return;
}

arr[rear]=data;
// increase index
// variable
rear++;

if(front=-1)
front=0;
}

int queue::retrieve()
{
int data;

if(front==-1)
{
cout<<"QUEUE EMPTY!";
return NULL;
}

data=arr[front];
arr[front]=0;

// if both index variables
// point to the same location
// then start afresh
if(front==rear-1)
{
front=-1;
rear=0;
}
else
front++;

return data;
}
// member functions ends

void main(void)
{
queue obj;
int ch;
int num;

while(ch!=3)
{
cout<<"1> ADD";
cout<<"\n2> RETRIVE";
cout<<"\n3> QUIT\n";

cin>>ch;

switch(ch)
{
case 1:
cout<<"enter element:";
cin>>num;

obj.add(num);
break;

case 2:
cout<<"\n\nRetrieved: ";
cout<<obj.retrieve();
cout<<"\n\n";
break;
}
}
}

Good-Bye


Please do check back for updates!


Related Articles:


Insertion and Deletion of elements in a Sorted Array

In the article Insertion
and Deletion of elements in an Array
, we saw how data is inserted and
deleted in an unsorted array. In that case, we needed two information, the element
as well as the position, for insertion while for deletion we needed the position.
In the case of sorted arrays insertion and deletion takes pace in a slightly
different way.


The following example will clarify this:


Suppose we have the following array:


arr[5]={1,2,3,4,5}


And, we need to insert the element 6, so where it should be inserted? We can’t
insert it at any place because then the array might not remain sorted. Therefore,
we let the program to automatically calculate the position suitable for the
new element, so that the array remains sorted even after insertion.


Now, arr[5]={1,2,3,4,6}


Now, suppose we wish to delete the element 6, in this case we don’t use
the position for deletion because we don’t know where the element was
placed by the program, so rather than referencing the position for deletion,
we reference the element itself.


arr[5]={1,2,3,4}




Therefore, we conclude that while insertion we can use the same process that
we used in the case of unsorted array but in spite of us giving the position
the program will itself calculate it. Similarly, while deletion we have to reference
the element and its position will be found out by the program. The rest of the
process remains the same as we did for the insertion and deletion in an unsorted
array.


I don’t think there is any need for further discussion on this topic,
so we straightaway move on to the example program. The program is self-explanatory,
wherever needed I have provided the comments.


  // Example Program to illustrate
// insertion and deletion of
// elements in a sorted array
#include<iostream.h>

// array has been declared as
// global so that other functions
// can also have access to it
int arr[5]={1,2,3,4,5};
// function prototype
void a_insert(int);
void a_delete(int);

void main(void)
{
int ch;
int num;

while(ch!=4)
{
cout<<"1> Insert";
cout<<"\n2> Delete";
cout<<"\n3> Show";
cout<<"\n4> Quit\n";

cin>>ch;

switch(ch)
{
case 1:
cout<<"enter element:";
cin>>num;

a_insert(num);
break;

case 2:
cout<<"enter element.:";
cin>>num;
a_delete(num);
break;

case 3:
cout<<"\nArray:";
for(int i=0;i<5;i++)
if(arr[i]!=0) cout<<arr[i]<<" ";
break;
}
cout<<"\n";
}
}

// insertion function
void a_insert(int num)
{
int pos;
// find the position where
// the element 'num' should
// be inserted
for(pos=0;arr[pos]<=num;pos++);
pos++;

// insert 'num' at the
// appropriate position
for(int i=4; i>=pos;i--)
arr[i]=arr[i-1];
arr[i]=num;
}

// deletion function
// THE ELEMENT 'NUM' SHOULD BE
// IN THE ARRAY
void a_delete(int num)
{
int pos;

// find the position where
// the element 'num' is at
// ---ELEMENT MUST BE IN THE
// ARRAY---
for(pos=0;arr[pos]!=num;pos++);
pos++;

// delete 'num' from the
// appropriate position
for(int i=pos; i<=4;i++)
arr[i-1]=arr[i];
arr[i-1]=0;
}

Good-Bye!


Do check back for updates!


Related Articles:


Data Structures: Introduction to Stacks

In the previous article, we saw how data is inserted and deleted in an array.
In that case we could insert data at any place throughout the array. However,
there are situations when we only need to add and retrieve data form the ends
of the array. Stacks are one of the examples of this.


Stacks are data structures in which data could be added and retrieved only
from one end (also known as the TOP of the stack). Suppose we insert 5, 6, 9
to the stack consecutively then while retrieving the first one to be retrieved
will be 9 then 6 and then 5. That is why stacks are also known as Last-In-First-Out
(or LIFO)
structure.


A few terms regarding stacks:




  • Stack: Stack is a user-defined data structure. It is most
    commonly represented by linked-lists and arrays. In this article, we will
    be representing stacks with arrays.




  • Push: Adding data to the stack is known as pushing.




  • Pop: Retrieving data from the stack is known as popping.




Let us have look at this process with the help of an example. Suppose we have
a stack represented by an array stack [10], which is empty to start with.


push(5)

Now, stack [10] = 5


push(10)

Now, stack [10] = 5, 10


pop() [It returns    10]

Now, stack [10] = 5


pop() [now it returns 5]

Now, stack [10] is again empty


In this way, a stack can grow and shrink over time.


Example Program


The process is quite simple so we straightaway move on to the example program
in c++ that illustrates the implementation of stack.


In the following program, we have defined a class that has all the function
implemented to represent a stack.


  // Example Program in C++
// to illustrate Stacks
#include<iostream.h>

// stack class
class stack
{
int arr[100];
// 'top' will hold the
// index number in the
// array from which all
// the pushing and popping
// will be done
int top;

  public:
stack();
void push(int);
int pop();
};
// stack class definition ends

// member functions
// of the stack class
stack::stack()
{
// initialize the top
// position
top=-1;
}

void stack::push(int num)
{
if(top==3)
{
cout<<"\nStack Full!\n";
return;
}

top++;
arr[top]=num;
}

int stack::pop()
{
if(top==-1)
{
cout<<"\nStack Empty!\n";
return NULL;
}

return arr[top--];
}
// member function definition ends

void main(void)
{
stack s;
int ch;
int num;

while(ch!=3)
{
cout<<"1> Push";
cout<<"\n2> Pop";
cout<<"\n3> Quit\n";

cin>>ch;

switch(ch)
{
case 1:
cout<<"enter element:";
cin>>num;

s.push(num);
break;

case 2:
cout<<"\n\nPopped: ";
cout<<s.pop();
cout<<"\n\n";
break;
}
}
}

Good-Bye!



Related Articles:


Insertion and Deletion of elements in an Array

Suppose you are storing temperature data for a few months and you forgot to
store the temperature of a particular day (say 5th day) then you need to INSERT
that temperature after the 4th element of the array and in the other case if
you accidentally stored duplicate data then you need to DELETE the duplicate
element.


Apart from these simple examples, there are many other uses of insertion and
deletion


The array to which the element is to be inserted or deleted can be of two types
unordered (unsorted) and ordered (sorted). Here we will be discussing about
the insertion and deletion of element in an unordered or unsorted array.


For insertion in these types of arrays, we need to have two information, the
element to be inserted and the position to which it will be inserted. For deletion,
we only need the position.


Suppose we have the following array:


arr[5]={5,7,2,1,3}


And we need to insert the element 6 at the 2nd position, after insertion:


arr[5]={5,6,7,2,1}


Notice how the last element of the array (i.e. 3) has gone out to compensate
for the insertion.


Now, suppose we wish to delete the element at position 3rd, after deletion:


arr[5]={5,6,2,1,0}


We see, all the elements after the 3rd have shifted to their left and the vacant
space is filled with 0.


That’s exactly how insertion and deletion are done!


Algorithm for Insertion of an element in an array


Suppose, the array to be arr[max], pos to be the position
at which the element num has to be inserted. For insertion,
all the elements starting from the position pos are shifted
towards their right to make a vacant space where the element num is
inserted.




  1. FOR I = (max-1) TO pos
    arr[I] = arr[I-1]



  2.  arr[I] = num



Yeah it is that simple!


Algorithm for Deletion of an element in an array


Suppose, the array to be arr[max], pos to be the position
from which the element has to be deleted. For deletion, all the elements to
the right of the element at position pos are shifted to their
left and the last vacant space is filled with 0.




  1. FOR I = pos TO (max-1)
    arr[I-1] = arr[I]



  2. arr[I-1] = 0



Now, to illustrate all this let me show you a simple example program:


  // Example Program to illustrate
// insertion and deletion of
// elements in an array

#include<iostream.h>

// array has been declared as
// global so that other functions
// can also have access to it
int arr[5];

// function prototype
void a_insert(int, int);
void a_delete(int);

void main(void)
{
int ch;
int num,pos;

while(ch!=4)
{
cout<<"1> Insert";
cout<<"\n2> Delete";
cout<<"\n3> Show";
cout<<"\n4> Quit\n";

cin>>ch;

switch(ch)
{
case 1:
cout<<"enter element:";
cin>>num;
cout<<"enter pos.:";
cin>>pos;

a_insert(num,pos);
break;

case 2:
cout<<"enter pos.:";
cin>>pos;
a_delete(pos);
break;

case 3:
cout<<"\nArray:";
for(int i=0;i<5;i++)
cout<<arr[i]<<" ";
break;
}
cout<<"\n";
}
}

// insertion function
void a_insert(int num, int pos)
{
for(int i=4; i>=pos;i--)
arr[i]=arr[i-1];
arr[i]=num;
}

  // deletion function
void a_delete(int pos)
{
for(int i=pos; i<=4;i++)
arr[i-1]=arr[i];
arr[i-1]=0;
}

Good-Bye!



Related Articles:


Algebra of Matrices (2D Arrays) Part II

As you know from the previous article, matrices are 2D arrays. In the previous
article, we saw how two matrices are added and subtracted. In this article,
we will continue our discussion on algebra of two matrices by discussing how
two matrices are multiplied.


Multiplication of two Matrices


Multiplication of two matrices mat1[a x b] and mat2[p x q] is only valid if
b=p. While there are many algorithms by which two matrices can be multiplied,
here I’ll give you the most simple algorithm. Others are used when efficiency
matters.


Algorithm for Multiplication of two Matrices


Suppose,




  • Two 2D arrays to be mat1 [p][p] and mat2 [p][p] having same number of rows
    and columns.




  • A third 2D array, mul [p][p] to store the result.




Here is the algorithm:


  1. FOR I = 0 TO (p-1)


  2. FOR J = 0 TO (p-1)
    mul [I][J] = 0
    FOR K = 0 TO (p-1)
    mul [I][J] += (mat1 [I][K] * mat2 [K][J])


  3. END OF INNER LOOP


  4. END OF OUTER LOOP



Below is a example program which illustrates the multiplication of two matrices
by this algorithm:


  // Example program in C++
// It shows you how to
// multiply two matrices
#include<iostream.h>

void main(void)
{
int i,j,k;
// this constant determines
// the number of rows and columns
const int max=3;

int mat1[max][max];
int mat2[max][max];
int mul[max][max];

cout<<"enter elements for mat1:";
for(i=0;i<=(max-1);i++)
for(j=0;j<=(max-1);j++)
cin>>mat1[i][j];

cout<<"enter elements for mat2:";
for(i=0;i<=(max-1);i++)
for(j=0;j<=(max-1);j++)
cin>>mat2[i][j];

// multiplication of two matrices
// is done here
for(i=0;i<=(max-1);i++)
for(j=0;j<=(max-1);j++)
{
mul[i][j]=0;
for(k=0;k<=(max-1);k++)
mul[i][j]+=mat1[i][k]*mat2[k][j];
}
// till here

// show the contents of the array
// after formatting
for(i=0;i<=(max-1);i++)
{
for(j=0;j<=(max-1);j++)
cout<<mul[i][j]<<" ";
cout<<endl;
}
}

Good-Bye!


Related Articles:


Algebra of Matrices (2D Arrays)

In the programming sense, Matrices are Two Dimensional or 2D arrays. Just as
Matrices have rows and columns, similarly 2D arrays too have rows and columns.


There are many mathematical operations like addition, subtraction, multiplication
etc. which can be performed on matrices, and therefore to 2D arrays also. In
this article, we will be discussing about the addition and subtraction of two
2D arrays (Matrices).


Addition of two Matrices (2D arrays)


For addition of two matrices both the matrices must have the same dimension.
Ex. if matrice one has the dimension p x q then matrice two must have the dimension
p x q.


In the addition process, each of the element of the first matrice is added
to the corresponding element of the second matrice and result is stored in the
third matrice having the same dimension (i.e. p x q). Below is the algorithm
for adding two matrices.


Algorithm for adding two Matrices


Suppose,




  • Two 2D arrays to be mat1 [p][q] and mat2 [p][q] having p rows and q columns
    respectively.




  • A third 2D array, sum [p][q] to store the result.




Here is the algorithm:




  1. FOR I = 0 TO (p-1)



  2. FOR J = 0 TO (q-1)



  3. sum [i][j] = mat1 [i][j] + mat2 [i][j]



  4. END OF INNER LOOP



  5. END OF OUTER LOOP



Subtraction of two Matrices


For subtraction, same rule applies. The process is also the same as for addition;
we just need to use the subtraction operator instead of the addition operator
;-)


Algorithm for subtracting two Matrices




  1. FOR I = 0 TO (p-1)



  2. FOR J = 0 TO (q-1)



  3. sum [i][j] = mat1 [i][j] - mat2 [i][j]



  4. END OF INNER LOOP



  5. END OF OUTER LOOP



Here is the program that illustrates the implementation of both of these algorithms:


  // Example program in C++
// It shows you how to add
// and subtract two matrices
#include<iostream.h>

void main(void)
{
int i,j,ch;
int mat1[3][3];
int mat2[3][3];
int sum[3][3];

cout<<"enter elements for mat1:";
for(i=0;i<=(3-1);i++)
for(j=0;j<=(3-1);j++)
cin>>mat1[i][j];

cout<<"enter elements for mat2:";
for(i=0;i<=(3-1);i++)
for(j=0;j<=(3-1);j++)
cin>>mat2[i][j];

cout<<"what do you want to do\n\n";
cout<<"1>addition\n2>subtraction\n";
cin>>ch;

switch(ch)
{
case 1:
// addition of matrices
// is done here
for(i=0;i<=(3-1);i++)
for(j=0;j<=(3-1);j++)
sum[i][j]=mat1[i][j]+mat2[i][j];
// till here
break;

case 2:
// subtraction of matrices
// is done here
for(i=0;i<=(3-1);i++)
for(j=0;j<=(3-1);j++)
sum[i][j]=mat1[i][j]-mat2[i][j];
// till her
break;
}

// sum is shown
for(i=0;i<=(3-1);i++)
for(j=0;j<=(3-1);j++)
cout<<"\n"<<sum[i][j];

cout<<endl;
}

Good-Bye for now!



Related Articles:


Binary Search: A Method of Searching

Binary Search method is popular for searching a specific item in an ordered
array (sorted). It can perform the search in minimum possible comparisons, but
it needs the array to be sorted in any order.


Practically, it is used when the data is itself sorted initially or needs to
be sorted for other activities also. This is because you don’t want to
first sort the data and then use binary search, in that case use of linear search
would be practical.


Binary Search Algorithm


Suppose,




  • The array to be AR[SIZE] having SIZE number of elements.




  • L is the index number of the lower element. We take it to be 0.




  • U is the index number of the upper (last) element. It will be (SIZE-1).




  • ITEM is the data that needs to be searched.




  • beg, last and mid are variables of type int(eger).




Here is the algorithm:




  1. LET beg = L AND last = U



  2. REPEAT STEPS 3 THROUGH 6 TILL beg<=last



  3. mid = ( (beg+last)/2)



  4. IF AR[mid] = ITEM THEN
    ITEM IS AT POSITION mid
    BREAK THE LOOP



  5. IF AR[mid] < ITEM THEN
    beg = mid+1



  6. IF AR[mid] > ITEM
    last = mid-1



  7. END OF LOOP



  8. IF AR[mid] = ITEM THEN
    SEARCH IS UNSUCCESSFULL



Here is the example program:


  // BINARY SEARCH PROGRAM
// example program in C++

#include<iostream.h>

void main(void)
{
int beg, last, mid, item, i;
int ar[5];

// sorted data needs to be input
cout<<"enter sorted data:\n";
for(i=0; i<5; i++)
cin>>ar[i];

cout<<"enter search term:";
cin>>item;

// as per array
beg=0;
last=5;

// binary searching starts
while(beg<=last)
{
// calculate the middle
// of the array section
mid=((beg+last)/2);

if (ar[mid]==item)
{
cout<<"\n\n";
cout<<item<<" found at index no. "<<mid;
break;
}

if(ar[mid]<item)
beg=mid+1;// should be beg=mid-1 for
// data in descending order

if(ar[mid]>item)
last=mid-1;// should be beg=mid+1 for
// data in descending order
}
// search end

if(!(ar[mid]==item))
cout<<"\nSearch unsuccessfull!";

cout<<endl;
}

Good-Bye guys!


Do check back for updates!


Related Articles:


Sorting an Array using Bubble Sort

In this article we will see how an array can be sorted using Bubble Sort Technique.
Sorting, as you know, is the method of arranging the elements of an array in
an order (ascending or descending).


The basic idea behind bubble sort method of sorting is to keep on comparing
adjoining elements of the array from the first until the last and interchanging
them if they are not in proper order. The whole sequence is repeated several
times when the array becomes sorted.


Bubble Sort Algorithm


Suppose,




  • The array (to be sorted) to be AR[SIZE] having SIZE number of elements.




  • L is the index number of the lower element. We take it to be 0, since the
    whole array has to be sorted.




  • U is the index number of the upper (last) element. It will be (SIZE-1).




Here is the algorithm of sorting the array using bubble sort




  1. FOR I = L TO U



  2. FOR J = L TO (U-1)



  3. IF AR[J] > AR[JA1] THEN
    temp = AR[J]
    AR[J] = AR[J+1]



  4. END OF INNER LOOP



  5. END OF OUTER LOOP



Now that you know the algorithm, lets have a look at a simple c++ program to
sort an array using bubble sort:


  // Example Program in C++
// to sort an array
// using bubble sort

#include<iostream.h>

void main(void)
{
int temp, i, j;
int ar[10];

cout<<"enter elements of array:\n";
for(i=0; i<10; i++)
cin>>ar[i];

// sorting is done here
for(i=0;i<10;i++)
for(j=0; j<(10-1); j++)
if (ar[j]>ar[j+1])
{
temp=ar[j];
ar[j]=ar[j+1];
ar[j+1]=temp;
}
// till here

for(i=0; i<10; i++)
cout<<endl<<ar[i];

cout<<endl;
}

Good-Bye guys!


Do check back for updates!


Related Articles:




A Multi-Purpose String Class in C++

NOTE: Here I present you with a String Class in C++. We have
pre-defined string class (CString in Microsoft Visual C++) which has similar but
more powerful to the one presented here but using something is one thing and learning
how it works is another. Here I show you how string functions actually work. All
the functions are programmed from the scratch without using any other standard
library function. Look at the program (Class) carefully and try to understand
how each of the function is working.

  //-----------------------------
//-----------myClass-----------
//----A String Class in C++----

#include<iostream.h>
#include<stdlib.h>

class myString
{
private:

// these functions are not
// needed outside the class
void allocate(int);
void copy(char *, char *);

public:

   char *string;

// member functions
myString();
myString(char *);
int getLength();
int getLength(char *);
void empty();
bool isEmpty();
void putString(char *);
char *getString();
char *fromLeft(int);
char *fromRight(int);
char *fromMid(int, int);
~myString();
};

//--------------------------------
//------------MEMBER--------------
//---FUNCTION DEFINITION STARTS---
void myString::allocate(int size)
{
empty();

string=new char[size];
if(string==NULL) exit(0);
}

void myString::copy(char *str1, char *str2)
{
int length=getLength(str2);

for(int i=0;i<=length;i++)
str1[i]=str2[i];
}

void myString::empty()
{
if(string!=NULL)
{
delete []string;
string=NULL;
}
}

bool myString::isEmpty()
{
if(string!=NULL)
return false;

return true;
}

int myString::getLength(char *str)
{
int i=0;

while(str[i]!='\0')
i++;

return i;
}

int myString::getLength()
{
if(string!=NULL)
return getLength(string);

return -1;
}

myString::myString(char *str)
{
string=NULL;
int size=getLength(str)+1;

allocate(size);

copy(string,str);
}

myString::myString()
{
string=NULL;
}

void myString::putString(char *str)
{
int size=getLength(str)+1;

allocate(size);

copy(string,str);
}

char *myString::getString()
{
if(string!=NULL)
{
return string;
}
}

myString::~myString()
{
if(string!=NULL)
delete []string;
}

char *myString::fromLeft(int chr)
{
if(string!=NULL)
{
char *temp;
temp=new char[chr+2];

if(temp==NULL) exit(1);

for(int i=0;i<chr;i++)
temp[i]=string[i];

temp[i]='\0';
return temp;
}
}

char *myString::fromRight(int chr)
{
if(string!=NULL)
{
char *temp;
temp=new char[chr+2];
int a=0;

if(temp==NULL) exit(1);

int i=getLength()-1;
int j=(i-chr)+1;

for(j;j<=i;j++)
{
temp[a]=string[j];
a++;
}
temp[a]='\0';
return temp;
}
}

char *myString::fromMid(int a,int b)
{
if(string!=NULL)
{
int size=b+1;
char *temp;
temp=new char[size];
int i=a,j=0,k=(a+b);

for(i;i<k;i++)
{
temp[j]=string[i];
j++;
}
temp[j]='\0';
return temp;
}
}
//-----------MEMBER-------------
//---FUNCTION DEFINITION ENDS---
//------------------------------

void main(void)
{
myString a("Learning C++ Programming");

cout<<a.getString();
cout<<endl;
cout<<a.fromLeft(3);
cout<<endl;
cout<<a.fromRight(3);
cout<<endl;
cout<<a.fromMid(3,3);
cout<<endl<<a.isEmpty();

a.empty();
// will not print anything
cout<<endl<<a.fromLeft(3);
// will print true(0)
cout<<endl<<a.isEmpty();
}


Good-Bye for now!


Check back for updates...

Check out this stream