facebook like button

12 December, 2011

Reversing order of words in a sentence using stack

The need:
     This is another way ( a layman's approach) to write previous program about this topic. I have written the approach there too.
The code:
----------------------------------------------------------
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

struct linked_list
{
    char *chr;
    struct linked_list *next;
};
typedef struct linked_list node;
void push(node **p,char *x);
char *pop(node **p);

int main()
{
    char a[50],*temp,*dup;
    strcpy(a,"I dont know why useless programs are asked");
    node * head=NULL;
    temp=strtok(a," ");
    while(temp != NULL)
    {
        dup=strdup(temp);
        temp=strtok(NULL," ");
        push(&head,dup);
    }
    strcpy(a,"");
    while((temp=pop(&head))!=NULL)
    {
        strcat(a,temp);
        strcat(a," ");
    }
    a[strlen(a)-1]='\0';
    printf("%s\n",a);
    return 0;
}

void push(node **p,char *x)
{
    node *new_node;
    new_node=(node *)malloc(sizeof(node));
    new_node->chr=x;
    new_node->next=*p;
    *p=new_node;
}

char *pop(node **p)
{
    char *temp=NULL;
    node *tmp;
    if(*p==NULL)
        return (NULL);
    else
    {
        temp=(*p)->chr;
        tmp=*p;
        (*p)=(*p)->next;
        free(tmp);
        return (temp);
    }
}
----------------------------------------------------------
Approach:
    In that case I have made use of my stack concepts and using almost no brain I have got it done. Have a look how simple is this. Steps are:
1. read word by word (strtok has been used to read words delimiter is space)
2. keep on pushing all words on a stack till last word.
3. Now pop each word and print. :-)
Remarks:
1. This is not the most efficient method to do this. For more efficient method have a look at previous program about this topic.
2. This program can also be used to reverse the order of words in a file. In that case steps are:
  1. read word by word (using fscanf(FilePointer,"%s",&TempString)).
  2. keep on pushing all words on a stack till last word.
  3. Now pop each word and print to another file. :-)

11 December, 2011

Finding k'th root of a number

The need:
    The need is nothing but to find k'th root of a number.
The code:
----------------------------------------------------------------
#include<stdio.h>
#include<math.h>
main()
{
    printf ("*********a program to find k'th root of x ....\n\n");
    char c;
    float i,j,k,m;
    do
    {
    printf ("To get k'th root of x ....\n");
    printf ("type the values .....\n\n");
    printf ("x= "); 
    scanf("%f",&i);
    printf ("k=  ");
    scanf("%f",&k);
    j=pow(i,(1/k));
    printf("\n %dth root of%f = %f\n\n\n",(int)k,i,j);
    printf("do you want to try more? y/n \t");
    fflush(stdin);
    c=getchar();
    }while(c=='y');
}
---------------------------------------------------------------- 
The Approach:
     The approach is very simple. Lets apply simple math
If y^k = x
then y =  x^(1/k)
and the problem is solved because we have built-in pow() function for a power.

10 December, 2011

Variable number of arguments to a function

Variable number of arguments:
     Till now we have seen various types of functions in C. Some them were built-in and some user defined. There are a lot of noticeable point about them. Intuitively We can say that all the functions should possess same characteristics  whether it is user defined or built-in. We have also seen function returning some value, not returning any value, taking no argument and taking certain fixed number of arguments with certain data-types.
    Some-times a question can come in your mind if it is possible for a function to accept any number of arguments in C language. Off course it is possible !!! In fact we have used such function many times. Don't remember??? Recall our most commonly used functions printf() and scanf(). How many arguments does printf() function take??
     Let me remind you when we pass arguments to a function while calling it, the arguments are separated by a comma(,). So printf() function takes variable number of arguments. First argument to printf() is a character string and after that some other arguments of various types may or may not come. This fact encourages us to create our own user defined function which would take variable number of arguments.
Problem and solution:
    There may be some problems while implementing variable arguments. One such problem is to determine how many arguments have been passed during a particular call. To overcome that problem there is a rule that at least one argument must be specified in the declaration of function. For more ease I will be giving that argument as a number equal to the count of following arguments so that I can easily know that how many arguments are being passed.
Sample program:
     This program is one of the simplest programs for illustrating the use of variable number of arguments. There is a function sum which can take may arguments and print the sum of those.
Have a look.
------------------------------------------------------------
#include <stdio.h>
#include <stdarg.h>
int sum(int num, ... );
int main( void )
{
    printf("This is program to show the use of variable numbers of arguments to a function\n");
    printf( "Sum of 1,2,3,4 is %d\n", sum(4,1,2,3,4) );
    printf( "Sum of 4,5,3 is %d\n", sum(3,4,5,3) );
    printf( "Sum of 7,3,4,9,1,5 is %d\n", sum(6,7,3,4,9,1,5) );
    return( 0 );
 }
int sum(int num, ... )
{
    int answer = 0;
    va_list argptr;
    va_start( argptr, num );
    while(num-- > 0)
    answer += va_arg( argptr, int );
    va_end( argptr );
    return( answer );
} 
------------------------------------------------------------
Explanation:
    Declaration of the function is clear as shown. Here argptr is a variable of type va_list. After va_start function is executed here, argptr will contain list of rest of the variables. After that each value of each argument can be accessed with the help of va_arg() function. When all the arguments are finished va_end() function should be put at the end. This va_end() is analogous to fclose() in file handling.
 
Remarks: 
1. variable number of arguments means the function can take some random(but finite) number of arguments. This does not mean that the function can take infinite number of arguments. Maximum number of arguments to a function are limited and depend on the compiler.

Insertion sort in C

The need:
     This is a program to sort a given array of numbers using insertion sort. This program sorts numbers in increasing order. To read more about insert sort read wikipedia.
The code:
----------------------------------------------------------
#include<stdio.h>
void insert_sort(int a[],int size);
int main()
{
    int i,size;
    printf("program for sorting using insert sort\nHow many numbers do you want to sort\n");
    scanf("%d",&size);
    int arr[size];
    printf("enter numbers\n");
    for(i=0;i<size;i++)
    scanf("%d",&arr[i]);
    
    printf("the array before sort is\n");
    for(i=0;i<size;i++)
    printf("%d ",arr[i]);
    printf("\n");
    insert_sort(arr,size);
    printf("the array after sort is\n");
    for(i=0;i<size;i++)
    printf("%d ",arr[i]);
    printf("\n");
    return 0;
}

void insert_sort(int a[],int size)
{
    int i,j,k,temp;
    for(i=1;i<size;i++)
    {
        j=0;
        temp=a[i];
        while(temp>a[j]&&j<i)
        j++;
        for(k=i;k>j;k--)
            a[k]=a[k-1];
        a[k]=temp;
    }
}
----------------------------------------------------------
Approach:
   The approach is to follow the existing algorithm. Read algorithm on wikipedia. The basic idea is traverse the array form start, temporarily store value of current element and search for the place to the left of that element where the value fits. When you find the place, shift the elements after that position by one to make the void to place temporarily stored element.

