Introduction to Inheritance in C++

Inheritance in C++ is one of the major aspects of Object Oriented Programming
(OOP). It is the process by which one object can inherit or acquire the features
of another object.


In C++ class and structure can use inheritance. It means we can make one class
(known as derived class) to acquire or inherit the features of another class
(known as base class).


Base class has general features common to all the derived classes and derived
class (apart from having all the features of the base class) adds specific features.
This enables us to form a hierarchy of classes.


Ex. if we define a class ‘computer’ then it could serve as the
base class for defining other classes such as ‘laptops’, ‘desktops’
etc.. This is because as you know that laptops have all the features of computers
and so have desktops (and so should their classes) but they have their specific
features too. So, rather than defining all the features of such classes from
scratch, we make them inherit general features from other classes.


General Form of Inheritance:



class
derived-class:access-specifier base-class
{
...
...
...
};


Here access-specifier can be any one of the three private, public and protected.
These will not be discussed here.


For this article we’ll be using public for all the classes we define.
This means, all the public members of the base class will be public to the derived
class too.


Now let’s take the example of ‘computer’ class a bit further
by actually defining it.



class computer
{
int speed;
int main_memory;
int harddisk_memory;

public:
void set_speed(int);
void set_mmemory(int);
void set_hmemory(int);
int get_speed();
int get_mmemory();
int get_hmemory();
};



As you can see, the features (properties and functions) defined in the class
computer is common to laptops, desktops etc. so we make their classes inherit
the base class ‘computer’.



class laptop:public computer
{
int battery_time;
float weight;

public:
void set_battime(int);
void set_weight(float);
int get_battime();
float get_weight();
};



This way the class laptop has all the features of the base class ‘computer’
and at the same time has its specific features (battery_time, weight) which
are specific to the ‘laptop’ class.


If we didn’t use inheritance we would have to define the laptop class
something like this:



class laptop
{
int speed;
int main_memory;
int harddisk_memory;

int battery_time;
float weight;

public:
void set_speed(int);
void set_mmemory(int);
void set_hmemory(int);
int get_speed();
int get_mmemory();
int get_hmemory();

void set_battime(int);
void set_weight(float);
int get_battime();
float get_weight();
};



And then again we would have to do the same thing for desktops and any other
class that would need to inherit from the base class ‘computer’.


Thanks to inheritance, we don’t need to do all this!


I think now you’ve got the essence of what inheritance is, so taking
the example of the ‘computer’ class a bit more further, we implement
it into an example program listed below:



// Introduction to Inheritance in C++
// ------------------------
// An example program to
// demonstrate inheritance in C++
#include<iostream.h>

// base class for inheritance
class computer
{
float speed;
int main_memory;
int harddisk_memory;

public:
void set_speed(float);
void set_mmemory(int);
void set_hmemory(int);
float get_speed();
int get_mmemory();
int get_hmemory();
};

// -- MEMBER FUNCTIONS --
void computer::set_speed(float sp)
{
speed=sp;
}

void computer::set_mmemory(int m)
{
main_memory=m;
}

void computer::set_hmemory(int h)
{
harddisk_memory=h;
}

int computer::get_hmemory()
{
return harddisk_memory;
}

int computer::get_mmemory()
{
return main_memory;
}

float computer::get_speed()
{
return speed;
}
// -- ENDS --

// inherited class
class laptop:public computer
{
int battery_time;
float weight;

public:
void set_battime(int);
void set_weight(float);
int get_battime();
float get_weight();
};

// -- MEMBER FUNCTIONS --
void laptop::set_battime(int b)
{
battery_time=b;
}

void laptop::set_weight(float w)
{
weight=w;
}

int laptop::get_battime()
{
return battery_time;
}

float laptop::get_weight()
{
return weight;
}
// -- ENDS --

