Wednesday, August 10, 2011

Sorting Techniques in C: Bubble Sort Implementation


Sorting is one of the most common used techniques in business as well any organizations as such. For arranging the database of an employee or student information you would definitely need to use any one of the sorting techniques. 

There many sorting techniques with simple ones being the bubble sort, insertion sort and selection which are used to sort small amount of data, whereas for sorting larger amounts of data you can use Heap, Merge or even Quick sort!

Bubble Sort

This is one of the basic sorting techniques to start of with; all you need to is traverse down the array from the first element to the last one and iterate until the array is completely sorted. 

It is always preferred to have flag which is set on an exchange of two elements in one iteration and if no exchange takes place then the flag is not set as such.

Let us now consider a simple example: 

Let the elements in the array be 3 1 2 4, and you need to sort them in ascending order

First iteration: 1 3 2 4

I and 3 are swapped, since 3 is greater than 1

Second iteration: 1 2 3 4

2 and 3 are swapped, since 3 is greater than 2

Code Snippet:

Let bsort[ ] be an array with n number of elements to be sorted.

// for n number of iteration

for( int i=0 ; i
{
            // to traverse from first element to last element (i.e. n-1 since it is an array)
            for( int j=0 ; j
            {
                        //logic for swapping two numbers
                        if( bsort[ j ] > bsort[ j+1] )
                        {
                                    int temp = bsort[ j+1];
                                   
                                    bsort[ j+1] = bsort [ j ];
                                   
bsort [j] = temp;
                        }
            }
}




Tuesday, February 1, 2011

C Program to Check How Function Calls Are Made Using Stack

A stack is used by programming languages for implementing function calls. Here's a handy C program to check how function calls are made using stack.



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

unsigned int far *ptr ;
void ( *p )( void ) ;

void f1( ) ;
void f2( ) ;

void main( )
{
f1( ) ;
f2( ) ;

printf ( "\nback to main..." ) ;
exit ( 1 ) ;
}

void f1( )
{
ptr = ( unsigned int far * ) MK_FP ( _SS, _SP + 2 ) ;
printf ( "\n%d", *ptr ) ;

p = ( void ( * )( ) ) MK_FP ( _CS, *ptr ) ;
( *p )( ) ;
printf ( "\nI am f1( ) function " ) ;
}

void f2( )
{
printf ( "\nI am f2( ) function" ) ;
}

Sunday, June 6, 2010

C Program to implement a circular queue as a linked list

Here's a simple C Program to implement a circular queue as a linked list





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

/* structure containing a data part and link part */
struct node
{
int data ;
struct node * link ;
} ;

void addcirq ( struct node **, struct node **, int ) ;
int delcirq ( struct node **, struct node ** ) ;
void cirq_display ( struct node * ) ;

void main( )
{
struct node *front, *rear ;

front = rear = NULL ;

addcirq ( &front, &rear, 10 ) ;
addcirq ( &front, &rear, 17 ) ;
addcirq ( &front, &rear, 18 ) ;
addcirq ( &front, &rear, 5 ) ;
addcirq ( &front, &rear, 30 ) ;
addcirq ( &front, &rear, 15 ) ;

clrscr( ) ;

printf ( "Before deletion:\n" ) ;
cirq_display ( front ) ;

delcirq ( &front, &rear ) ;
delcirq ( &front, &rear ) ;
delcirq ( &front, &rear ) ;

printf ( "\n\nAfter deletion:\n" ) ;
cirq_display ( front ) ;
}

/* adds a new element at the end of queue */
void addcirq ( struct node **f, struct node **r, int item )
{
struct node *q ;

/* create new node */
q = malloc ( sizeof ( struct node ) ) ;
q - > data = item ;

/* if the queue is empty */
if ( *f == NULL )
*f = q ;
else
( *r ) - > link = q ;

*r = q ;
( *r ) - > link = *f ;
}

/* removes an element from front of queue */
int delcirq ( struct node **f, struct node **r )
{
struct node *q ;
int item ;

/* if queue is empty */
if ( *f == NULL )
printf ( "queue is empty" ) ;
else
{
if ( *f == *r )
{
item = ( *f ) - > data ;
free ( *f ) ;
*f = NULL ;
*r = NULL ;
}
else
{
/* delete the node */
q = *f ;
item = q - > data ;
*f = ( *f ) - > link ;
( *r ) - > link = *f ;
free ( q ) ;
}
return ( item ) ;
}
return NULL ;
}

/* displays whole of the queue */
void cirq_display ( struct node *f )
{
struct node *q = f, *p = NULL ;

/* traverse the entire linked list */
while ( q != p )
{
printf ( "%d\t", q - > data ) ;

q = q - > link ;
p = f ;
}
}

Monday, April 19, 2010

Which is the Best Place to Find Saving Deals and Discount Coupon Offers?

More often than not, we tend to look for discount deals on various merchandise and goods while shopping online, or looking for services such as car rentals. But, just when you really need something urgently, you don’t seem to get hold of the right deal! Well, if this has happened to you in past, then here are some great deals on Enterprise Coupons.

Monday, February 15, 2010

Sorting a Structure of Multiple Keys

C Program that accepts a set of 5 records for students -

Ask user to enter name, age and height of a student. Sort these records in ascending order of their names. If the names are alike then sort according to their age.

/* Sorting of a structure of multiple keys. */

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

struct stud
{
      char name[25] ;
      int age ;
      float height ;
} ;

void main( )
{
      int i, j, choice ;
      struct stud s[5], temp ;

      float ff ( float ) ;

      clrscr( ) ;

      printf ( "Enter student's name, age and height in cm :-\n") ;
      for ( i = 0 ; i  < = 4 ; i++ )
      {
            fflush ( stdin ) ;
            gets ( s[i].name ) ;
            scanf ( "%d %f", &s[i].age, &s[i].height ) ;
      }

      clrscr( ) ;

      for ( i = 0 ; i  < = 3 ; i++ )
      {
            for ( j = 0 ; j  < = 3 - i ; j++ )
            {
                  if ( strcmp ( s[j].name, s[j + 1].name )  > = 0 )
                  {
                        if ( strcmp ( s[j].name, s[j + 1].name ) == 0 )
                        {
                              if ( s[j].age  >  s[j + 1].age )
                              {
                                    temp = s[j] ;
                                    s[j] = s[j + 1] ;
                                    s[j + 1] = temp ;
                              }
                        }
                        else
                        {
                              temp = s[j] ;
                              s[j] = s[j + 1] ;
                              s[j + 1] = temp ;
                        }
                  }
            }
      }

      printf ( "Records after sorting :-\n") ;
      printf ( "Students Name\t\tAge Height\n" ) ;

      for ( i = 0 ; i  < = 4 ; i++ )
      {
            printf ( "%-20s %2d %.2f\n", s[i].name, s[i].age, s[i].height ) ;
      }

      getch( ) ;
}

float ff ( float f )
{
      float *f1 = &f ;
    return *f1 ;
}

So, how is that for a Tutorial?

Monday, November 30, 2009

Relationships in RDBMS

The relationship in a RDBMS refers to the relation which exists between data of one table and data of another table. There are three kinds of relationships:

1. One to One relationship: In a normalized table, preference should always be given to one-one relationship. This means that a particular column in a table should have a one-to-one relationship with the primary key. In other words, if we know the value of the column we will immediately know the value of the primary key.

2. Many to one or one to many relationship: This refers to the relation between a single primary key and many foreign keys or a single foreign key and many other primary keys. In such relationships, a table is present where each key column of the different tables are included.

3.Many to many relationship - An example of such a relationship is a supplier supplying different parts and a part being supplied by different suppliers. In such cases, a third table is created which will hold the supplier as well as the parts tables’ columns.

What is Normalization: Basics of Relational Databases

Normalization is a design procedure which provides a method for representing data and their relationships precisely in a tabular format that makes database easy to understand and operationally efficient.

Advantages of normalization -

1. Reduced data redundancy - Data redundancy means the repetition of data in a table. This is undesirable since data maintenance becomes a tedious job as more and more records are added to the table.

2.Protection against update and delete anomalies - Update and delete anomalies: The tables which are normalized will contain primary and foreign keys. To maintain data integrity and referential integrity constraints, RDBMS instructs us to insert primary key values into a table at any given point of time but foreign keys can be inserted into any table if and only if the corresponding primary key value is already existing. This helps in maintaining data integrity and referential integrity constraints.

Similarly, with delete anomalies a primary key value will be deleted unconditionally only if any dependencies does not exist for that key.

3.Smaller tables - A table will be split into many smaller tables when it is normalized

Wednesday, September 2, 2009

Any Faithful Followers?

Hi,

It has been quite sometime that i updated this blog, sorry about that!

Coders i am back in action and now i will start the series of XML and PL/SQL Tutorials.

Keep your comments coming and you can also find interesting updates on my new web technology blog and tech blog too

Next post coming in few hours :)

Saturday, April 11, 2009

Handy JavaScript Code Snippet to float a block of code

Here's a handy JavaScript Code Snippet to float a block of code, you can particularly use this piece of code to float your ad-blocks to left or right!

< div style="display:inline; padding:5px; margin:0 0 0 10px;border:1px solid #fff >

/* your business logic goes here */

< /div >

Monday, January 12, 2009

50th Post on the blog, PL/SQL code-snippets will also be a part of the blog

This is the 50th post on this blog, and i wish to convey my thanks to all the frequent visitors and extensive users of this blog.

On this occasion, i would like to mention that hereon i will also be posting some SQL & PL/SQL code snippets on this blog.

Moreover, i will also offer some tips and info for the testers, apart from the coders and developers.

I wish to expand this blog as a more generic one, rather than catering to the needs of barely the hard core programmers!

If you are also a professional programmer, or fresh graduate or even a student, you can contribute. Any handy info provided will be publisher under your name, so kindly contribute generously. It's not about contributing money, as this blog is not a commercial one, but rather an informative one!

Remember that knowledge is meant to be shared, because by sharing it, you increase it, unlike money!

I don't demand any PayPal donations, all i demand from my visitors is their patronage, and handy contributions in form of comments!

Keep visiting and keep sending me your queries and sharing your knowledge!

This is a great destination for everyone, irrespective of whether you are a professional programmer, fresher or just some who fancies reading techie stuff

Happy New Year 2009!

Wishing a very Happy and Warm New Year to everyone!

This year, I will dedicate a lot of time to this blog, and take it one step further.

Till now, there used to be posts about useful code snippets, but hereafter along with that i will also be publishing useful tips for sutdents, fresh graduates as well as professional programmers.

It is all about your dedication, programming can be boring, or it may be real fun, it's left upto you, how you really take it!!

Programming is not all about mugging up syntax!

It is pretty natural that students tend to mug up C/C++ codes & clear the examinations. However,when things come down to real life scenario, it is not possible to by-heart code snippets & survive in the IT industry.

So it is good to realize this fact that programming is not all about mugging up the syntax but rather learning how to deal with the language and how to make use of appropriate Data structures at the right time!

It may take a while for you to get accustomed to real-life programming, however once you get used to it, programming will be real fun, doesn't matter if it is C, C++, Java, PHP, Perl, Shell, Unix, SQL, PL/SQL or any other language.

C-code snippet to reverse a given number

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

int findReverse(int number)
{
int reminder,sum=0;
while(number > 0)
{
reminder=number%10;
sum=sum*10+(reminder);
number=number/10;
}
return sum;
}
void main()
{
int number,reversenumber;
printf("Enter positive integer :");
scanf("%d",&number);
int tempnumber=number;
reversenumber=findReverse(number);
printf("The reverse Number of %d is %d\n",tempnumber,reversenumber);
}

Sunday, November 16, 2008

How to Print a data from a binary tree In ascending order

Code snippet to Print a data from a binary tree – In-order(ascending)


// recursive version


Void PrintTree ( struct * node node )
{
if ( node == NULL )
return;

PrintTree(node - > left );
Printf(“%d”, node - > data);
PrintTree(node - > right );
}

Tips for reducing unexpected buffer errors

When using functions such as strncpy() that take a size input parameter, you should use the size of the destination buffer and not the source buffer for correct functionality!

Following code snippet is an example of incorrect usage -

strncpy(dest, src, sizeof(src));

//If sizeof(src) > sizeof(dest) this would give unexpected results;


Therefore, the correct and safe usage should be,

memset(dest, 0, sizeof(dest)); //Fill the buffer with null characters

strncpy(dest, src, sizeof(dest)-1);

//sizeof(dest)-1 takes care of the space for the terminating null character

Sunday, November 9, 2008

C++ function to return Nth the node from the end of the linked list in one pass.

C++ function to return Nth the node from the end of the linked list in one pass.

Node * GetNthNode ( Node* Head , int NthNode )
{
Node * pNthNode = NULL;
Node * pTempNode = NULL;
int nCurrentElement = 0;

for ( pTempNode = Head; pTempNode != NULL; pTempNode = pTempNode->pNext )
{
nCurrentElement++;
if ( nCurrentElement - NthNode == 0 )
{
pNthNode = Head;
}
else
if ( nCurrentElement - NthNode > 0)
{
pNthNode = pNthNode - > pNext;
}
}
if (pNthNode )
{
return pNthNode;
}
else
return NULL;
}

Wednesday, October 29, 2008

Codd's Rules for Relational Database Management

The following are the 12Codd's rules for Relational Database Management!

If the first 5 are satisfied then the system is considered as a DBMS, and if 6 or more rules are being followed by the system, then it is regarded as an RDBMS!

•The information rule
•The rule of guaranteed access
•The Systematic treatment of all null values
•The database description rule
•Comprehensive data sub language
•The view updating rule
•The insert and update rule
•The physical independence rule
•The logical independence rule
•The integrity independence rule
•The distribution rule
•The Nonsubversion rule

Sunday, October 12, 2008

XML file for creation of a database of cricket players

save this as a .xml file...

< ?xml version="1.0" encoding="ISO-8859-1"? >

< ?xml-stylesheet type="text/xsl" href="cricket.xsl"? >


< Team >
< player >
< name > Sachin Tendulkar < /name >
< age > 35 < /age >
< role > Allrounder < /role >
< country > india < /country >
< runs > 12075 < /runs >
< batavg > 45.26 < /batavg >
< wickets > 234 < /wickets >
< matches > 333 < /matches >
< innings > 300 < /innings >
< highscore > 186 < /highscore >
< bestbowling > 5/29 < /bestbowling >
< /player >

< player >
< name > Shahid Afridi < /name >
< age > 34 < /age >
< role > Batsman < /role >
< country > pakistan < /country >
< runs > 3752 < /runs >
< batavg > 40.26 < /batavg >
< wickets > 154 < /wickets >
< matches > 200 < /matches >
< innings > 173 < /innings >
< highscore > 107 < /highscore >
< bestbowling > 5/34 < /bestbowling >
< /player >

< player >
< name > Jacques Kallis < /name >
< age > 31 < /age >
< role > Allrounder < /role >
< country > South Africa < /country >
< runs > 5752 < /runs >
< batavg > 40.26 < /batavg >
< wickets > 89 < /wickets >
< matches > 186 < /matches >
< innings > 140 < /innings >
< highscore > 167 < /highscore >
< bestbowling > 5/45 < /bestbowling >
< /player >

< player >
< name > Ricky Ponting < /name >
< age > 36 < /age >
< role > Batsman < /role >
< country > australia < /country >
< runs > 9876 < /runs >
< batavg > 45.48 < /batavg >
< wickets > 1 < /wickets >
< matches > 325 < /matches >
< innings > 297 < /innings >
< highscore > 161 < /highscore >
< bestbowling > 1/36 < /bestbowling >
< /player >
< /Team >

XSL stylesheet for database of cricket players

save this as a .xsl file, & it will highligh the indian players in blue, Aussies in yellow & pakistan players in green & add few more colors to various attributes...

< ?xml version="1.0" encoding="ISO-8859-1"? >
< xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >




< xsl:template match="/" >
< html >
< body >
< h2 > List < /h2 >
< table border="1" >
< tr > < th > name < /th >
< th > age < /th >
< th > Matches < /th > < /tr >

< xsl:for-each select="Team/player" >

< xsl:choose > < xsl:when test= "country='india'" >
< tr >
< td style="color:blue" > < xsl:value-of select="name"/ > < /td >
< td style="color:red" > < xsl:value-of select="age"/ > < /td >
< xsl:value-of select="matches"/ > < /td > < /tr >
< /xsl :choose >


< xsl:choose > < xsl:when test= "country='australia'" >
< tr >
< td style="color:yellow" > < xsl:value-of select="name"/ > < /td >
< td style="color:red" > < xsl:value-of select="age"/ > < /td >
< td style="color:orange" > < xsl:value-of select="matches"/ > < /td > < /tr >
< /xsl:choose >


< xsl:choose > < xsl:when test= "country='pakistan'" >
< tr >
< td style="color:green" > < xsl:value-of select="name"/ > < /td >
< td style="color:red" > < xsl:value-of select="age"/ > < /td >
< td style="color:orange" > < xsl:value-of select="matches"/ > < /xsl:when > < /xsl:choose >



< /xsl:for-each >


< /table>
< /body >
< /html >
< /xsl:template >

Tuesday, September 30, 2008

How to Pass a Function Pointer in C++

Sample C++ code snippet...


void PassPtr(int (*ptr2Func)(float, char, char))
{
float result = ptr2Func(12, 'a', 'b'); // call using function pointer

cout << result << endl;
} /* is a pointer to a function which returns an int and takes a float and two char */

void Pass_A_Function_Pointer()
{
cout << endl << "Executing 'Pass_A_Function_Pointer'" << endl;
PassPtr(&DoIt);
} // execute example code - 'DoIt' is a suitable function