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:


Why Software Projects Fail?

Today I read a nice set of ideas on "Why Projects Fail" by Andrew Stellman and Jennifer Greene (ppt or pdf). They have analyzed and categorized the reasons for failures of projects. That led me to write this post.

Ways a project can fail
1. Things the boss does
- Top level may not be communicating well with the rest of the members to pass the knowledge that they got on the requirements or they may not have gained required knowledge. Also some of them may be over confidence on what the team can actually achieve, so they make a guess and resulted in huge issues on development phase.

2. Things the software does
- One major problem is receiving unclear incomplete requirements at the start, but has to continue on what is available. This is a huge problem as it would be too late when it's figured out that the the software does not match the expectations of the end user.

3. Things the team should have done
- Development team also should think wisely and accept the project dead lines. Usually a project comes with an abstract set of requirements, then estimates and deadlines are fixed without even analyzing them thoroughly. As the time passes, developers realize the risks and issues. But many of them keep mouth shut till the end as they feel that it's too late. But the best way to handle such a situation would be to discuss that with your team or the top level immediately rather than waiting for the delivery date.

4. Things that could have been caught
- Testing is one of the areas where most of the development companies do not touch, but that makes an huge impact on the quality of the product. Getting one or two guys from the support team and training them for testing by developers is not a good patch for this. The developer is having only his view on what he build, so training by him/her would not lead to uncovering hidden issues. Also neglecting on issues we see before hand is also a problem. If a design issue or a coding error is found, no one should wait till another catch it.

What can be done?
1. Tell the truth, so that the team and top level has a good understanding on status of project.
2. Have reviews as much as possible, as this will lead to moving the project toward the correct path always.
3. Let everyone express their ideas and issues. Some members may have difficulties on understanding requirements or issues on skills, and let them to come up with those. This will lead to a far better team.
4. Treat the team well and make sure all the necessities are fulfilled to continue with the project.
5. Solve issues early as possible by not trying to point fingers later.

What are your experiences and views? We would like if you share those with us.

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:


Adsense rounded borders for ads formats

Google Adsense has come up with a new feature for ad borders, that is "Corner style". This features improves the look and feel making an advantage for site developers.



Now publishers can choose between 'slightly rounded' or 'highly rounded' corner (two sample are shown here). If your site has a rounded template this will help a lot.

To apply this change for existing Adsense ads, you only have to add another line to set another value inside the script. Set the value of "google_ui_features" as follows.

google_ui_features = "rc:6";
google_ui_features = "rc:10";

"rc:6" is for 'slightly rounded' while "rc:10" for 'highly rounded'.

Adding SQLite to Run BASIC

Here is some example code that runs under Run BASIC using SQLite v3.4. I haven't pushed this stuff onto the publicly hosted site. SQLite will come with the Run BASIC personal server and should be suitable for many projects. Support for other databases like Oracle, PostgreSQL, SQL Server, etc. will be added with the professional server license.

sqliteconnect #users, "test.db"
call execAndPrint "select * from users"
call execAndPrint "select count(*) from users"
#users disconnect()
end

sub execAndPrint query$
#users execute(query$)

while #users hasanswer()
result$ = #users nextrow$(",")
print result$
wend
end sub

SQLite is a popular database engine provided as a library and is supported for Windows, Mac and Linux. The source code is available and is in the public domain so it is completely free. We will support the parts of Run BASIC that integrate with SQLite, but as for the specific level of conformance to the SQL standard and other technical details, see http://www.sqlite.org/

The SQLITECONNECT #obj, "databasefile.db" statement connects to a database and sets the #obj variable to be a connection object. The connection object understands EXECUTE(), HASANSWER(), NEXTROW$() and DISCONNECT(). I'm sure there will be more commands.

Notice the NEXTROW$() method. It returns each query result row as a string, with each item delimited by the specified string ("," in the example but it could be CHR$(9) or something else). It is trivial then to use the WORD$() function to extract the information. We will certainly also add the ability to get items by name.

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:




Classes & Objects: Dynamic Memory Allocation

Just as variables of pre-def data type are dynamically allocated, same way
objects of class can also be dynamically allocated. While the method of doing
this is no different but the way members of such objects are accessed is a bit
different. This is why I thought of writing a separate article on it.


Before discussing any further, look at the program below:


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

// class
class myclass
{
// by default everything is
// private to the class
int var1, var2;
void add();

public:
int sum;

void input(int,int);
};

// function definitions
void myclass::input(int a, int b)
{
var1=a;
var2=b;
add();
}