void main(void)
{
computer c;
laptop l;

c.set_mmemory(512);
c.set_hmemory(1024);
c.set_speed(3.60);

// set common features
l.set_mmemory(256);
l.set_hmemory(512);
l.set_speed(1.8);

// set specific features
l.set_battime(7);
l.set_weight(2.6);

// show details of base class object
cout<<"Info. of computer class\n\n";
cout<<"Speed:"<<c.get_speed()<<"\n";
cout<<"Main Memory:"<<c.get_mmemory()<<"\n";
cout<<"Hard Disk Memory:"<<c.get_hmemory()<<"\n";

//show details of derived class object
cout<<"\n\nInfo. of laptop class\n\n";
cout<<"Speed:"<<l.get_speed()<<"\n";
cout<<"Main Memory:"<<l.get_mmemory()<<"\n";
cout<<"Hard Disk Memory:"<<l.get_hmemory()<<"\n";
cout<<"Weight:"<<l.get_weight()<<"\n";
cout<<"Battery Time:"<<l.get_battime()<<"\n";
}

New Firefox release 2.0.0.6 - Security update

A new version of Firefox, 2.0.0.6 has been released today. This is another security update. And they released the 2.0.0.5 version just 13 days ago. That's why I really love Firefox. When ever an issue is reported, they work on it and provide us with a new version so that we are on the safe side always. And this is not the case with some other browsers where people have to wait months and years for some fixes. So thanks guys for all your dedication on making a better product.

Read the release note for more info.

How String Functions Work? Part II

This is the second part of the article How
String Functions (strinh.h) Work?


Here we'll be designing our own version of some other commonly used standard
library string manipulation function that we discussed in the article String
Manipulation Functions (string.h) II.


These will help increase your programming skills further.


mystrlwr():



// mystrlwr function
#include<iostream.h>

// -- FUNCTION PROTOTYPES --
char *mystrlwr(char *);
// -- ENDS --

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

cout<<mystrlwr(ch);
}

char *mystrlwr(char *str)
{
char *temp;
temp=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++;
}
return temp;;
}


mystrupr():



// mystrupr function
#include<iostream.h>

// -- FUNCTION PROTOTYPES --
char *mystrupr(char *);
// -- ENDS --

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

cout<<mystrupr(ch);
}

char *mystrupr(char *str)
{
char *temp;
temp=str;

while(*str!='\0')
{
// change only if its a
// UPPER case character
// intelligent enough not to
// temper with special
// symbols and numbers
if(*str>=97 && *str<=122)
*str-=32;

str++;
}
return temp;
}

mystrncat():



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

void mystrncat(char *,const char *,int);

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

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

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

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

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

mystrncpy():



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

void mystrncpy(char *,const char *,int);

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

mystrncpy(ch2,ch,6);

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

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

// copy 'n' characters
// from str2 to str1
while(i<n)
{
str1[i]=str2[i];
i++;
}
// put the end of
// string identifier
str1[i]='\0';
}

mystrrev():



// mysrtrev function

#include<iostream.h>

char *mystrrev(char *);

void main(void)
{
char ch[]="Programming";
cout<<mystrrev(ch);

cout<<ch;
}

char *mystrrev(char *str)
{
char temp;
int len=0;
int i,j;

// find the length
while(str[len]!='\0')
len++;

j=len-1;

for(i=0;i<len/2;i++)
{
// interchange the
// characters from
// the beginning to
// the end
temp=str[j];
str[j]=str[i];
str[i]=temp;
j--;
}

return str;
}

Related Articles:


What is Polymorphism?

Polymorphism means to have one interface for different methods or functions.
It is the ability through which we can do different operations (by calling different
functions) from the same interface.


In C++ functions and operators can be made to be polymorphic, but in this article
we’ll only be discussing about polymorphic functions.


There can be two types of polymorphism which are discussed below:


Compile-Time Polymorphism: When we have two or more polymorphic function (overloaded
functions) and the call to a particular function is resolved (or known) at the
compile-time, it is called compile-time polymorphism.


The following example program illustrates this. Please read the comments for
further information.


   // program to demonstrate
// compile-time polymorphism
#include<iostream.h>

// -- FUNCTION PROTOTYPES --
// -- OVERLOADED FUNCTIONS --
void func(int);
void func(char *);
// -- ENDS --


void main()
{
// by seeing the argument

// passed, anyone can tell
// which version of the
// function is being called
// hence call to particular
// polymorphic functions is
// resolved or known at the
// time of compilation
func(10);
func("Polymorphism");
}