09 December, 2011

finding kth largest number out of n numbers

The need:
     This program gives the kth largest number from the given unsorted list of n numbers. I don't know what could be the application of that but some sites tell that it is asked as interview question sometimes.
The code:
----------------------------------------------------------
/*find kth largest number from a list of n numbers*/
#include<stdio.h>
#include<stdlib.h>
void getMaxToFront(int *p,int front, int end);
void swap(int *, int *);
int main()
{
    int i,*num,n,k;
    printf("This is a program to find kth largest number from a list of numbers\n");
    printf("how many are total numbers\n n = \t");
    scanf("%d",&n);
    if(1>n)
        exit(printf("n cannot be less than 1\n"));
    printf("for kth largest give value of k\n k = \t");
    scanf("%d",&k);
    if(k<1)
        exit(printf("k cannot be less than 1\n"));
    if(k>n)
        exit(printf("k must be less then n\n"));
    num=(int *)malloc(n*sizeof(int));
    printf("now enter %d integers\n",n);
    for(i=0;i<n;i++)
    scanf("%d",num+i);
    for(i=0;i<k;i++)
        getMaxToFront(num,i,n-1);
    printf("\n%d is %dth largest\n",*(num+k-1),k);
    getchar();
    return 0;
}

void getMaxToFront(int *p,int front, int end)
{              
    int i;
    for(i=front+1;i<=end;i++)
        if( *(p+front) < *(p+i) )
        swap(p+front,p+i);
}

void swap(int *a,int *b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

----------------------------------------------------------
Approach:
   first approach is simple. Pick the largest bring it to 1st position, then pick largest from the rest of list and bring on 2nd position and so on upto kth :-).

Remarks:
Analyze the case:
n=100, k=5;
The above program is fine with that. Just find out biggest 5 numbers and done.
Now have a look at this case:
n=100, k=95;
In this case you will not want to go from front to end because you will have to iterate the loop in main 95 time. Instead we'll find out 6th smallest and go end to front... :-)
so better modify the above program a little bit which is like below:
-------------------------------------------------------------
/*find kth largest number from a list of n numbers*/
#include<stdio.h>
#include<stdlib.h>
void getMaxToFront(int *p,int front, int end);
void getMinToEnd(int *p,int front, int end);
void swap(int *, int *);
int main()
{
    int i,*num,n,k;
    printf("This is a program to find kth largest number from a list of numbers\n");
    printf("how many are total numbers\n n = \t");
    scanf("%d",&n);
    if(1>n)
        exit(printf("n cannot be less than 1\n"));
    printf("for kth largest give value of k\n k = \t");
    scanf("%d",&k);
    if(k<1)
        exit(printf("k cannot be less than 1\n"));
    if(k>n)
        exit(printf("k must be less then n\n"));
    num=(int *)malloc(n*sizeof(int));
    printf("now enter %d integers\n",n);
    for(i=0;i<n;i++)
    scanf("%d",num+i);
    if(k<=n/2){
    printf("\nusing getMaxToFront\n");
    for(i=0;i<k;i++)
        getMaxToFront(num,i,n-1);
    }
    else{
    printf("\nusing getMinToEnd\n");
    for(i=n;i>=k;i--)
        getMinToEnd(num,0,i-1);
    }
    printf("\n%d is %dth largest\n",*(num+k-1),k);
    getchar();
    return 0;
}

void getMaxToFront(int *p,int front, int end)
{                //end is needed as an argument here because we need to use the length of list
    int i;
    for(i=front+1;i<=end;i++)
        if( *(p+front) < *(p+i) )
        swap(p+front,p+i);
}

void getMinToEnd(int *p,int front, int end)
{                //actually we could have skipped front as an argument here observe each time I am passing 0 as front
    int i;
    for(i=end;i>=front;i--)
        if( *(p+end) > *(p+i) )
        swap(p+end,p+i);
}