void myclass::add()
{
sum=var1+var2;
}

// main function starts
void main(void)
{
myclass obj; // simple object

myclass *pobj; // pointer
// of type 'myclass'

pobj=&obj; // now 'pobj' pointer
// points to the object 'obj' of
// class 'myclass'

// members are accessed by the '.'
// operator
obj.input(10,20);
cout<<obj.sum;
cout<<endl;

// in case of pointers of class,
// members are accessed by the
// '->' arrow operator
pobj->input(30,40);
cout<<pobj->sum;
cout<<endl;
}

Did you notice the difference?


Members of the object of the class as you know are accessed like this:


object.membername;

While, in case of pointers of the class, the members are accessed like this:


objectptr->membername;

This is the difference I wanted to show you!


As in case of dynamic memory allocation, we have to declare pointer of the
class, therefore members of the dynamically allocated objects will be accessed
by the (->) arrow operator.


Arrays and pointers are closely related. While the members of the pointers
of objects are accessed by the (->) operator, in case of arrays of objects,
we have to use ‘.’ operator instead.


The example program below will clear the confusion, if any:


  // Example Program in C++
#include<stdio.h>
#include<iostream.h>
#include<process.h>

class employee
{
private:
char name[30];
int emp_no,age;
float salary, net_salary, tax;
void calculate();

public:
void input();
void output();
};

//----FUNCTION DEFINITION STARTS----
void employee::input()
{
printf("Enter Name: ");
gets(name);
printf("Enter Employee Number: ");
cin>>emp_no;
printf("Enter Age: ");
cin>>age;
printf("Enter Salary: ");
cin>>salary;
printf("Enter Tax Paid: ");
cin>>tax;
printf("\n\n");

calculate();
}

void employee::output()
{
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Employee Number: %d\n", emp_no);
printf("Net Salary: %f\n", net_salary);
printf("\n\n");
}

void employee::calculate()
{
net_salary=salary-tax;
}
//----FUNCTION DEFINTION ENDS----

// main function starts
void main(void)
{
employee *emp_obj;
int num_emp;

printf("Enter Number of Employees: ");
cin>>num_emp;

emp_obj=new employee[num_emp];
// terminate if memory allocation
// failed
if(emp_obj==NULL) exit(1);

// take input
for(int i=0;i<num_emp;i++)
// object are accessed as arrays
// so '.' operator is used
// we can also write
// (emp_obj+i)->input(); to do the
// same thing
emp_obj[i].input();

printf("\n\n EMPLOYEE DETAILS\n");

// give output
for(i=0;i<num_emp;i++)
emp_obj[i].output();
}

As in the comments, we can either use


   emp_obj[i].input();
or
(emp_obj+i)->input();

to do the same thing, in the first case the object is referenced as an array
while in the other case, it is referenced as pointer. So the appropriate operator
is used in each case.


Hope this article helps!

Features of C++, we haven't discussed...

In this article, we will discuss about certain features of C++ Programming
Language, which we haven’t discussed so far. All the features are discussed
with the help of example programs so that you could straightaway learn to use
them.


Let us have a look at them one-by-one:

(Things are discussed in the comments wherever necessary)


EXAMPLE 1: Variation of for-loop


  // Example Program in C++
#include<stdio.h>
#include<conio.h>

void main(void)
{
char ch;

for(;;)
{
// this loop will run
// infinitely till
// 'q' is pressed
ch=getch();
if (ch=='q' ch=='Q') break;
}

printf("out of loop\n");
}

EXAMPLE 2: Variation of for-loop


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

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

for(int i=0;str[i];i++)
;// notice that there
// is nothing in the
// body of the loop

cout<<"length of str :"<<i;

cout<<endl;
}

OUTPUT:


   length of str :9
Press any key to continue

EXAMPLE 3: Variation of for-loop


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

void main(void)
{
for(int a=0,b=0; a+b<10; a++)
{
// here the number of iteration
// also depends on the value of
// 'b' which is entered by the
// user
cout<<"enter value for b: ";
cin>>b;

cout<<a<<endl;
}
}

EXAMPLE 4: Function having default arguments


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

// function prototype
// it is necessary to define the
// parameter list when default
// argument is used
float power(float num, int pow=2);

void main(void)
{
float number=10;

// here power is called with
// the second argument having
// the default value 2
cout<<power(number);

cout<<endl;

// here the function is called
// as usual with two arguments
cout<<power(number, 4);

cout<<endl;
}

// function definition
// DO NOT write 'int pow=2' here
float power(float num, int pow)
{
float num2=num;

for(int i=1; i<pow; i++)
num=num*num2;

return num;
}