void func(int a)
{
cout<<a;
cout<<endl;
}

void func(char *str)
{
cout<<str;
cout<<endl;
}


Run-Time Polymorphism: When the call to a particular function (out of the many
polymorphic functions) is not resolved (or known) until execution then it is
called run-time polymorphism.


The following example program illustrates this. Pay extra attention to the
comments!



// Program to demonstrate
// run-time polymorphism
#include<iostream.h>

// -- FUNCTION PROTOTYPES --
void func1();
void func2();
// -- ENDS --

void main()
{
int ch=0;
// here pointer to function
// is declared which will
// be used to call one of
// the two functions
void (*ptr)();

while(ch!=3)
{
cout<<"1> Call Func1";
cout<<"\n2> Call Func2";
cout<<"\n3> Quit\n";

cin>>ch;

switch(ch)
{
case 1:
// make 'ptr' point
// to func1
ptr=func1;
break;

case 2:
// make 'ptr' point
// to func2
ptr=func2;
break;
}

// call whichever
// function is selected
// PLEASE NOTE THAT IT IS
// NOT POSSIBLE TO TELL
// WHICH OF THE TWO
// FUNCTION WILL BE
// CALLED. HENCE CALL
// TO A PARTICULAR
// PLOYMORPHIC FUNCTION
// REMAINS UNRESOLVED
(*ptr)();
}
}

// -- FUNCTIONS DEFINITION --
void func1()
{
cout<<"Called Func1!\n";
}

void func2()
{
cout<<"Called Func2!\n";
}
// -- ENDS --



Good-Bye!


Related Articles:


Array of Functions

In the article
Pointers to Function
, we saw how pointers can be made to point
at functions and hence can be used to invoke them.


By far the most important use of pointers to functions is to have arrays of
functions. This can be achieved as stated below


You already know that we can have arrays of pointers and pointers can be made
to point at functions. So combining both we can have array of pointers to functions
put differently, we can have array of functions.


The example program below demonstrates how we can have array of functions;
please note that this concept is mostly used in writing compilers and interpreters,
so you shouldn’t expect the program to do anything serious or useful!


  // Program to demonstrate
// array of functions
#include<iostream.h>

// -- FUNCTION PROTOTYPES --
void func1();
void func2();
void func3();
void func4();
void func5();
// -- ENDS --

void main()
{
// notice the prototype
void (*ptr[5])();

// arrays are made to point
// at the respective functions
ptr[0]=func1;
ptr[1]=func2;
ptr[2]=func3;
ptr[3]=func4;
ptr[4]=func5;

// now the array elements
// point to different functions
// which are called just like
// we access the elements of
// an array
for(int i=0;i<5;i++)
(*ptr[i])();
}

// -- FUNCTIONS DEFINITION --
void func1()
{
cout<<"Called Func1!\n";
}

void func2()
{
cout<<"Called Func2!\n";
}

void func3()
{
cout<<"Called Func3!\n";
}

void func4()
{
cout<<"Called Func4!\n";
}

void func5()
{
cout<<"Called Func5!\n";
}
// -- ENDS --

Good-Bye!


Related Articles:


String Manipulation Functions (string.h) II

This is the continuation of the article String
Manipulation Functions (string.h)
in which we’re discussing about
the string manipulation functions.


Here I have listed 8 functions along with their prototype (simplified) and
a short description.


One thing to note here is that unlike the last article on this topic, I have
not included example programs, since the functions (with their prototypes) are
pretty much straightforward.



strlwr:


Prototype: char *strlwr(char *)

This function converts the given string to lowercase and returns the same.


strupr:


Prototype: char *strupr(char *)

This function converts the given string to UPPERCASE and returns it.


strncat:


Prototype: strncat(char *str1, const char *str2, int n)

It appends first ‘n’ characters of str2 to the end of str1.


strncpy:


Prototype: int strncmp(char *str1, const char *str2, int n)

This function compares first ‘n’ characters of str1 with str2,
it returns 0 if compare was successful.


stricmp:


Prototype: int stricmp(const char *str1, const char *str2)