void swap(int *a,int *b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
-------------------------------------------------------------
This program uses the method/function which gives less number of loop runs.

Finding whether a number is armstrong number of not

The need:
     This one is trivial program at this point of time. Still putting on demand of Rahul Devra.For those who dont know what is Armstrong number (Narcissistic number) first have a look at Narcissistic number on wikipedia.
The code:
----------------------------------------------------------
/*Find whether entered number is armstrong number or not*/
#include<stdio.h>
#include<math.h>
int digit_count(int x);
int isArmstrong(int x);

int main()
{
    int flg=0,num;
    printf("This is a program to find whether a number is armstrong number\n");
    printf("enter a natural number\n");
    scanf("%d",&num);
    if(isArmstrong(num))
    printf("%d is an armstrong number\n",num);
    else
    printf("%d is not an armstrong number\n",num);
    getchar();
    return 0;
}

int digit_count(int x)
{
    int count=0;
    if(x==0)
    return 0;
    while(x/=10)
    count++;
    return count+1;
}

int isArmstrong(int x)
{
    int i,num_digit,sum=0,current_digit,holder;
    num_digit = digit_count(x);
    holder=x;
    for(i=0;i<num_digit;i++)
    {
        current_digit = x%10;
        sum+=pow(current_digit,num_digit);
        x/=10;
    }
    if(sum==holder)
    return 1;
    else
    return 0;
}
----------------------------------------------------------
Approach:
   The approach is simple. Go by the definition, take digit by digit check for the condition for Armstrong number and that's it.

07 December, 2011

getting nth term of fibonacci series unlimited number of terms

The need:
     The program for fibonacci series is very simple but those programs give you terms upto the limit of integer size. This is a program to print Fibonacci series upto 10000th term. I wrote this program when I noticed people coming on previous fibonacci program in search of 2011th term or so.
The code: 
--------------------------------------------
#define MAX 2100 
#include<stdio.h> 
#include<string.h> 
#include<stdlib.h> 
void print(char x[]); 
void add(char x[], char y[], char z[]); 

int main() 
{ 
    int i=0,j,num; 
    char n_minus1[MAX]="1",n_minus2[MAX]="1",nth[MAX]=""; 
    printf("This is a program to print fibonacci sequence upto desired term.(max 10000)\n"); 
    printf("\nenter a natural number upto which do you want fibonacci series\n");
    scanf("%d",&num); 
    if(    num<1||num>10000) 
    { 
        printf("The desired term index was either invalid or greater than 10000\n"); 
        exit(0); 
    }
    printf("\noptions:\n1. print only %dth term\n2. print all terms\n",num);
    scanf("%d",&j);
    switch(j)
    {
        case 1: 
                if(num<2){
                printf("The first term is 1\n");
                break;
                }
                if(num<3){
                printf("The second term is 1\n");
                break;
                }
                for(i=2;i<num;i++)
                {
                  add(nth,n_minus1,n_minus2);
                  strcpy(n_minus2,n_minus1);
                  strcpy(n_minus1,nth);
                }
                printf("The %dth term is ",num);
                print(nth);
                break;
        case 2:    printf("\nFibonacci series upto %dth term\n\n",num);
                printf("term \tvalue\n",num);
                printf("%4d \t1\n",1);
                if(num<2)
                break;
                printf("%4d \t1\n",2);
                if(num<3)
                break;
                for(i=2;i<num;i++)
                {
                  add(nth,n_minus1,n_minus2);
                  printf("%4d\t",i+1);
                  print(nth);
                  strcpy(n_minus2,n_minus1);
                  strcpy(n_minus1,nth);
                }
                break;
        default: printf("Invalid choice...!!! \tExiting\n");
                exit(0);
    }
    printf("\n\nprgram finished successfully.\t press any key to continue\n");
    getchar(); 
    return 0; 
} 

void print(char x[]) 
{ 
    int i; 
    for(i=strlen(x)-1;i>=0;i--) 
    { 
        putchar(x[i]); 
        if(i%5==0) 
        putchar(' '); 
    } 
    putchar('\n'); 
    return; 
} 

void add(char x[],char y[],char z[]) 
{ 
    int i,ylen,zlen,equal;
    char c = 0,temp;
    ylen = strlen(y);
    zlen = strlen(z);
    equal = (ylen == zlen) ? 1 : 0; 
    for(i=0;i<zlen;i++) 
    { 
        x[i]=c + y[i] + z[i] - '0'; 
        if( x[i]-'0' > 9)
        {
            x[i]-=10;
            c=1;
        }
        else
        c=0; 
    }
    if(equal)
    {
        if(c!=0)
        {
            x[i]=c + '0';
            x[i+1]='\0';
        }
    }
    else
    {
        x[i]=c + y[i];
        x[i+1]='\0';
    } 
    return; 
}
-------------------------------------------- 

The approach: 
This program creates a Fibonacci series upto the terms given by the user. The logic is same. Just go with the definition of Fibonacci that any term is the sum of its two preceding terms. Here nth always hold current term and n_minus1 and n_minus2 hold previous 2 terms(except for first 2 terms case). I have already told that integers are very small to work when we have more than 10digits in the scene so these 3 variables are taken as strings. add() is UDF defined by me which takes 3 arguments x,y,z. add puts sum of y and z into x. This add() is the only twist here to differentiate this program from program38 of this blog.

Remarks:
1. In this program is capable to give you upto 10000th term of fibonacci easily.
2. You can get upto more terms. all you have to do is to increase the value of max in #define statement. This is why I wrote unlimited in the title.

06 December, 2011

program to reverse the spelling of words in a sentence

The need:
     I don't know what could be the need of this program but I found this question on many sites and thats why I wrote this program.
The code:
----------------------------------------------------------
#include<stdio.h>
#include<string.h>

void reverse(char *str,int start, int end)
{
    char temp;
    int i,j;
    i=end-start;
    for(j=0;j<=i/2;j++)
    {       
        temp=*(str+start+j);
        *(str+start+j)=*(str+start+i-j);
        *(str+start+i-j)=temp;
    }
}

rev_word(char *str)
{
    int start=0,end=0,i=0;   
    while(*(str+i)!='\0')
    {
        if(*(str+i)==' ')
        {
            end=i-1;
            reverse(str, start, end);
            i++;
            start=i;
        }
        else
            i++;
    }
    end=i-1;
    reverse(str, start, end);
}

int main()
{
    char a[]="I dont know why useless programs are asked";
    printf("before\n%s\n",a);
    rev_word(a);
    printf("after\n%s\n",a);
    return 0;
}
----------------------------------------------------------
Approach:
   The approach is simple. make a note of start and end points (indices) of each word and reverse with the help of those points. The UDF reverse() does the job here.

program to reverse the order of words in a sentence

The need:
     I don't know what could be the need of this program but I found this question on many sites and thats why I wrote this program.This program is extension of previous program.
The code:
----------------------------------------------------------
#include<stdio.h>
#include<string.h>

void reverse(char *str,int start, int end)
{
    char temp;
    int i,j;
    i=end-start;
    for(j=0;j<=i/2;j++)
    {      
        temp=*(str+start+j);
        *(str+start+j)=*(str+start+i-j);
        *(str+start+i-j)=temp;
    }
}

rev_word(char *str)
{
    int start=0,end=0,i=0;  
    while(*(str+i)!='\0')
    {
        if(*(str+i)==' ')
        {
            end=i-1;
            reverse(str, start, end);
            i++;
            start=i;
        }
        else
            i++;
    }
    end=i-1;
    reverse(str, start, end);
}

int main()
{
    char a[]="I dont know why useless programs are asked";
    printf("before\n%s\n",a);
    rev_word(a);
    reverse(a, 0, strlen(a)-1);
    printf("after\n%s\n",a);
    return 0;
}
----------------------------------------------------------
Approach:
   The approach is simple. make a note of start and end points (indices) of each word and reverse with the help of those points. The UDF reverse() does the job here. After that reverse the whole sentence character by character. I have used my UDF here because its existing and I dont need to write or search for another function though one could also use strrev() built-in function to reverse the whole sentence character by character.
Remarks:
1. You can modify reverse() function here into ordinary string_reverse (same as built-in strrev) function. For that remove arguments start and end from the function definition and use 0 in place of start and (length of string-1) as end.
Other approach:
2. Here for doing the whole thing I have used only one extra character other than the provided string (off course I have also used counters etc. but that is different thing). If I was allowed to use as much space as I wanted, I would have not thought this much like I have thought here --> reversing the spelling of each word and then reversing the whole string. In that case I would have made use of my stack concepts and using almost no brain I could have got it done. Have a look how simple is this. Steps are:
1. read word by word (using scanf with %s)
2. keep on pushing all words on a stack till last word.
3. Now pop each word and print. :-)
For this approach have a look at next program on this topic.

23 November, 2011

Get the execution time of a C program

The need:
     Need is same as previous program which gives you precision of nanoseconds but that program would work only on linux. This program will work on windows also but will give you precision of milli seconds only.  All you need to do is to place your test program code (the code whose execution time is to be measured) in between the comments which indicate the start and end of the program.
The code:
----------------------------------------------------------
/*This program should work on both windows and linux*/
#include<time.h> 
#include<stdio.h>
#include<stdlib.h> 
#define START if ( (start_time = clock()) == -1) {printf("Could not call clock");exit(1);} 
#define STOP if ( (stop_time = clock()) == -1) {printf("Could call clock");exit(1);} 
#define PRINT_TIME_DIFF printf( "Your program took %.3f seconds.\n", ((double)stop_time-start_time)/CLOCKS_PER_SEC); 
    