OUTPUT:


   100
10000
Press any key to continue

Good-Bye for now!


Please check back for updates!

Reference Variables in Detail

A reference is an alias or alternate name for an object. It is just like having
two variables having the same memory address, if one of them changes the other
will also change.


Actually, a reference is an implicit pointer. Suppose, we have an int(eger)
variable num and its reference refnum, then
both will always have the same value no matter which one gets alerted.


We can have independent references, reference parameters in functions, functions
returning references etc. that are illustrated below with the help of example
programs:-


EXAMPLE 1: Independent Reference to a variable


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

void main(void)
{
int num;
// notice the declaration of a reference
// & has nothing to do with the 'address
// of' operator (&amp;)
int &refnum=num;

cout<<"enter value for num: ";
cin>>num;
cout<<"now refnum="<<refnum;

cout<<"\nenter value for refnum: ";
cin>>refnum;
cout<<"now num="<<num;
cout<<endl;
}

OUTPUT:


   enter value for num: 10
now refnum=10
enter value for refnum: 20
now num=20
Press any key to continue

EXAMPLE 2: Functions having reference parameters


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

void myfunc(int &);//notice the prototype

void main(void)
{
int a=10;
cout<<a<<endl;
myfunc(a);
// the variable itself has been changed
cout<<a;

cout<<endl;
}

void myfunc(int &var)
{
var=-var;
// no need to return anything
// the reference of the variable
// passed is altered, so that the
// actual variable gets changed
}

OUTPUT:


   10
-10
Press any key to continue

EXAMPLE 3: Returning Reference from a function


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

int &myfunc(int &, int&);//notice the prototype

void main(void)
{
int a=10, b=20;
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;

// beauty of reference
// function used at the left hand side
myfunc(a,b)=30;
// value of 'b' has been assigned to
// 30 since it has greater value of
// the two

cout<<"\n\nnow...\n\n";
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;

cout<<endl;
}

// this function return the reference of the
// variable which is greater of the two
int &myfunc(int &a, int &b)
{
if(a>b) return a;
else return b;
}

OUTPUT:


   a=10
b=20

now...

a=10
b=30

Press any key to continue

Notice the use of function at the left hand side of the (=) operator, it looks
as if we are assigning value to a function!


Confused!


Let me explain this, what is actually happening here is that the function myfunc()
is returning a reference to the variable which is greater of the two passed
as arguments. Since in the example above, the value of variable ‘b’
is greater, therefore its reference is returned from the function, which is
then assigned the value 30, ultimately changing the value of the actual variable
passed.


Good-Bye!

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...

Run BASIC and the iPhone

With Apple's iPhone getting ready to ship at the end of this month I'm very excited that we will have something soon that iPhone owners can use to customize their devices by running their own programs in the iPhone's built-in Safari web browser. Run BASIC (http://www.runbasic.com/) will be one easy way to extend the new device in the same way that many people used to use BASIC to create their own applications and games. This is really just the beginning since you can be sure that there will be so many similar kinds of telephones produced by the major cell phone makers.

I have a Treo 650 myself, and I can use it to access the Run BASIC site, but it is awkward because the web browser it includes is slow and the Treo has a tiny little screen. I am eager to see how this all works on the iPhone, and if it is compelling I may even buy one just so I can demonstrate Run BASIC wherever I am. ;-)

Destructor Functions in Detail

If you don’t know what destructor functions are, read Introduction to Constructor and Destructor functions of a Class. As the example
programs in this article makes use of the dynamic memory allocation of C++,
so please read Introduction to Dynamic Memory Allocation in C++ , in case you missed it.


When does the destructor function gets invoked


The examples below illustrates when the destructor function gets invoked:


Example 1:


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

class myclass
{
public:

~myclass()
{
cout<<"destructed\n";
}
};

void main(void)
{
myclass obj;
cout<<"inside main\n";
}

OUTPUT:


   inside main
destructed
Press any key to continue

As I said in the other article, destructors get invoked when the object of
a class goes out of scope. In this case, the object goes out of scope as the
program terminates. So the destructor gets invoked just before the program’s
termination.


Example 2:


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

void myfunc(void);

  class myclass
{
public:

~myclass()
{
cout<<"destructed\n";
}
};

void main(void)
{
cout<<"inside main\n";
myfunc();
cout<<"again inside main\n";
}

void myfunc(void)
{
cout<<"inside myfunc\n";
myclass obj;
cout<<"still inside myfunc\n";
}