It compares two strings str1 and str2 without regard to case and returns
0 on being successful.


strnicmp:


Prototype: int strnicmp(const char *str1, const char *str2, int n)

This function compares first ‘n’ characters of str1 with str2
without regard to case.


strrev:


Prototype: char *strrev(char *)

This function reverses the given string and returns it.


stcstr:


Prototype: char *strstr(const char *str1, const char *str2)

This function returns the pointer to where the first occurrence of string
str2 is found inside str1.


Good-Bye!


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:


String Manipulation Functions (string.h)

This article discusses about the classic string manipulation functions defined
in the string.h header file.


From quite a while peoples have been asking me to write an article on the standard
library string manipulation functions. These functions are defined in the string.h
header file, so you must include it to use them.


There are dozens of string functions in the string.h header
file and thus it is difficult to list them all. So rather than listing them
all I would be discussing in detail about only few commonly used string manipulation
functions along with an example program illustrating how each function is used.


strlen:


  Prototype: int strlen(const char *string);

This function takes the base address of the string as the argument and returns
the number of characters in it (including spaces).


  // strlen() string manipulation
// function
#include<iostream.h>
#include<string.h>

void main(void)
{
char ch[]="String Manipulation";

cout<<strlen(ch);
}

OUTPUT:

   19

strcpy:


  Prototype: strcpy(char *target, const char *source);

This function takes two arguments (base address of two strings) and copies
the contents of the source string to the target string.


It doesn't check bounds thus its our responsibility to be sure that target
string is enough to store the contents of the source string.


  // strcpy - string manipulation
// function
#include<iostream.h>
#include<string.h>

void main(void)
{
char source[]="C++";
char target[10];

strcpy(target,source);

cout<<source;
cout<<endl;
cout<<target;
}

OUTPUT:

   C++
C++

strcat:


  Prototype: strcat(char *target, const char *source);

It concatenates or appends the source string at the end of the target string.


Target string is itself concentrated so it must be big enough to hold the concatenated
characters.


  // strcat - string manipulation
// function
#include<iostream.h>
#include<string.h>

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

strcat(target,source);

cout<<source;
cout<<endl;
cout<<target;
}

OUTPUT:

   C++
I like C++

strcmp:


  Prototype: int strcmp(const char *string1, const char *string2);

This function compares two strings and returns 0 if they are identical or else
returns a non-zero value.


Case (lower or upper) does matters, thus c++ and C++ are not the same according
to this function.


  // strcmp - string manipulation
// function
#include<iostream.h>
#include<string.h>

void main(void)
{
cout<<strcmp("c++","C++");
cout<<endl;

cout<<strcmp("Jerry","Jerry");
}

OUTPUT:

   1
0

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:


Increase your Programming Skills III

Here I have listed some questions related to strings in c++, solve them to
increase your programming skills.


Problem #1:


  // Problem related to strings

#include<iostream.h>

void main(void)
{
char ch[]="Programming Skills";
int i=0;

cout<<ch[++i];
cout<<ch[i++];
cout<<i++[ch];
cout<<++i[ch];
}

Problem #2:


  // Problems related to strings

#include<iostream.h>

void main(void)
{
char ch[]="Programming Skills";
char *s="Programming Skills";

cout<<sizeof(ch)<<sizeof(s);
cout<<sizeof(*ch)<<sizeof(*s);
}

Problem #3:


  // Problems related to strings

#include<iostream.h>

void main(void)
{
int n[]={4,3,2,1,0};

for(int i=0;i<5;i++)
cout<<n[n[i]];
}

Problem #4:


  // Problems related to strings

  #include<iostream.h>

void main(void)
{
int n[]={11,10,9,8,7,6,5,4,3,2,1,0};
char ch[]="C++ Language";

for(int i=0;i<12;i++)
cout<<ch[n[i]];
}

ANSWERS:


#1: rroh


#2: 19411


#3: 01234


#4: egaugnaL ++C


Good-Bye!


Related Articles:


Increase your Programming Skills II

This is the continuation of the last article… Increase
your Programming Skills


Solve the problems listed here to gain programming skills.