int main()
{ 
    clock_t start_time, stop_time;
    int i=0; 
    START
    //test program code begins
    
    //test program code ends 
    STOP 
    PRINT_TIME_DIFF
    return 0; 
} 
----------------------------------------------------------
Approach:
   The approach is simple. There is a built-in function clock() in <time.h> header file. In this program I have use macros to differentiate between your test code and the statement which would be used to print the time and other things. I thought this would simplify the look of the program a little bit.
Remarks:
1. This program should work on both windows and linux.
2. This program will give accuracy of (1/1000)th part of a second.

22 November, 2011

Getting running time of a C program

The need:
     Need is obvious.Whenever you are curious to find running time of a program or you are asked to do so, you can use this program. All you need to do is to place your program code(the code between the brackets of main() function ) in between the comments which indicate the start and end of the program.
The code:
----------------------------------------------------------
/*This program is intended to work on linux*/
#include <stdio.h> 
#include <time.h> 
void print_time_diff(struct timespec begin,struct timespec end);
int main ( void )
{
    struct timespec start, end;
    gettimeofday(&start, NULL);
    //program code begins
    //program code ends
    gettimeofday(&end, NULL);
    print_time_diff(start,end);
    return 0;
}

void print_time_diff(struct timespec begin,struct timespec end)
{
    unsigned int sec,nanosec;
    if (end.tv_nsec<begin.tv_nsec) {
        sec = end.tv_sec-begin.tv_sec-1;
        nanosec = 1000000000+end.tv_nsec-begin.tv_nsec;
    } else {
        sec = end.tv_sec-begin.tv_sec;
        nanosec = end.tv_nsec-begin.tv_nsec;
    }
    printf("your program took %d seconds and %u nanoseconds to run.\n",sec,nanosec);
} 
----------------------------------------------------------
Approach:
   The approach is simple. There is a built-in structure timespec in <time.h> header file of linux.The built-in definition of structure is:
struct timespec
  {
    __time_t tv_sec;        /* Seconds.  */
    long int tv_nsec;        /* Nanoseconds.  */
  };
The program declares 2 struct variables start and end. built-in function gettimeofday() fills the struct variable passed to it with suitable values at that particular instance. This implies that start gets the value of time when your program (code to be measured) is just about to start and end gets the value of time as soon as your program finishes.
print_time_diff() is user defined function which prints the difference of the two times passed to it as arguments.
Remarks:
1. This program should not work on windows and operating systems other than linux.
2. The program which would work on windows will be posted shortly.

Heap sort in C

The need:
   Heap sort is a better than bubble, selection and insertion algorithm for sorting. To show how heap can be useful in real life implementation.
The code:
-----------------------------------------------------------
/*this program is an array implementation of heap*/ 
#include<stdio.h> 
#include<string.h> 
#include<stdlib.h> 

void print_array(int a[],int array_size); 
void heap_sort(int a[],int array_size); 
void heapify(int a[],int count); 
void adjust_down(int a[],int start, int end); 

main() 
{ 
    int i,arr[50],size=0; 
    arr[0]=0; 
    printf("how many elements do you want to enter\n");
    scanf("%d",&size); 
    if(size<1)
    {
        printf("You did not enter a valid count of elements.\n");
        printf("Rerun the program and try again\n");
        exit(0);
    }
    printf("enter array\n"); 
    for(i=1;i<=size;i++) 
        scanf("%d",&arr[i]);
    printf("the array before heap sort.\n"); 
    print_array(arr,size); 
    heap_sort(arr,size);
    printf("the array after heap sort.\n"); 
    print_array(arr,size);    
} 

void heap_sort(int a[],int array_size)
{
    int i,j,heap_end,temp;
    heap_end=array_size;
    heapify(a,array_size);
    while(heap_end>2)
    {
        temp=a[1];
        a[1]=a[heap_end];
        a[heap_end]=temp;
        heap_end--;
        adjust_down(a, 1, heap_end);
    }
}

void heapify(int a[],int count) 
{ 
    int start;
    start = count/2 + 1;
    while(start>0)
    {
        adjust_down(a, start, count);
        start--;
    } 
} 

void adjust_down(int a[],int start, int end)
{
    int root = start,temp,bigger_child;
    while(2*root <= end)
    {
        if(2*root+1 > end)
        {
            if(a[2*root]<a[root])
            {
                temp=a[root];
                a[root]=a[2*root];
                a[2*root]=temp;
            }
            root=2*root;
        }
        else
        {
            bigger_child = (a[2*root]>a[2*root+1])? 2*root : 2*root+1;
            if(a[root]<a[bigger_child])
            {
                temp=a[root];
                a[root]=a[bigger_child];
                a[bigger_child]=temp;
            }
            root=bigger_child;
        }
    }
}

void print_array(int x[],int size) 
{ 
    int i; 
    for(i=0;i<size;i++) 
        printf("%d\t",x[i+1]); 
    putchar('\n'); 
} 
-----------------------------------------------------------

The approach:
   The approach is simple. This program uses a max heap to sort the numbers in ascending order. You know that in a max heap root is largest element. This program works on the below logic:
1. first take an array from user. Notice that I have saved the elements from index one leaving index 0 empty. See remark1 below.
2. make that array to satisfy max heap property(max - heapify array).
3. Now swap last element of heap with the root. So that the biggest element comes last.
4. Now leave the last element and assume rest array as heap.
5. Adjust the new heap so satisfy max heap property.
6. Repeat step 3-5 till only root is left as rest part of heap.
7. You will be getting an increasingly sorted array.
you can refer to wikipedia for more theory and graphics about heap sort.

Remark:
1. This is the convention I follow when I implement heap on an array because this gets you left and right children as 2*current_node, and (2*current_node + 1). You can use other convention of starting with index 0. In that case left and right children will be evaluated (2*current_node+1), and (2*current_node + 2) which seems a little bigger expressions to me :P

Concept of Heap in C

Heap is a concept which can be implemented on trees, priority queues and arrays. When we plot a heap on paper, we draw it as binary tree. We also analyse a heap as a binary tree. There are 2 types of heaps:
1. min heap: parent node is always less than both children.
2. max heap: parent node is always greater than both children.
In both the cases equality is permitted. No other property is required for a heap. We do not care about any other thing like which child is greater.

Heap can be utilized in
1. heapsort
2. a priority queue can be implemented with a heap
3. auto balancing binary tree

For general purposes this much on heap is enough. For more you can study in details on wikipedia.

16 October, 2011

Creating and traversing a binary search tree

The need:
     This program is written to show creation and various types of printing of a binary search tree. This program takes values and put them in a binary search tree and then prints the resulting tree in preorder, inorder and post order.
 The BST(Binary Search tree): a binary search tree is a binary tree in which value of each node is greater or equal than that of its left child and less than that of its right child. Hence all nodes in the left sub-tree of a node are less than or equal to the value of that node and all nodes in the right sub-tree of a node are greater than the value of that node if it is a binary search tree. We'll use this property while inserting a node in the BST in insert() function.