OUTPUT:


   inside main
inside myfunc
still inside myfunc
destructed
again inside main
Press any key to continue

In this case, destructor function is invoked just as the program’s execution
returns from the function, but before executing any further instruction from
where it was called (main).


Example 3: In the following example we are creating a dynamically
allocated object of a class in the same way as we did with the variables.


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

class myclass
{
public:

   ~myclass()
{
cout<<"destructed\n";
}
};

void main(void)
{
myclass *obj;
obj=new myclass;
cout<<"inside main\n";

delete obj;

cout<<"still inside main\n";
}

OUTPUT:


   inside main
destructed
still inside main
Press any key to continue

Here the programmer is explicitly destroying the object, hence the destructor
function is called.


Now that you know some details about the destructor function, let me give you
a practical example of the use of destructor function:


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

class myclass
{
int *number;

public:
myclass(int num)
{
number=new int[num];
}

~myclass()
{
delete []number;
}

void input_num(int index, int num)
{
number[index]=num;
}

int output_num(int index)
{
return number[index];
}
};

void main(void)
{
int size, num;
cout<<"enter number of elments: ";
cin>>size;

myclass obj(size);

for(int i=0;i<size;i++)
{
cout<<"enter element "<<i+1<<":";
cin>>num;
obj.input_num(i,num);
}

cout<<"\nelements have the following values\n\n";

for(i=0;i<size;i++)
{
cout<<"element "<<i+1<<":";
cout<<obj.output_num(i);
cout<<"\n";
}
}

Good-Bye!


Related Articles:


Introduction to Dynamic Memory Allocation in C++

Suppose you are making a C++ program to store a particular number (specified
by the user at runtime) of phone numbers. What will you do? You cannot declare
array of 10 or 20 elements because you don’t know how many numbers the
user will enter. He may want to enter 1, 10 or even 100 phone numbers.


So what will you do?


Actually, you can do two things to achieve this, that are listed below:




  1. You can create a very large int(eger) array (say, of 500 elements) , in
    this case whether the user wants to store 1 or 500 phone numbers, the memory
    used will always be the same (large!).




  2. You can make use of C++’s dynamic memory allocation to allocate only
    the needed amount of memory.




The first choice is a very bad way of programming, nevertheless it works fine,
you should never employ such an inefficient method of programming.


So, you are left with only one choice to use the Dynamic Memory Allocation
of C++ programming language, that I will be discussing in this article.


As is clear from the above example, dynamic memory allocation is needed when
you don’t know the program’s memory needs beforehand.


Allocating Memory


Dynamic memory is allocated by the new keyword. Memory for
one variable is allocated as below:


ptr=new DataType (initializer);

Here,




  • ptr is a valid pointer of type DataType.




  • DataType is any valid c++ data type.




  • Initializer (optional) if given, the newly allocated variable is initialized
    to that value.




Ex.


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

void main(void)
{
int *ptr;
ptr=new int(10);


cout<<*ptr;

delete ptr;
}

This is will allocate memory for an int(eger) having initial value 10, pointed
by the ptr pointer.


Memory space for arrays is allocated as shown below:


ptr=new DataType [x];

Here,




  • ptr and DataType have the same meaning as above.




  • x is the number of elements and C is a constant.




Ex.


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

void main(void)
{
int *ptr, size;

cin>>size;
ptr=new int[size];

//arrays are freed-up like this
delete []ptr;
}

Freeing-Up Allocated Memory


Unlike static variables, c++ will not free-up the memory allocated through
dynamic allocation. Its your duty to free them up. delete keyword
is used to free-up the allocated memory.


delete ptr;

Arrays are deleted in a slightly different manner as shown below:


delete []ptr;

It’s easy to forget to free the allocated memory because C++ compiler
won’t inform you that you are doing this. It’s your job and should
always be done.


Now let me show you an example of dynamic memory allocation in action:


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

void main(void)
{
int *ptr, size;

cout<<"How many PH. Numbers do you wish to enter:";
cin>>size;
ptr=new int[size];//allocate memory

//input ph. numbers
for (int i=0;i<size;i++)
{
cout<<"Enter PH. NO."<<i+1<<" :";
cin>>ptr[i];
}

//output ph. numbers
cout<<"\n\n\n PH. NOs. are\n";
for (i=0;i<size;i++)
cout<<"\nPH. NO."<<i+1<<" :"<<ptr[i];

cout<<endl;

delete []ptr;//free-up memory
}

Good-Bye!


Related Articles:


Introduction to Constructor and Destructor functions of a Class