Problem #5:


  // Problem or Question in C++
// --------------------------
// Problem related to pointers
// for increasing programming
// skills

#include<iostream.h>

void main()
{
char ch1[]="Programming";
char ch2[]="Skills";

char *s1=ch1;
char *s2=ch2;

while(*s1++=*s2++);
cout<<ch1;
}

Problem #6:


  // Problem or Question in C++
// --------------------------
// Problem related to pointers
// for increasing programming
// skills

#include<iostream.h>

void main()
{
int i, *j;

i=1;
j=&i;

cout<<i**j*i+*j;
}

Problem #7:


  // Problem related to pointers

#include<iostream.h>

void main()
{
int ar[]={1,2,3,4,5};
char *p;

p=(char *)ar;

cout<<*((int *)p+3);
}

Problem #8:


  // Problem related to pointers

#include<iostream.h>

void change(int *,int);

void main()
{
int ar[]={1,2,3,4,5};

change(ar,5);

for(int i=0;i<5;i++)
cout<<*(ar+i);
}

void change(int *p,int n)
{
for(int i=0;i<n;i++)
*(p+i)=*(p+i)+3;
}

ANSWERS:


#5: Skills


#6: 2


#7: 4


#8: 45678


Good-Bye!


Related Articles:


Increase your Programming Skills I

Here I have listed some selected problems or questions related to pointers
in C++. Solve them to increase your programming skills.


Problem #1:


  // Problem or Question in C++
// --------------------------
// Problem related to pointers
// for increasing programming
// skills

#include<iostream.h>

void main()
{
char ch[]="I_Like_C++";
cout<<*&*&ch;
}

Problem #2:


  // Problem or Question in C++
// --------------------------
// Problem related to pointers
// for increasing programming
// skills

#include<iostream.h>

void main()
{
int i,*p,**q,***r;

i=10;
p=&i;
q=&p;
r=&q;

cout<<i<<*p<<**q<<***r;
}

Problem #3:


  // problem related to pointers

#include<iostream.h>

void main()
{
char ch[]="Programming Skills";
char *s=ch;
cout<<s+++3;
}

Problem #4:


  // Problem related to pointers

#include<iostream.h>

void main()
{
int ar[2][2][2]={1,2,3,4,5,6,7,8};
cout<<***ar;
cout<<ar[1][1][1];
}

ANSWERS:


#1: I_Like_C++


#2: 10101010


#3: gramming Skills


#4: 18


Since this article has become a bit too long, I have broken it into one more
part.

Read Increase
your Programming Skills II



Hope this helps!


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:


Scrollable table with GWT

We came across a requirement to build a scrollable data table using Google Web Toolkit (GWT) because we had a limited space, but a growing table depending on the search criteria. As anyone can guess, having a scrollable table would be the best option. For that we used two components rather than one; com.google.gwt.user.client.ui.ScrollPanel and com.google.gwt.user.client.ui.FlexTable. The data table was added inside the Scrollable Panel.

For clarification, we have added the code below.
ScrollPanel scrollPanel = new ScrollPanel();
FlexTable dataTable = new FlexTable();

dataTable.setWidth("100%");
scrollPanel.add(dataTable);
scrollPanel.setSize("300", "200");

//add data to table
....

For setting width and height; it's advised to use css rules, but for ease of understanding we have shown some hard coded values here.

Macros with Arguments

Have a look at the following code:


  #include<iostream.h>

#define MAX 10

void main(void)
{
for(int i=1;i<=MAX;i++)
cout<<i<<endl;
}

Above we have used the type of macro expansion that we learnt in the article

Introduction to C++ Preprocessor Directives


Do you know that just like functions we can have arguments in the macros too!
The following code shows how:


  #include<iostream.h>

// this is how macros with
// arguments are defined
// NOTE: THERE SHOULD NOT BE
// ANY SPACE BETWEEN THE
// MACRO TEMPLATE (i.e. AREA)
// AND THE PARANTHESIS
// CONTAINING THE ARGUMENTS
// (i.e. (x))

#define AREA(x) (x*x)

void main(void)
{
// calling a macro
// is almost similar
// to calling a function
cout<<AREA(10);
}