The code:
----------------------------------------------------------
#define MAX 10
#define DEBUG if(!(root->left))    printf("inserted %d to the left of %d\n",x,root->data);
#include<stdio.h>
#include<stdlib.h>
struct tree_node
{
    int data;
    struct tree_node *left,*right,*parent;
};
typedef struct tree_node node;
node * new_node(int x);
node * insert_node(node *root, int x);
void print_preorder(node *root);
void print_inorder(node *root);
void print_postorder(node *root);

int main()
{
    node *root=NULL;
    int i;
    int arr[]={5,6,1,9,0,4,2,3,8,7};
    for(i=0;i<MAX;i++)
    root = insert_node(root, arr[i]);
    printf("\ntree pre order is\n");
    print_preorder(root);
    printf("\n\ntree in order is\n");
    print_inorder(root);
    printf("\n\ntree post order is\n");
    print_postorder(root);
    return 0;
}

node * insert_node(node *root, int x)
{
    if(!root)
    {
        root = new_node(x);
        return root;
    }
    if(root->data > x)
    {
//        DEBUG
        root->left = insert_node(root->left,x);
    }
    else
    {
//        DEBUG
        root->right = insert_node(root->right,x);
    }
    return root;
}

void print_preorder(node *root)
{
    if(!root)
    return;
    printf("%d ",root->data);
    print_preorder(root->left);
    print_preorder(root->right);
    return;
}

void print_inorder(node *root)
{
    if(!root)
    return;
    print_inorder(root->left);
    printf("%d ",root->data);
    print_inorder(root->right);
    return;
}

void print_postorder(node *root)
{
    if(!root)
    return;
    print_postorder(root->left);
    print_postorder(root->right);
    printf("%d ",root->data);
    return;
}

node * new_node(int x)
{
    node *furnished;
    furnished = (node*)malloc(sizeof(node));
    furnished->data=x;
    furnished->left=NULL;
    furnished->right=NULL;
    furnished->parent=NULL;
    return furnished;
}
----------------------------------------------------------
Approach:
    This program is just to show the printing of a tree in pre-order, inorder and post order. For that first we have to make the tree. Here we dont have tree with 3 nodes necessarily. So we need to make a function to construct the tree. Here insert() function does the job. create_node() function creates a node with given data/value ans returns it address. we create first node, make it root. After that we create 2 more nodes and make them left and right children of root. Then there are 3 functions in_print(), pre_print() and post_print() which print the expression in infix, prefix and postfix form respectively.
Remarks:
1. We noticed that here in each function I have used recursion like I have already said in previous posts that recursion makes our life easier in trees.
2. Uncomment DEBUG to see where the nodes are being inserted.
3. Here I am taking node data from an array we can take data from user also.

14 October, 2011

Inorder, Preorder and Post-Order traversal of tree

The need:
     This program is written to show the program implementation of the concept explained in the previous post. This program is the implementation of 2 + 3 example given there.
The code:
----------------------------------------------------------
#include<stdio.h>
#include<stdlib.h>
struct tree
{
    char num;
    struct tree *left, *right, *parent;
};
typedef struct tree node;

void in_print(node *p);
void pre_print(node *p);
void post_print(node *p);
node * create_node(char c);
int main()
{
    int i;
    node *root=NULL;
    root = create_node('+');
    root->left = create_node('a');
    root->right = create_node('b');
    printf("Pre order print\t\t");
    pre_print(root);
    printf("\nIn order print\t\t");
    in_print(root);
    printf("\nPost order print\t");
    post_print(root);
    putchar('\n');
    return 0;
}

node * create_node(char c)
{
    node *new_node;
    new_node = (node *)malloc(sizeof(node));
    new_node->num = c;
    new_node->parent = NULL;
    new_node->left = NULL;
    new_node->right = NULL;
    return new_node;
}

void pre_print(node *p)
{
    if(p==NULL)
    return;
    else
    printf("%c ",p->num);
    pre_print(p->left);
    pre_print(p->right);
}

void in_print(node *p)
{
    if(p==NULL)
    return;
    else
    in_print(p->left);
    printf("%c ",p->num);
    in_print(p->right);
}

void post_print(node *p)
{
    if(p==NULL)
    return;
    else
    post_print(p->left);
    post_print(p->right);
    printf("%c ",p->num);
}
----------------------------------------------------------
Approach:
    This program is just to show the printing of a tree in pre-order, inorder and post order. For that first we have to make the tree. Here I have not created a bigger tree. Here we have the simplest tree with 3 nodes only. So we need not make a function to construct the tree. Here simply I have created 3 nodes and put them to make a small tree. create_node() function creates a node with given data/value ans returns it address. we create first node, make it root. After that we create 2 more nodes and make them left and right children of root. Then there are 3 functions in_print(), pre_print() and post_print() which print the expression in infix, prefix and postfix form respectively.
Remarks:
1. Here this program is shown to print the simplest expression in prefix, infix and post-fix form but this program can be used to print any binary tree in pre-order, inorder and post order.
2. This program is the base of all the tree programs related to trees.

12 October, 2011

Inorder, Preorder and Post-Order traversal : An overview

The Idea:
Lets first have a look at some mathematical side. The Infix, Prefix and Post-fix notations are exactly analogous to the In-order, Preorder and Post-order traversal of trees.
Have a look at the expresstion:
a + b
     This is a familiar expression to all of us. Here + is an operator with a and b as operands. This is one way to write sum of a and b. This way is called in-fix notation. In this way we write operator in between the operands. This is the only used method for writing expressions for human understanding. Thats why everybody is familiar to this method. But this is not the only way to be used for every purpose. there are 2 more ways.
     Prefix notation: In this way of writing expressions the operator comes first which is followed by the operators. The same expression can be written in Prefix notation as:
+ a b
     Postfix notation: In this way of writing expressions the operator comes last after both the operands have been written. The same expression can be written in Prefix notation as: 
a b +

Analogy comes from here. Have a look at the above image.
Its a tree with + at parent node and 2 and 3 as child nodes. Now we have
Infix: 2 + 3
Prefix: + 2 3
postfix: 2 3 +
    We see that it is the position of operator which changes and decides which fix notation is this. The relative positions of operands are always same.
    This is about expressions writing. Now lets move to traversal of trees in data-structures topic. In the same manner as in the case of expressions in trees also left child will always be accessed before the right. It is the root which decides which type of traversal it is.
     InOrder Traversal: In this way of traversing tree the root is accessed first after that the children are accessed.
     PreOrder Traversal: In this way of traversing tree one child is accessed first and then the root is accessed after that the other child is accessed.
     PostOrder Traversal: In this way of traversing tree the root is accessed after both of the children are accessed.
   here this concept is explained with the basic tree consisting of only 3 nodes but this holds true for any tree(binary tree). Recursion will play very important role in tree traversal. We can store a mathematical expression in tree and then that can be printed in any order using inorder, preorder and postorder traversal giving infix, prefix and post-fix form of that expression respectively. Obviously this is not the only use of trees.