Constructor and Destructor functions are Member Functions of a class having
some special property.


Constructor function gets invoked when an object of a class is constructed
(declared) and destructor function gets invoked when the object is destructed
(goes out of scope).


Use of Constructor and Destructor function of a class




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




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




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





Defining Constructor and Destructor functions


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


  class myclass
{
private:
int number;

public:
myclass()//constructor
{
number=10;
}

~myclass()//destructor
{
//nothing needed
}
};

A few points to note:




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




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




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




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




  • Constructor function can take arguments but destructors cannot.




  • Constructor function can be overloaded as usual functions.




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


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

class myclass
{
private:
int a;
int b;

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

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

void main(void)
{
myclass a;

cout<<a.add();
}

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


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

class myclass
{
private:
int a;
int b;

public:
myclass(int i, int j)
{
a=i;
b=j;
}

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

void main(void)
{
//notice how the object of the class
//has been declared
//it can be thought as
// myclass a;
// a=myclass(10,20)
myclass a(10,20);

cout<<a.add();
}

Notice that there is no destructor function in both the examples, just because
we don’t need them.


I will discuss destructor functions in detail in the coming articles.


So, keep checking!


Related Articles:


Introduction to Function Overloading in C++

Let us start this with a question!


All of you know that we cannot have two variables of the same name, but can
we have two Functions having the same name.


The answer is YES, we can have two functions of the same name by a method known
as function overloading and the functions having the same name are known as
overloaded functions.


So, what’s the use of Function Overloading


Function overloading is one of the most powerful features of C++ programming
language. It forms the basis of polymorphism (compile-time polymorphism).


Most of the time you’ll be overloading the constructor function of a
class.


How function overloading is achieved


One thing that might be coming to your mind is, how will the compiler know
when to call which function, if there are more than one function of the same
name.


The answer is, you have to declare functions in such a way that they differ
either in terms of the number of parameters or in terms of the type of parameters
they take.


What that means is, nothing special needs to be done, you just need to declare
two or more functions having the same name but either having different number
of parameters or having parameters of different types.


Example 1: Overloading Functions that differ in terms of NUMBER
OF PARAMETERS


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

//FUNTION PROTOTYPES
int func(int i);
int func(int i, int j);

void main(void)
{
cout<<func(10);//func(int i)is called

cout<<func(10,10);//func(int i, int j) is called
}

int func(int i)
{
return i;
}

int func(int i, int j)
{
return i+j;
}

Example 2: Overloading Functions that differ in terms of TYPE
OF PARAMETERS


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

//FUNTION PROTOTYPES
int func(int i);
double func(double i);

void main(void)
{
cout<<func(10);//func(int i)is called

cout<<func(10.201);//func(double i) is called
}

int func(int i)
{
return i;
}

double func(double i)
{
return i;
}

One more Question, is the program below, valid?


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

//FUNTION PROTOTYPES
int func(int i);
double func(int i);

void main(void)
{
cout<<func(10);

cout<<func(10.201);
}

int func(int i)
{
return i;
}

double func(int i)
{
return i;
}

No, because you can’t overload functions if they differ only in terms
of the data type they return.


I Hope this article throws some light on function overloading!


Good-Bye for now


Thanks for reading…


Do check back for updates!


Related Articles:


Unit Conversion Program using Classes

Welcome back guys, I hope you like my previous article, Introduction to Classes
in C++
, in this article we will be further continuing our discussion on classes
in C++. We will not be discussing anything new on the topic though, just a simple
example program to elaborate more on Classes in C++.


In this article, I will show you a program based on classes, which converts
units of length from one to another. The program is simple and I do not think
there is any need for discussing it in detail.


The example program is given below:


  //C++ Program
#include<iostream.h>

class length
{
private:
float in_meter, in_cm, in_inch;

public:
void input(float len,int ch);
float output(int ch);
};

//---function definition starts---
void length::input(float len,int ch)
{
switch(ch)
{
case 1://for meter
in_meter=len;
in_cm=in_meter*100;
in_inch=in_cm*2.54;
break;

case 2://for cm
in_cm=len;
in_meter=in_cm/100;
in_inch=in_cm/2.54;
break;

case 3://for inch
in_inch=len;
in_cm=in_inch*2.54;
in_meter=in_cm/100;
break;
}
}

float length::output(int ch)
{
switch(ch)
{
case 1://for meter
return in_meter;

case 2://for cm
return in_cm;

    case 3://for inch
return in_inch;

default://for other values
return -1;
}
}
//---function definition ends---

void main(void)
{
int choice;
float org_length;

length length_obj;

cout<<"Enter choice of unit:";
cout<<"\n\n 1>Meter";
cout<<"\n\n 2>Centimeter";
cout<<"\n\n 3>Inch\n";
cin>>choice;

cout<<"\nEnter Length:";
cin>>org_length;

length_obj.input(org_length,choice);

cout<<"\nLength in Meters: "<<length_obj.output(1);
cout<<"\nLength in CMs : "<<length_obj.output(2);
cout<<"\nLength in Inches: "<<length_obj.output(3);
cout<<"\n\n";
}

Enough for now, please check back for updates!

Introduction to Classes in C++

Classes are the building blocks of Object Oriented Programming in C++ language.
Class gives us the ability to simplify certain types of programs by creating
objects that forms the basis of Object Oriented programming.


Just like identifiers of built-in data types (ex. int, char etc.) are known
as variables similarly identifiers (instances) of class are known as Objects.


Classes in C++ have two parts, data and functions; these are known as data
members and member function respectively. Member functions are usually the means
of accessing and modifying data members.


Anything inside the class can be either private to the class or public to the
program. Classes may have both type of members (private and public) at the same
time.


General form of Class:


  class class_name
{
access-specifier:
member…
member…
member…

access-specifier:
member…
member…
member…
}object-list;

Few points to remember:




  • Access-specifier can be anyone of the three private, public and protected.




  • Anything after an access-specifier has that type of access until another
    access-specifier is encountered.




  • There can be any number of access-specifier, but in general all the members
    having same access are grouped together under one access-specifier.




  • So,




    class c1
    {
    private;
    int a;
    int b;

    public:
    int c;

    private:
    int d;
    };

    Should be written as


    class c1
    {
    private:
    int a;
    int b;
    int d;

    public:
    int c;
    };


  • Object list is optional which is used to declare objects of the class.


private and public Access-Specifiers


private tells the compiler that the members following it are private to the
class and can not be accessed by other parts of the program.


Ex.




class c1
{
private:
int a;
int b;
void func();
};

Here, the variable a, b and function func() can can only be accessed by the
members of the class c1.


On the other hand, public members are accessible to the other parts of the
program also.




class c1
{
private:
int a;
int b;
void func();

   public:
void func2();
int c;
}obj;

Here the variable c and function func2() are accessible from other parts of
the program, but the private members are only accessible from the public function
func2().


The public members of the class (i.e. func2() and c) can be accessed from other
parts of the program with the help of the following syntax:


obj.c=10;


functions (public) are also accessed like this:


obj.func2();


A few points to remember:




  • Please note that in the previous example a, b and func() can not be accessed
    from other parts of the program with the help of (.) operator.




  • Member functions can simply access any of the private and public members
    of the class without the use of (.) operator.




  • For example, if func2() is a member function class c2 then it can access
    other members (both private and public) as shown below:


    func2()
    {
    a=b;
    b=c;
    func();
    }



Enough talking…

Now let us move on to a simple program to illustrate:




  • How to define a class and its objects in C++.




  • Use of private and public access-specifiers.




  • How to define and use member functions.




  //C++ Program
#include<stdio.h>
#include<iostream.h>

class employee
{
private:
char name[30];
int emp_no,age;
float salary, net_salary, tax;
void calculate()//in line function
//used for the short ones
{
net_salary=salary-tax;
}

public:
void input();
void output();
};

//----FUNCTION DEFINITION STARTS----
void employee::input()
{
printf("Enter Name: ");
gets(name);
printf("Enter Employee Number: ");
cin>>emp_no;
printf("Enter Age: ");
cin>>age;
printf("Enter Salary: ");
cin>>salary;
printf("Enter Tax Paid: ");
cin>>tax;

//the function below can only be invoked
//from the member function like here
//and not from the other parts of the program
calculate();
}

void employee::output()
{
printf("\n\n EMPLOYEE DETAILS\n");
//'\n' is used to print to the next line
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Employee Number: %d\n", emp_no);
printf("Net Salary: %f\n", net_salary);
}
//----FUNCTION DEFINTION ENDS----

void main()
{
employee e1;

e1.input();
e1.output();
}

A few points about the program:




  • Notice how member functions are used to modify data members of the class.




  • Notice the use of private function calculate(), that can only be accessed
    from other member function (i.e. input() and output()).