It is that simple! However, keep one thing in mind as stated in the comments
not to put any space between the macro template and the braces containing the
argument.


   #define AREA(x) (x*x) //correct
#define AREA (x) (x*x) // incorrect

Why use Macros


While function can do the same thing, still there are times when macros preferred
over function.


As a general rule, using macros increases the execution speed of a program
but at the same time increase the file size of the program. On the other hand
using functions decreases the speed of execution of program but also decreases
the file size.


Therefore, macros are used in time critical programs where execution speed
must be as fast as possible no matter what the file size is, in all other cases
functions are generally used.


Good-Bye!


Related Articles:


Introduction
to C++ Preprocessor Directives

Hurray! My 50th Post

I am so glad to inform you all that this is my 50th post
on this blog. In the span of 57 days this blog has grown in terms of both content
and readership.


I won’t take much of your time saying it out loud
but I would like to thank all of my readers and subscribers for their valuable
response and co-operation!


Thanking You

Arvind Gupta

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!

Merging Two-Dimensional Arrays (Matrices)

In the article Merging
One Dimensional Arrays
, we discussed how to merge one-dimensional
arrays, in this article we will be discussing about the merging of two-dimensional
arrays. Merging as you know is the process of combining two similar things.
In the context of arrays, it means to form a big array from two smaller arrays
which has all the elements from both the arrays.


In case of one-dimensional arrays there is only one way in which two arrays
can be merged but in case of two-dimensional arrays there are two ways.


Suppose, we have the following two 2d arrays (matrices):


mat1={
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}

and

mat2={
{10, 11, 12},
{13, 14, 15},
{16, 17, 18}
}

then they can be merged in the following two ways:

merge_row={
{1, 2, 3, 10, 11, 12},
{4, 5, 6, 13, 14, 15},
{7, 8, 9, 16, 17, 18}
}

merge_col={
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12},
{13, 14, 15},
{16, 17, 18}
}

Now that you know the funda, we move on to the example program to illustrate
this:


  // example program to illustrate
// merging of two-dimensional or
// 2d arrays(matrices)
#include<iostream.h>

#define ROW1 3
#define ROW2 3
#define COL1 3
#define COL2 3

void main(void)
{
int i,j;
int matrix1[ROW1][COL1];
int matrix2[ROW2][COL2];

// these will store merged
// matrices
int merge_row[ROW1][COL1+COL2];
int merge_col[ROW1+ROW2][COL1];

// input the elements
cout<<"Input elements for MATRIX 1:\n";
for(i=0;i<ROW1;i++)
{
cout<<"ROW "<<i+1<<":\n";
for(j=0;j<COL1;j++)
cin>>matrix1[i][j];
}

cout<<"\nInput elements for MATRIX 2:\n";
for(i=0;i<ROW2;i++)
{
cout<<"ROW "<<i+1<<":";
for(j=0;j<COL2;j++)
cin>>matrix2[i][j];
}
//input complete

// merge matrices
// row merge starts
for(i=0;i<ROW1;i++)
for(j=0;j<COL1;j++)
merge_row[i][j]=matrix1[i][j];

for(i=0;i<ROW2;i++)
for(j=0;j<COL2;j++)
merge_row[i][j+COL2]=matrix2[i][j];
// row merge complete

// column merge starts
for(i=0;i<ROW1;i++)
for(j=0;j<COL1;j++)
merge_col[i][j]=matrix1[i][j];

for(i=0;i<ROW2;i++)
for(j=0;j<COL2;j++)
merge_col[i+ROW1][j]=matrix2[i][j];
// column merge complete

// show the merged martices
cout<<"\nROW Merge:\n\n";
for(i=0;i<ROW1;i++)
{
for(j=0;j<COL1+COL2;j++)
cout<<" "<<merge_row[i][j];

cout<<endl;
}

cout<<"\nCOLUMN Merge:\n\n";
for(i=0;i<ROW1+ROW2;i++)
{
for(j=0;j<COL1;j++)
cout<<" "<<merge_col[i][j];

cout<<endl;
}
}

Good-Bye!


Related Articles:


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:


Check out this stream