11 October, 2011

Concept of trees in C:

The concept of trees is same to real world tree. In real word every tree has roots, and can have many branches. Each branch can have sub-branches. If you look at branches and sub-branches as a whole, the combination looks like a tree (lets call it a sub-tree). Same is the case of a tree in programming jargon. There is only one difference in plotting the trees. A real world tree has roots on the downside while in C programming, a tree is upside down which has roots on the top and sub-trees below that. Tree is a variation of linked lists.

Here in programming the most commonly used tree is a binary tree. Now lets come to data-structural jargon. A binary tree is a tree in a tree (data structure) in which each node (say current node) has addresses of 2 next possible nodes. The current node is called parent node and these next 2 nodes are called children of that node. We'll call them left child and right child. From the current node, if you want to come down, you have 2 options (either you can come on left child or the right child).

You people have seen that we can traverse a singly linked list in one direction and doubly linked list in two directions in the similar way in a tree you can reach max three nodes from a current node. So in a binary tree each node has only 2 address pointers, you can traverse only in the down direction. If you want to traverse the tree in both the directions (downward as well as upward), each node must be having address of its parent node also.

Here the node structure is a bit different. You can think of a binary tree as a continuation of linked lists from singly to doubly to binary tree. Let me explain further. In node of a singly connected linked list we have one single pointer pointing to next node and in node of a doubly connected linked list we have 2 pointers which can point to other 2 nodes (next and previous nodes). Similarly in a node of a binary tree we have 3 pointers which can point to 3 other nodes one to parent, one to left child, one to right child so that we can traverse easily in both the directions.

23 September, 2011

program to print a linked list in reverse order

The need: 
     This program is a program to prints a linked list in reverse order without actually reversing it (For reversing a given linked list have a look on program78 of this blog). This program is written to show how recursion becomes more useful. First it asks user to enter numbers to be entered into linked list then creates a linked list, prints it in same as given and reversed order.
The code: 
---------------------------------------------------------
#include<stdio.h>
#include<stdlib.h>
typedef struct linked_list
{
    int item;
    struct linked_list *next;
}node;

node *create_list();
void print_list(node *);
void print_list_in_reverse(node *);

int main()
{
    node *head=NULL;
    printf("This program creates a linked list and then prints it first in given order and then in reverse\n");
    printf("create a list by entering elements press -999 to end\n");
    head=create_list();
    printf("\nThe list is\n");
    print_list(head);
    printf("\nThe list in reverse order is");
    print_list_in_reverse(head);
    printf("\n");
    return 0;
}

node *create_list()
{
    int x;
    node *temp=NULL;
    scanf("%d",&x);
    if(x!=-999)
    {
        temp=(node*)malloc(sizeof(node));
        temp->item=x;
        temp->next=NULL;
        temp->next=create_list();
    }
    return temp;
}
void print_list(node *p)
{
    if(p)
    {
        printf("%d ",p->item);
        print_list(p->next);
    }
    else
    printf("\n");
}

void print_list_in_reverse(node *p)
{
    if(p)
    {
        print_list_in_reverse(p->next);
        printf("%d ",p->item);
    }
    else
    printf("\n");
}
---------------------------------------------------------
The need:
   The approach is nothing but basics of recursion.
If we say the recursion in create_list function in normal English, we'll say "It will take a number form user if it is not -999, a new node is created, data is filled in it and address of this node is returned else NULL is returned." because temp is initialised to NULL each time in the starting of function.
If we say the recursion in print_list function in normal English, we'll say "It will print the data of a node and then go for doing the same to the next node after that if present".
If we say the recursion in print_list_in_reverse function in normal English, we'll say "It will print the data of a node when all the node after that are printed or if there is no node after that node".
 
Remarks:
1. We can print linked list as it is (in the given order) without using extra storage or extra thinking. We can just use loops but if we are asked to write a program to print the linked list without actually reversing it, we can not do it by just using loops. What we can do is next point.
2. For that we have to create a stack and push addresses of all the elements of linked list on it starting from head to end. Then pop addresses one by one and print the corresponding data. This requires extra storage and extra thinking.
3. So in this program recursion is the way to do the same without extra thinking and without explicitly using extra memory and functions.
4. I wrote explicitly with stress because recursion actually uses its own stack (System stack). Now I am not going into these details.

12 September, 2011

getting nth term of fibonacci series using recursion

The need: 
     This program is written just to give example of writing programs with recursion. This program finds nth term of a fibonacci series. Given that first term is 1, second term is also 1 and for rest terms T(n)=T(n-1) + T(n-2) holds true.
The code: 
---------------------------------------------------------

#include<stdio.h>
#include<stdlib.h>
int fibo(int x);

int main()
{
    int n,Tn;
    printf("Enter which term do you want?\n");
    scanf("%d",&n);
    if(n>0)
    Tn=fibo(n);
    else
    exit(printf("term index entered should be natural number\n"));
    printf("T(%d) of fibonacci series = %d\n",n,Tn);
    return 0;
}

int fibo(int x)
{
    int term;
    if(x==1)
      term=1;
    else if(x==2)
      term=1;
    else
      term= fibo(x-1) + fibo(x-2);
    return term;
}
---------------------------------------------------------
Remarks:
1. This program may not give correct output if the desired term is after 40th term. This is because the later terms can not fit into int data-type of C and data overflows.
2. This type of recursion when one function calls 2 instances of itself, is called binary recursion.
3. This program was written just to show use of binary recursion. Personally I would suggest not to use a recursion which calls 2 or more instances because not only it uses more system resources but also slows down the program execution drastically. For fibonacci series without recursion see program38 of this blog.

11 September, 2011

programs to find sum of first n natural numbers with recursion

The need: 
     This is a simple programs to find sum of first n natural numbers with recursion explaining the example2 of previous to previous post. We know that natural numbers form a series whose first term is 1 and T(n)=n and this is obvious that sum upto n term = sum upto n-1 terms + nth term.
The code: 
---------------------------------------------------------


#include<stdio.h>
int get_sum(int x);

int main()
{
    int n,Sn;
    printf("Enter upto which number do you want sum?\n");
    scanf("%d",&n);
    Sn=get_sum(n);
    printf("S(%d) = %d\n",n,Sn);
    return 0;
}

int get_sum(int x)
{
    int SUM;
    if(x==1)
      SUM=1;
    else
      SUM= get_sum(x-1) + x;
    return SUM;
}
---------------------------------------------------------

finding nth term of the series using recursion

The need: 
     This is a simple program just to get start with recursion explaining the example1 of previous post. This is very specific purpose program. This program finds nth term of a series whose first term is 2 and T(n)=T(n-1) + 1; is given.