  • Notice how the member functions are declared and defined.






This article has gone a bit too long but once the discussion on topics like
classes in C++ starts it never seems to end -;)


Good-bye for now!

Support for CSS class tags

In an earlier post I described how Run BASIC can use the DIV and CSS statements to style a web page. That works well for styling the different parts of a web page, but not for styling individual things on a page.

One new addition to Run BASIC is the ability to add a CSS class tag to an object on a web page, so that it can be manipulated.

For example the following would create a link and set a class to "button".

link #doMyBidding, "GO", [go]
#doMyBidding cssclass("button")

And the following statement would add the CSS needed to style the link (or any object that has the class tag "button"):

cssclass ".button", "{ put some css styling in here }"

Here is a link to a video demonstrating how this all works.

http://www.youtube.com/watch?v=1qomg67VdF0

Jar utility can compress files?

Java archive creator is the Jar tool. Is it just a packaging tool or does it compress and package (like zip utilities)? It can compress and package, also by default compression is on. So all the jar files that others have created so far may be compressed (since they did not turn off that).

You can turn off the compression feature by using the 0 (zero) option of the jar command. The command would look like follows.

jar cvf0 TicTacToe.jar *.class

So what's the big deal? It's always better to compress it!!! Many may think so?

No, that's not the truth. There are reasons why you should turn off the compression. For a situation where a jar file is loaded to a browser, uncompressed jar will be suitable over a compressed jar. Uncompressed JAR files can generally be loaded more faster than compressed files because the need to decompression overhead is eliminated. However there's a trade-off, for an uncompressed jar download time over a network may be longer. So decision must be taken by considering both aspects.

Method of Adding Individual Digits of a Number

NOTE: The program discussed in this article has no use in practice but
it would definitely help you understand a few things, so please read on…


What this program does is that it takes a number as input (such as 12345) and
outputs the sum of the individual digits, which in this case is 15 (1+2+3+4+5).


For achieving the required result, we need to do two things, first we should
store each of the individual digits in the number and second, we need to add
those numbers, which will give us the required result.


Let us move on to the first stage where we need to separate the digits.

Here are the steps:-




  • STEP 1: We declare a variable num as integer type and
    an array sep[] again as integer type.


           Suppose num=12345


  • STEP 2: We will be fetching digits from the right (5) to
    left (1). For this, we use the modulus (%) operator which divides two numbers,
    giving us the remainder.

           sep[0]=12345 % 10

    Now,
    num=12345
    sep[0]=5 (last digit has been fetched)


  • STEP 3: Now num is divided by 10 and stored to itself (i.e.
    num).

         num=num/10

    Now,
    num=1234 (integer type cannot hold fractional values,
    which ultimately gets eliminated)
    sep[0]=5


  • STEP 4: Step 2 and Step 3 are repeated until num<10.


  • STEP 5: Now,

           num=1
    sep[0]=5
    sep[1]=4
    sep[2]=3
    sep[3]=2
    Now, we just need to store the value of num to
    sep[4] and -1 is to sep[5]
    (it will mark the end of array)

    We have,
    sep[0]=5
    sep[1]=4
    sep[2]=3
    sep[3]=2
    sep[4]=1
    sep[5]=-1





The easy part, now we just need to add all the elements in the array sep[] until
the end of array is reached (-1).


Here is the program…


  //C++ Program to add the digits of a
//number individually and output the sum
#include<iostream.h>

  void main(void)
{
int i=0,total=0,num;
int sep[10];

cout<<"Enter any number: ";
cin>>num;

while(num>=10)
{
sep[i]=num%10;
num=num/10;
i++;
}

sep[i]=num;
sep[i+1]=-1;
i=0;

while(sep[i]!=-1)
{
total=total+sep[i];
i++;
}

cout<<endl<<"TOTAL: "<<total<<endl;
}

Hope this helps!

Simulating the throw of dice in C++

What makes the throw of dice special is the fact that you can’t always guess which number will come up. This property is known as randomness, which is needed in certain types of programs (ex. Games).

In this article, we are going to discuss how random numbers are generated and used in C++ with the help of a simple example.

The program illustrates generation and use of random numbers in C++:

  //C++ Program to generate RANDOM NUMBERS
//function is isolated so it may be easily
//incorporated in other programs
//NOTE:stdlib.h header file is required
//for using this funtion elsewhere

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

//FUNCTION PROTOTYPE
int random(int HighestNumber,int LowestNumber);

void main(void)
{
char ch = '';
puts("Random Number Generator: ");

while(ch!='q' && ch!='Q')
//loop until q or Q is pressed
{
puts("Press any key to throw dice...");
ch=getch();

//%d tells the compiler that the value after
//the comma is of integer type (value returned
//by the function)
printf("%d",random(6,1));

puts("\nPress Q to QUIT");
}

}

//USER-DEFINED FUNCTION
//it takes two integer arguments and returns a
//random number in between the two.

int random(int HighestNumber,int LowestNumber)
{
//rand() is a standard library function
//which generates random numbers, these are
//operated to get the numbers within range

//stdlib.h header file is necessary for its
//operation
int i=((rand()%(HighestNumber-LowestNumber+1))+LowestNumber);
return i;
}

Hope this article helps!

String Searching Function in C++

Nothing much to say, here I present you with a searching function. It takes
two-character string (array) as the argument and finds the position of the second
string in the first. For example, if the two arrays passed to the function have
the following values:

String 1: ”I like C++”

String 2: “C++”

then the function will return 7, because as an array, string 1 has the word
C++ starting from the index number 7.

If the function cannot find the second string inside first then it will return
the value -1, indicating that the search was unsuccessful.

The program below is easy to understand; therefore, I have left it up to you
to understand how it is working.


   //C++ program which searches for a substring
//in the main string
#include<stdio.h>
int search(char *string, char *substring);

void main(void)
{
char s1[50], s2[30];
int n;

puts("Enter main string: ");
gets(s1);
puts("Enter substring: ");
gets(s2);
n=search(s1,s2);

if(n!=-1)
{
puts("Index Number: ");
printf("%d", n);
}
else
puts("The substring cannot be found...");
}


//FUNTION DEFINITION
//this function takes two arguments
//first is the pointer to the main
//string and second argument is the
//pointer to the substring
//it returns the index number of the
//main string where the substring is found
int search(char *string, char *substring)
{
int i=0,j=0, yes=0, index;

while(string[i]!='\0')
//search until the end of the string
{
if(string[i]==substring[j])
{
index=i;

for (j=1;substring[j];j++)
//match characters until
//the end of substring
{
i++;

if(string[i]==substring[j])
yes=1;
else
{
yes=0;
break;
}
}
if(yes==1) return index;
}
i++;
j=0;
}
return -1;
}

Hope this helps!



Related Articles:


Sorting an array using Selection Sort

Sorting is the process by which the elements of a group (ex. Arrays) are arranged
in a specific order (ascending or descending).

The process of sorting is very important, since it is needed in many types
of programs. Ex. If you need to arrange the heights of various students in a
class, you need to sort their heights.

While there are quite a few methods employed for sorting, we will be discussing
about Selection Sort method in this article.

In selection sort, all the elements of an array are compared with the other
elements following it and interchanged so that smaller elements come at the
top.

So, what that means is that the first element is compared with the second,
third … elements then the next is selected (second element of the array)
and it is compared with the third, fourth … elements and in this way different
elements are selected serially and compared with elements following it.

Interchange is done so that smaller elements come high up in the array. (for
ascending order)

To make this process clear, let us consider this array:


a rr[4]={4,5,3,2}

Steps for sorting this array are outlined below:


  1. The first element of the array is selected and compared with the other elements
    following it and interchanged if required so that the smallest elements comes
    at the top.

    Now,

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

  2. Again the same process is repeated taking the next element (second element
    of the array) as the selected element and comparing it with the elements following
    it (i.e. 4,3).


    Now,

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

  3. Same process is repeated again.


    Now,

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

The array has been sorted.


In the program below, I have programmed the sorting process as a separate function
so that it would be easy for you to incorporate sorting function in your programs.


   //selection sort program in C++
#include<iostream.h>
void sel_sort (int *array,int n);

   void main(void)
{
int arr[10],i;
cout<<"Input 10 Numbers: ";
for (i=0;i<10;i++)
cin>>arr[i];

sel_sort(arr,10);

for (i=0;i<10;i++)
cout<<arr[i]<<" ";
}
//FUNCTION IS DEFINED HERE
//this function takes two arguments
//first argument is the pointer to
//the array that has to be sorted
//and the second is the number of
//elements the array has.

void sel_sort(int *array, int n)
{
int temp,i,j;

for(i=0;i<(n-1);i++)
for(j=i+1;j<(n);j++)
{
if(*(array+i)>*(array+j))
{
temp=*(array+i);
*(array+i)=*(array+j);
*(array+j)=temp;
}
}
}

Here a pointer is used in the parameter of the function. This is because we
cannot return an array from a function therefore we need to the modify (sort,
in this case) the array that is being passed to the function.

That means, we are not modifying any variables, we are just modifying the contents
of the memory address that is being passed as a pointer.

Hope this helps!



Related Articles:


Check out this stream