facebook like button

10 January, 2012

Returning a structure in C

The need:
     This program is basically solution of a problem I found on internet. Problem statement is:
There is a purse filled with some coins of gold, silver ans copper. A person draws coins one by one and notes down the type of coin each time. He writes g for gold, s for silver and c for copper coin. Thus a character string is formed. You have to write a function countCoins() which takes that string as parameter and returns count each type of coin. As we know that a function can return only single value, we have 2 options left to return all three counts with one function:
    1. store 3 answers in some contiguous location and return a pointer to that location.
    2. If possible, club all three variables to make a single variable and return that single variable. Yes it is possible, we can make a structure variable containing all three counts and return that structure variable.

The code:
----------------------------------------------------------
#include<stdio.h>
typedef struct
{
    int silver;
    int copper;
    int gold;
}CoinPurse;
CoinPurse countCoin(char *);

int main()
{
    int i;
    CoinPurse a,*b;
    char *coins="gscgcc";
    a=countCoin(coins);
    printf("Coppper coins are %d\n",a.copper);
    printf("Gold coins are %d\n",a.gold);
    printf("Silver coins are %d\n",a.silver);
    return 0;
}

CoinPurse countCoin(char *coins)
{
    CoinPurse x;
    x.copper=0;
    x.gold=0;
    x.silver=0;
    while(*coins)
    {
        switch(*coins)
        {
        case 'c':    x.copper++;
                    break;
        case 'g':    x.gold++;
                    break;
        case 's':    x.silver++;
                    break;
        default:    break;
        }
        coins++;
    }
    return x;
}
----------------------------------------------------------
Approach:
    The approach is very simple. The structure CoinPurse contains counter for each type of coin. the function countCoin() takes a character string , examines each character and based on that increments the correct counter. after the string is finished, the structure containing the counts is returned by the function countCoin(). In this program i have given the character string *coins as "gscgcc" soit is clear that there are 2 gold, 1 silver and 3 copper coins which can be verified by the program output.

08 January, 2012

Counting total number of nodes in a tree

The need:
     This program counts the total number of nodes in a binary tree and prints that for the user. This count is also known as tree size.
The code:
----------------------------------------------------------
#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);
int count_nodes(node *root);

int main()
{
 node *root=NULL;
 int i,x,max;
 printf("how many numbers do you want to enter in tree?\n");
 scanf("%d",&max);
 printf("Enter %d numbers \n",max);
 for(i=0;i<max;i++)
 {
  scanf("%d",&x);
  root = insert_node(root, x);
 }
 printf("all numbers inserted into the tree\t press enter to count");
 fflush(stdin);
 getchar();
 printf("\nThere are total %d nodes in this tree\n",count_nodes(root));
    return 0;
}

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

int count_nodes(node *root)
{
 if(!root)
 return 0;
 else
 return(count_nodes(root->left) + 1 + count_nodes(root->right));
}

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:     The approach is simple. We have to go by recursion. if the root is null(means there is no tree) then number of nodes are 0. Otherwise if root is not null(the tree exists), the total number of nodes will be
       (number of nodes in left subtree + number of nodes in right subtree + 1 ) 
Here recursive function count_nodes does the job very well.

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.