The code: 
---------------------------------------------------------


#include<stdio.h>
int get_term(int x);

int main()
{
    int n,Tn;
    printf("Enter which term do you want?\n");
    scanf("%d",&n);
    Tn=get_term(n);
    printf("T(%d) = %d\n",n,Tn);
    return 0;
}

int get_term(int x)
{
    int term;
    if(x==1)
      term=2;
    else
      term= get_term(x-1) + 1;
    return term;
}

---------------------------------------------------------

Recursion in C programming langauge

what is recursion?
  The word recursion bears meaning similar to self-repeating. In programming it can be useful for programmers. Recursion is mostly used when we work with series and linked lists. In mathematics you people may have seen recursion while working with series. There you might have encountered a problem in which n'th term of a series was given as a function of some previous term/terms and value of first term would be given. Let me remind you with examples. This is highly recommended that for you to go through the examples below and then proceed.

Example1:   A n'th term of a series is 1 more than the (n-1)th term. Find the 4th term of the series given that first term is 2.
   Solution: Given that. T(1)=2
      and T(n)=T(n-1) + 1;    ------>    Eq.-1   (n'th term as function of (n-1)th term)
      so T(4)=T(3) + 1;                       we'll write T(3) in terms of t(2)
           T(4)=T(2) + 1 + 1;               we'll write T(2) in terms of t(1)
           T(4)=T(1) + 1 + 1 + 1;         we'll write value of T(1)
           T(4)=2 + 1 + 1 + 1;
           T(4)=    Ans.
In this way you could find any term of the series.

Example2: Find the sum of first 5 natural numbers.
   Solution: If you know what natural numbers are, you'll know that
     It is given that nth term is n.
      S(1)=1      (Sum upto/of first term)
      and S(n)=S(n-1) + n;    (We got S(n) as a function of S(n-1))
             because this is obvious that
             sum up to n terms =  sum up to (n-1) terms + nth term.

      we have to find out
      so S(5)=S(4) + 5;                       we'll write S(4) in terms of S(3)
           S(5)=S(3) + 4 + 5;               we'll write S(3) in terms of S(2)
           S(5)=S(2) + 3 + 4 + 5;         we'll write S(2) in terms of S(1)
           S(5)=S(1) + 2 + 3 + 4 + 5;  we'll write value of S(1)
           S(5)=1 + 2 + 3 + 4 + 5;
           S(5)=15     Ans.
In this way you could find sum up to any term in the series.

That was mathematical recursion. In this case mathematical function used to express nth entity in terms of (n-1)th entity is called recursion function or recursive function.

Recursion in programming is same as mathematical recursion with a little bit programming touch. You have seen that a function can call other function to achieve any particular task. In programming when a function calls itself, its called recursion in programming jargon. As you'll practice programs, you'll get to know more. Next 2 programs will be for solving the 2 examples given above.

  In further posts we'll see how recursion can be used with linked lists and trees.
wait for it :P.

25 August, 2011

A program to count the occurrences of a string in a given text

The need: 
     This is a simple program to count the occurrences of a string in a given text. The code is straight forward and uses built-in function strstr().
The code: 
---------------------------------------------------------

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

int count_occur(char *big, char *small);

int main()
{
    char big_string[]="The fat cat sat on a mat",search_string[]="at";
    printf("total %d occurrences found\n",count_occur(big_string,search_string));
    return 0;
}

int count_occur(char *big, char *small)
{
    char *temp;
    int count=0;
    temp=strstr(big,small);
    while (temp!=NULL)
    {
        temp=strstr(temp+1,small);
        count++;
    }
    return (count);
}
--------------------------------------------------------

18 August, 2011

program 78: do everything with linked list

The need:
This is a program to show almost all basic operations on linked lists. This program is just a combination of various programs of linked lists written by me. This is written in a way that you can pick data and function definitions and can use as-it-is in other programs.
The code:
------------------------------------------------------------
#include<stdio.h> 
#include<stdlib.h> 

// defining data-type node 
struct linked_list 
{ 
    int num;
    struct linked_list *next;
}; 
typedef struct linked_list node ;   //defining datatype node 

//declaration of functions 

node *create_list(node *p); 
node *reverse(node *p); 
int count (node *p); 
void print(node *p); 
node *insert(node *p); 
node *find(node *p,int a); 
node *hatana(node *p); 
node *insert_sort(node *head,int n); 
void sort(node *p); 
node *rearrange(node *p); 

main() 
{ 
    int i;
    node *head=NULL ;
    printf("This is a program to do with linked list .\n\n");
    lebel:
    printf("Options :\n(1)Create linked list.\n(2)view list.\n(3)Insert element.\n(4)Delete Element.\n");
    printf("(5)To arrange list in increasing order.\n");
    printf("(6)To remove double entries .\n(7)to reverse the list\n(8)Exit program.\n");
    scanf("%d",&i);
    switch(i)
    {
        case 1 :
                printf("Enter element numbers .\n");
                printf("Type -999 to end :\n");
                head=create_list(head);
                printf("List created successfully .\nNumber of items in the list are %d.\n\n\n",count(head));
                goto lebel;
        case 2 :
                print(head);
                goto lebel ;
        case 3 :         
                head=insert(head);
                goto lebel ;
        case 4 :         
                head=hatana(head);
                goto lebel ;
        case 5 :
                sort(head);
                printf("\nsorted in increasing order\n\n");
                goto lebel;
        case 6 :
                rearrange(head);
                printf("\nduplicate entries deleted\n\n");
                goto lebel;
        case 7 :
                head=reverse(head);
                printf("\nList reversed\n\n");
                goto lebel;
        case 8 :
                exit (0);
                break;         
        default:     
                printf("Invalid Choice !!!.\n");
                goto lebel ;
                break;
    }
     
     
    return 0;
        
}                //main ends here 

node *create_list(node *list) 
{ 
    int i;
    list=NULL;
    scanf("%d",&i);
    if(i!=-999)
    {
        list=(node*)malloc(sizeof(node));
        list->num=i;
        list->next=create_list(list->next);
    }
    return list;
} 

node *reverse(node *p) 
{ 
    node *temp=NULL,*rev=NULL;
    while(p)
    {
        temp=p;
        p=p->next;
        temp->next=rev;
        rev=temp;
    }
    return(rev);
} 

int count (node *list) 
{ 
    if(list==NULL)
    return 0;
    else
    return (1+count(list->next));            //recursion 
} 


void print(node *list) 
{ 
    if(list==NULL)
    printf("The list is empty.\n\n");
    else
    {
        printf("%d-->",list->num);
        if(list->next==NULL)
        printf("END\n\n\n");
        else
        print(list->next);            //recursion 
    }
} 



node *find(node *list, int key)            //This function returns the node after which 
{     
    if(list->next)
    {                                    //the key is found .                             
        if(list->next->num == key)     /* key found */ 
            return(list);
        else if(list->next->next == NULL)    /* end */ 
            return(NULL);
        else
        find(list->next, key);
    }
    else
    return NULL;
} 



node *insert(node *head) 
{ 
    node *new_node;          /* pointer to new node */ 
    node *n1=head;        /* pointer to node preceding key node */ 
    int key;
    int x;            /* new item (number) to be inserted */ 
    if(!head)
    {
        printf("\nlist is not created yet.\n\n");
        return head;
    }
    printf("What value you want to insert?");
    scanf("%d", &x);
    printf("before which key item ? (type -999 if to be inserted last) ");
    scanf("%d", &key);

    if(key==-999)        /* insert new node at last*/ 
    {
        while(n1->next)
            n1=n1->next;    //navigate to last node 
            
        new_node = (node *)malloc(sizeof(node));
        new_node->num = x;
        new_node->next = n1->next;
        n1->next = new_node;
    }
    else if(head->num == key)        /* new node is first */ 
    {
        new_node = (node *)malloc(sizeof(node));
        new_node->num = x;
        new_node->next = head;
        head = new_node;
    }
    else        /* find key node and insert new node */ 
    {            /* before the key node */ 
        n1 = find(head, key);    /* find key node */

        if(n1 == NULL&&key!=-999)
           printf("\n key is not found !!!\n\n");
            
        else        /* insert new node */ 
        {
          new_node = (node *)malloc(sizeof(node));
          new_node->num = x;
          new_node->next = n1->next;
          n1->next = new_node;
        }
      }
      return head;
} 



node *hatana(node *list) 
{ 
    void delete_node(node *);
    node *n1,*n2;
    int key;
    if(!list)
    {
        printf("\nlist is not created yet.\n\n");
        return list;
    }
    printf("What value do you want to delete ?");
    scanf("%d",&key);
    if(key==list->num)                        //key is the first node 
    {
        n2=list->next;
        free(list);
        list=n2;
        printf("\n%d is deleted successfully .\n\n",key);
    }
    else
    {
         n1=find (list ,key);
         if(n1)
        {
            delete_node(n1);                        //This function deletes n1->next 
            printf("\n%d is deleted successfully .\n\n",key);
        }
         else
         printf("\nItem is not in the list !!! \n\n\n");
    }
return(list); 
} 


void delete_node(node *list)  //This function deletes list->next 
{ 
    node *n2;
    n2=list->next->next;
    free(list->next);
    list->next=n2;
} 



node *rearrange(node *list) 
{ 
    node *p1;
    sort(list);
    for(p1=list;p1->next!=NULL;p1=p1->next)
    {
        if(p1->num==p1->next->num)
        delete_node(p1);
    }
    return(list);
} 


void sort(node *list) 
{ 
    void exchange(int *s1,int *s2);
    node *p,*q;
    for(p=list;(p->next)!=NULL;p=p->next)
        for(q=list;(q->next)!=NULL;q=q->next)
        {
            if(q->num > q->next->num)            //simple bubble sort 
            exchange(&(q->num),&(q->next->num));
        }
} 

void exchange(int *s1,int *s2) 
{ 
    int temp;
    temp =*s1;
    *s1=*s2;
    *s2=temp;
}
------------------------------------------------------------
Remarks:
This program has a small bug try and find out.

17 August, 2011

Program 77: Queue implementation on linked lists general case

The need:
    This program shows how one can implement concept of queue in linked lists. This is extension of previous program. This program is analogous to program75 of this blog.
The code:

------------------------------------------------------
/*
This is a program showing the queue implimentation on linked list
program writtem by RP Singh
compiled and tested on C-free4.0 standard
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node1
{
    int item;
    struct node1 *next;
};
typedef struct node1 node;        //defining datatype node

struct q1
{
    node *front;
    node *rear;
    int length;
};
typedef struct q1 queue;        //defining queue datatype

void enqueue(node *, queue *);
node *dequeue(queue *);
int queue_length(queue *);
void view_queue(queue *);
node *create_node(void);
void fill_node(node *);


int main()
{
    int i,j;
    node *current_node;
    queue que;                    //local queue
    que.front=NULL;
    que.rear=NULL;
    que.length=0;
    printf("This is a demo program to show working of queues");
    anchor:                    //anchor is a label
    printf("\n\nyou have following options\n");
    printf("1. enqueue an item\n2. dequeue an item\n3. view queue\n");
    printf("4. count items in queue\n5. exit program\n\n");
    scanf("%d",&j);
    switch(j)
    {
        case 1:
            printf("\nEnter a number to be enqueued =>\t");
            current_node=create_node();
            fill_node(current_node);
            enqueue(current_node, &que);
            goto anchor;
        case 2:
            current_node = dequeue(&que);
            if(current_node)
            printf("The item %d dequeued successfully\n",current_node->item);
            goto anchor;
        case 3:
            view_queue(&que);
            goto anchor;
        case 4:
            printf("total items in the queue are %d\n",que.length);
            goto anchor;
        case 5:
            printf("Thank you\n");
            exit(0);
            goto anchor;
        default:
            printf("Invalid choice...!!!\n try choosing again\n\n");
            goto anchor;
    }
  
    return 0;
}

void enqueue(node *p,queue *q)                    //definition of enqueue function
{
    if(q->rear==NULL&&q->front==NULL)
    {
        q->rear=p;
        q->front=p;
    }
    else
    {
        q->rear->next=p;
        q->rear=p;
    }
    q->length++;
    printf("item %d enqueued successfully.\n",p->item);
}

node *dequeue(queue *q)                    //definition of dequeue function
{
    node *temp=NULL;
    if(q->rear==NULL&&q->front==NULL)        //this is the case when queue is empty
    {
        printf("queue is empty hence can not be dequeued\n");
        return temp;
    }
    else if(q->rear==q->front&&q->front!=NULL)    //this is the case when queue has only one node
    {
        temp=q->front;
        q->front=NULL;
        q->rear=NULL;
    }
    else
    {
        temp=q->front;
        q->front=q->front->next;
    }
    q->length--;
    return temp;
}

void view_queue(queue *q)
{
    node *temp_front;
    temp_front=q->front;
    if(q->length==0)
    {
        printf("\nThe queue is empty...!!!\n");
        return;
    }
    printf("The queue is\n");
    while(temp_front!=NULL)
    {
        printf("%d -> ",temp_front->item);
        temp_front=temp_front->next;
    }
    printf("\n");
    return;
}

node *create_node()                    //function to create a blank node
{
    node *temp;
    temp=(node*)malloc(sizeof(node));
    temp->next=NULL;
    return temp;
}

void fill_node(node *p)                    //function to fill a blank node with values taken from user
{
    int i;
    scanf("%d",&i);                    //this is the value taken from user
    p->item=i;
}

------------------------------------------------------