facebook like button

23 June, 2011

program 66: working with linked lists using user defined functions



The need:
     This program is the same previous program written using User Defined Functions (UDFs). This program takes some numbers from the user stores them in nodes (creates linked list) and prints back for the user in the same order. So this program teaches us creating and accessing linked lists.

The code:  
--------------------------------------------

#include<stdio.h>
#include<stdlib.h>
struct node1
{
 int data;
 struct node1 *next;
};
typedef struct node1 node; //defining a datatype node
void printlist(node *p); //udf to print list
void add_node(int a,node *p); //udf to add node to last of list
node *create_node(int); //udf to create a new node
int main()
{
 int i,j;
 node *head; //head will be first node of list
 head=NULL; //initialising head to null
 printf("Enter numbers to be stored. enter -999 to end.\n");
 while(i!=-999) //this while loop takes the numbers and creates list
 { //loop runs untill user enters -999
  scanf("%d",&i);
  if(head==NULL) //if i is first node
  head=create_node(i); //creates a new node and assigns its address to head
  else
  add_node(i,head);
 }
 printf("All the  numbers has been entered into linked list.\n");
 printf("press any key to view the list\n");
 fflush(stdin); //to flush previous undesired inputs from keyboard
 getchar(); //to give a pause to program untill user press any key
 printf("\nThe list is\n\n");
 printlist(head); //UDF to print the linked list
 printf("\n");
 return 0;
}

void printlist(node *p)
{
 node *temp=p;
 while(temp->next!=NULL) //this loop prints the list
 {
  printf("%d-->",temp->data); //printing current member
  temp=temp->next; //jumping to next member in the list
 }
  printf("END");
}

void add_node(int a,node *p)
{
 node *temp1,*temp2;
 temp2=p;
 /*the case when temp1 is not first node, we have a list of some members.
   Its kind of a line of persons in which a newcomer has to stand at the last
   so we have to go to last position starting from first*/
 temp1=create_node(a);
 while(temp2->next!=NULL) //checking if temp2 is last node
  temp2=temp2->next; //loop exits if temp2 is last node
 temp2->next=temp1; //temp1 is appended to the list after last node
}

node *create_node(int b)
{
 node *temp1;
 temp1=(node*)malloc(sizeof(node)); //allocation of a temporary node
 temp1->data=b; //filling data in node
 temp1->next=NULL; /*making pointer to next location NULL
 because there is no next location till now*/
 return temp1; //return 
}
--------------------------------------------  

The approach:  
The approach is very simple once you have read previous post. Everything has been written near statements as comments. Still this is a new topic so in case of any doubt please let me know. Now onward I'll use UDFs to do deal with linked lists.


17 June, 2011

program 65: using linked lists


The need:
     This program is written just to show the use of linked lists. This program takes some numbers from the user stores them in nodes (creates linked list) and prints back for the user in the same order. So this program teaches us creating and accessing linked lists.

The code:  
--------------------------------------------
#include<stdio.h>
#include<stdlib.h>
struct node1
{
    int data;
    struct node1 *next;
};
typedef struct node1 node; //defining a datatype node
int main()
{
    int i,j;
    node *head,*temp1,*temp2; //declaring 3 pointers of type node
    head=NULL; //initialising head to null
    printf("Enter numbers to be stored. enter -999 to end.\n");
    while(i!=-999) //this while loop takes the numbers and creates list
    {    //loop runs untill user enters -999
        scanf("%d",&i);
        temp1=(node*)malloc(sizeof(node)); //allocation of a temporary node
        temp1->data=i; //filling data in node
        temp1->next=NULL; /*making pointer to next location NULL
        because there is no next location till now*/
        if(head==NULL) //the case when temp1 is very first node
        {
            head=temp1; //so head will be containing the address of first node permanently
            temp2=head; //temp2 is temporarily given address of first node
        }
        else /*the case when temp1 is not first node, we have a list of some members.
        Its kind of a line of persons in which a newcomer has to stand at the last
         so we have to go to last position starting from first*/
        {
            while(temp2->next!=NULL) //checking if temp2 is last node
            temp2=temp2->next; //loop exits if temp2 is last node
            temp2->next=temp1; //temp1 is appended to the list after last node
        }
    }
    printf("All the  numbers has been entered into linked list.\n");
    printf("press any key to view the list\n");
    fflush(stdin); //to flush previous undesired inputs from keyboard
    getchar(); //to give a pause to program untill user press any key
    printf("\nThe list is\n\n");
    temp2=head;
    while(temp2->next!=NULL) //this loop prints the list
    {
        printf("%d-->",temp2->data); //printing current member
        temp2=temp2->next; //jumping to next member in the list
    }
    printf("\n");
    return 0;
}
 --------------------------------------------  

The approach:  
The approach is very simple once you have read previous post. Everything has been written near statements as comments. Still this is a new topic so in case of any doubt please let me know.

16 June, 2011

Concept of linked lists in C

     You have seen dynamic allocation of memory in C. But that was only introduction. How this is implemented in real life is shown in this post. Imagine the case of scanning some numbers and storing in memory. Now you know that there is something called dynamic memory allocation so you can use that instead of declaring a large array at the start of the program. You can think of scanning a number, then allocating memory for that number and then putting the number in the allocated memory space and repeating the same procedure for next numbers if needed. Your thinking is very good and apreciable but there is a problem that you can face. That is how you will keep track of each and every location allocated dynamically during the execution of the program.
     One solution which can come to your mind is just keep track of first location (just store it's address in a pointer variable) and store address of next location beside it. So this is the situaation in which you dont  This solution is also globally accepted. For this purpose you can create a derrived data-type which would contain a number (or may be more data depending on your need) and a pointer variable to hold the address of next location of data. This pointer is a link between the two nodes ( Each location can be said a node.) This is why these are called linked lists.
     To give you more clear idea of linked lists let me give an analogy. Lets compare arrays and linked lists. An array can be thought as a line of persons so any viewer can easily tell the location of any particular person in the line. He can also judge next person just by seeing the line and the current person because its very obvious. On the other hand linked lists can be think of a bunch of persons which are scattered here and there in a place and every person knows who is the person next to him. No outsider can say anything about their order. In the same way if you want to go to 3rd member of linked list then first of all go to first member take address of second from there, go to second take address of 3rd from there and then go to 3rd. Each time you have to start from first member and then proceed towards the desired member by going through intermediate members.

Remarks:
when you realize that you have got some command on linked list concepts after going through next 3-4 programs, you can have a look on program78 of this blog. This is a good program combining various operations on linked lists.

Data structures in C

You people have seen varius types of structure and derrived data types. You are also familiar to file handling, pointers and arrays. All these things are clearly visible in the source code of the program. There are certain more concepts which are called popular data-structures which are:
1. linked lists
2. queues
3. The stack
4. trees

   Now dont worry about these things. Just read its once and proceed. Concept of linked list has been explained in the next post.Queues, stack, and trees are just three different implementations of linked lists. Those will be explained later in subsequent posts. Just wait for it.

15 June, 2011

program 64: use of pointer as array



The need:
     This is a simple program to show that pointer is equivalent to a one dimensional array of same datatype and how a pointer variable can be used as an array.

The code:  
-------------------------------------------- 

#include<stdio.h>
#include<stdlib.h>
#define max 5
main()
{
  int i;
  int *p,*q;
  p=(int *)malloc(max * sizeof(int));
  q=p;
  printf("Enter %d integers\n",max);
  for(i=0;i<max;i++)
  {
   printf("Enter number %d =>\t",i);
   scanf("%d",p++);
  }
  printf("\nyou entered\n");
  for(i=0,p=q;i<max;i++)
  {
   printf("%d whose address is %d\n",*p,p);
   p++;
  }
  return 0;
}
--------------------------------------------  

The approach:  
This program takes 5 integers from user, store them in memory and prints back for user. This is a trivial task. Here I have shown how a pointer variable (in our case p) can be used  as an array of integers. This can be done for other data-types and even with derrived datatypes. First of all the pointer p is initialised and allocated sufficient memory (here using malloc function). After that five integers are scanned one by one and each time pointer p is incremented. In each increment p is automatically set to point to the next integer location in the memory. The initial value of p (starting location of array) is temporarily stored in other variable q. Which is later used to access the array to print it.

11 June, 2011

program 63: getting size of data-type in C

The need:
  This is a program just to show how sizeof() function can be used to determine memory space occupied by any variable or data-type.
The code:
--------------------------------------------
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct list
{
    char name[20];
    int age;
    float height;
};
typedef struct list person;
int main()
{
    person p;
    int i;
    char c;
    int size_of_person;
    size_of_person=sizeof(person);
    printf("memory occupied by person = %d bytes\n",size_of_person);
    printf("memory occupied by person = %d bytes\n",sizeof(person));
    printf("memory occupied by variable p = %d bytes\n\n",sizeof(p));
    printf("memory occupied by integer = %d bytes\n",sizeof(int));
    printf("memory occupied by variable i = %d bytes\n\n",sizeof(i));
    printf("memory occupied by character = %d bytes\n",sizeof(char));
    printf("memory occupied by vairable c = %d bytes\n\n",sizeof(c));
    return 0;
}
--------------------------------------------
The approach:
This program is one of the simplest programs which give intro of using sizeof function. First a user defined data-type person is defined. After that sizeof() function is used in different ways, how it can be directly used in printf statement and how it can return a value to an integer variable. Other than this there is nothing in the program.


07 June, 2011

Dynamic memory allocation

What is Dynamic memory allocation ???
     You may or may not have heard the term. Don't worry about this much. In programming jargon whenever the memory is allocated during execution of the program rather than compile time or load time of the program is termed as dynamic memory allocation. Now question comes in which cases memory is allocated at load time? Answer is till now upto previous post of this blog wherever memory was allocated, was allocated at load time.


Why dynamic memory allocation ???
     Suppose you have to make program to manipulate some data and which may be of long range. I mean sometimes the data to be stored can be of some units and sometimes it can be go up to millions. If the memory is allocated at load time, on each run of program we have to declare an array of size more than the maximum expected size of input data. Now suppose you have taken declared array of 10million locations and data in that program run is merely some units, this is absolute wastage of resources (available memory). To get rid of this problem dynamic memory allocation is used.


How?
    For this we have some built-in functions. There are three function to allocate memory dynamically.
1. malloc => allocates a block oh memory
2. calloc => allocates n blocks of memory
3. realloc => modifies a previous allocation of memory.
Out of all these malloc is most commonly used. I don't think I have ever used calloc or realloc unless it was asked to do so. So I'll elaborate only malloc rest you can find on google.


The malloc() function in C:
Like I have already said that malloc() is used to allocate a block of memory of specified size and type and returns its starting address to a pointer variable of same type. How this is done is shown in below given sample code.
int *p;
p=(int *)malloc(200);
This statement allocates a continuous block of 200bytes and returns a pointer to it to variable integer pointer variable p. This is also a way to initialise a pointer variable. If memory is not successfully allocated malloc function returns NULL to p.


Additional functions:
Some additional functions also should be known to us when we write programs using dynamic memory allocation.
1. free() => to free the memory allocated by previous allocation. The syntax is:
free(p);
this frees the memory occupied by p so that after the use of p operating system can use that space for some other purpose.


2. sizeof(): The sizeof() function in C returns the size of datatype passed to it in integer value which can also be assigned to a variable. The syntax is:
int size;
size=sizeof(float);
This assigns value 4 to variable size because float data-type takes 4 bytes in the memory. In this way this function can be used to find out which data-type takes how many bytes in memory whether it is built-in or user defined data-type.
    This also feciliate writing memory allocation statement because the programmer need not bother about the size of memory used. Say I want to allocate memory for 100 integers. I also want to tell you that in unix compilers int takes 2bytes while in C-free3.5 or higher it takes 4bytes. So the programmer who does not know this fact about C-free will make mistake of writing
p=(int *)malloc(200);
which will allocate 200bytes which is sufficient to hold only 50 integers instead of 100 in C-free. So he may face problem later in the program.
To do away with this blunder he can write the statement in the following way:
p=(int *)malloc(100*sizeof(int));
This first calculate size of an integer for that particular compiler then multiplies by 100 to get the appropriate value of apace and allocate that. 

06 June, 2011

program 62: group player by team (from file using command line arguments)

The need:

  This is a program to group a given number of players according to their teams. This is same as program59 of this blog. The only difference is: here input has been taken from the file and the concerned file name has been taken through command line arguments.

The code:

--------------------------------------------
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
    struct record
    {
        char name[20],team[10];
        float av;
    }pl[15];
 
int main(int argc,char *argv[])
{
    int i=0,j=0,k,count;
    char x[10],filename[20];
    FILE *fp;
    printf("total number of arguments given=%d\n",argc);
    printf("Executing program name is %s\n",argv[0]);
    strcpy(filename,argv[1]);
    if((fp = fopen(filename, "r"))==NULL)
    {
        printf("Cannot open file.\n");
        exit(1);
    }
    while(!feof(fp))
    {
        fscanf(fp,"%s",&pl[i].name);
        fscanf(fp,"%s",pl[i].team);
        fscanf(fp,"%f",&pl[i].av);
        i++;
    }
    count=i-1;
    for(i=0;i<count;i++)
    {
        if(strcmp(pl[i].team,"\0")!=0)
        {
            strcpy(x,pl[i].team);
            printf("\nplayers of team %s are =>\n",x);
            for(j=0;j<count;j++)
            {
                if(strcmp(x,pl[j].team)==0)
                {
                printf("name => %s\n",pl[j].name);
                printf("Average => %f\n",pl[j].av);
                for(k=0;k<10;k++)
                pl[j].team[k]='\0';
                }
            }
        }
    }
    fclose(fp);
    return 0;
}

--------------------------------------------
The approach: This program takes input from a file whose name is given through command line arguments. To know how command line arguments are used visit previous post. For other logic see  program59. command line to run this program will be:
  prog1.exe data.txt
 where data.txt can be downloaded from this link. In menu bar there select file-> download as -> text.

program 61: command line arguments demo

The code:
--------------------------------------------
#include<stdio.h>
int main(int argc,char *argv[])
{
    int i=0;
    printf("total number of arguments given=%d\n",argc);
    printf("Executing program name is %s\n",argv[0]);
    printf("Other arguments given are as under:\n\n");
    while(argv[i++])
    printf("%s\n",argv[i]);
    return 0;
}
--------------------------------------------
Understanding execution:
First compile the program. People who are using C-free or other compiler which does not asks command from user and directly runs the program with a single click should only compile the code with that compiler. In this way an .exe file will be created in the same directory. Now open command prompt and run program there. Steps for C-free are:
1. write the code and save it with any name say prog1.c.
2. Go to build menu and select compile or press f11.
3. Again go to build menu and select make or press Shift+f11.
4. Now see a prog1.exe file is created in the same directory.
5. Open command prompt program form "all programs->accessories->command prompt".
6. navigate to your program directory.
7. now run the command:
prog1.exe ranu pratap singh
and you are done with program.
The output:
total number of arguments given=4
Executing program name is temp.exe
Other arguments given are as under:

ranu
pratap
singh
(null)

Command line arguments

What is "command line argument"??
You have seen that any built-in or user defined function can take some arguments when it is called. main() can also take arguments without exception because it is a built-in function. Every function takes arguments when it is called (or before it starts running). You people also know that main() is the start point of the program. So by guessing you can say that main() should take argument even before the program starts to execute. Your thinking is correct. If you are using unix, ubuntu or any other compiler in which you have to write a command to compile and run your code, you can give arguments to main() while giving command to run the program. Ex. in unix based OS when you give ./a.out command after that arguments to main() can be given. These arguments are given in the command this is why these are called command line arguments. For all this the programmer also need to specify in the program that main() has to take arguments or not.
   main() can be declared to take 2 arguments first is an integer type and second is a array of character pointers. Usually first argument is named 'argc' abbreviation to 'argument counter' because this automatically inherits the value of number of arguments given. The second argument is usually written agrv probably abbreviation of 'argument variable' because this is the variable which takes the array of strings given as arguments after the file name (file name inclusive). After you give arguments to main(), these (argc and argv) can be used as normal variables in main() in the same way we gave arguments to other functions and used inside them.

In program code:
int main(argc, *argv[])
{
//program body
}


In ubuntu or or any other unix based system --
command to compile is same which is:
cc file1.c
After this a file named a.out is created in the same directory. To run that a.out file we used to write ./a.out now we'll write like this:
./a.out bla bla bla
where "bla bla bla" are command line arguments.

05 June, 2011

program 60: sample election program

The need:
  This program is a sample C program, PHP modification of which can be used in voting of any club or association. I wrote this program to be used in sangam election when I did not know php.
The code:
--------------------------------------------
//A program for voting

#include<stdio.h>
main()
{
    FILE *fp;
    char z;
    struct post
    {
        int cand1, cand2, cand3,none;
    }treas,sec,pres;
    printf("Election for SANGAM...\n");
    printf("press ^ for next vote and press @ to count and store results\n");
    pres.cand1=0;
    pres.cand2=0;
    pres.cand3=0;
    pres.none=0;
   
    treas.cand1=0;
    treas.cand2=0;
    treas.cand3=0;
    treas.none=0;
   
    sec.cand1=0;
    sec.cand2=0;
    sec.cand3=0;
    sec.none=0;
   
    for(z='t';z!='\0';)
    {
    printf("\n\nEnter choice for pres . \n1. cand1\n2. cand2\n3. cand3\n4. none\n\t\t");
   
    lebel_1:
    z=getchar();
    fflush(stdin);
    switch(z)
    {
    case '1' :
              pres.cand1++;
              break;
    case '2' :
              pres.cand2++;
              break;
    case '3' :
              pres.cand3++;
              break;
    case '4' :
              pres.none++;
              break;
    default :printf("Please enter a valid choice !!\n\t\t");
              goto lebel_1;
              break;
    }
   
   
    printf("\n\nEnter choice for sec . \n1. cand1\n2. cand2\n3. cand3\n4. none\n\t\t");
   
    lebel_2:
    z=getchar();
    fflush(stdin);
    switch(z)
    {
    case '1' :
              sec.cand1++;
              break;
    case '2' :
              sec.cand2++;
              break;
    case '3' :
              sec.cand3++;
              break;
    case '4' :
              sec.none++;
              break;
    default :printf("Please enter a valid choice !!\n\t\t");
                goto lebel_2;
              break;
    }
   
       
    printf("\n\nEnter choice for treasurer . \n1. cand1\n2. cand2\n3. cand3\n4. none\n\t\t");
   
    lebel_3:
    z=getchar();
    fflush(stdin);
    switch(z)
    {
    case '1' :
              treas.cand1++;
              break;
    case '2' :
              treas.cand2++;
              break;
    case '3' :
              treas.cand3++;
              break;
    case '4' :
              treas.none++;
              break;
    default :printf("Please enter a valid choice !!\n\t\t");
                goto lebel_3;
              break;
    }
   
    printf("Your vote is successful ! Thank You !\n");
   
    printf("\n\n\n\n\n\n\nNext Vote ? y/n\n");
    while(z!='\0')
    {
    z=getchar();
    fflush(stdin);
    if(z=='^'||z=='@')
    break;
    }
    if(z=='^')
    continue;
    if(z=='@')
    break;
       
    }
   
    fp=fopen("Results.txt","w");
    printf("\nVote results are .\n\n");
    printf("President .\n\ncand1=%d\ncand2=%d\ncand3=%d\nnone=%d\n
\n",pres.cand1,pres.cand2,pres.cand3,pres.none);
    fprintf(fp,"President .\n\ncand1=%d\ncand2=%d\ncand3=%d\nnone=%d\n
\n",pres.cand1,pres.cand2,pres.cand3,pres.none);
    printf("Secretory .\n\ncand1=%d\ncand2=%d\ncand3=%d\nnone=%d\n
\n",sec.cand1,sec.cand2,sec.cand3,sec.none);
    fprintf(fp,"Secretory .\n\ncand1=%d\ncand2=%d\ncand3=%d\nnone=%d\n
\n",sec.cand1,sec.cand2,sec.cand3,sec.none);
    printf("Treasurer .\n\ncand1=%d\ncand2=%d\ncand3=%d\nnone=%d\n
\n",treas.cand1,treas.cand2,treas.cand3,treas.none);
    fprintf(fp,"Treasurer .\n\ncand1=%d\ncand2=%d\ncand3=%d\nnone=%d\n
\n",treas.cand1,treas.cand2,treas.cand3,treas.none);
    fclose(fp);
}
--------------------------------------------

The approach:
    The description of the problem is following. There are 3 posts (secretory, president and treasurer) and 3 candidates for each post. A person can either vote for a single person or choose none for a particular post. The approach to program is simple. We can have structures for each post. In each structure there will be counters for each candidate and none. The program pauses to take some input after a person is done with voting. Now if authorized person gives ^ as input, the program gets ready for next vote else if @ is entered the program prints results on screen, stores the results in a file "results.txt" and exits.

Remarks:
1. This program was not submitted there because I came to know that php programs were better for voting for some reasons.

program 59: sort players grouped by teams

The need:
  This is a program to group a given number of players according to their teams. This program was given to me as assignment in lab.
The code:
--------------------------------------------
#include<stdio.h>
#include<string.h>
#define max 3
main()
{
    struct record
    {
        char name[20],team[10];
        float av;
    }pl[max];
   
    char x[10];
    int i,j=0,k;
    for(i=1;i<=max;i++)
    {
        printf("Enter player name .");
        gets(pl[i].name);
        printf("Enter team name .");
        gets(pl[i].team);
        printf("Enter player average .");
        scanf("%f",&pl[i].av);
        fflush(stdin);
    }
    for(i=1;i<=max;i++)
    {
        if(strcmp(pl[i].team,"\0")!=0)
        {
            strcpy(x,pl[i].team);
            printf("\nplayers of team %s are =>\n",x);
            for(j=1;j<=max;j++)
            {
                if(strcmp(x,pl[j].team)==0)
                {
                printf("name => %s\n",pl[j].name);
                printf("Average => %f\n",pl[j].av);
                for(k=0;k<10;k++)
                pl[j].team[k]='\0';
                }
            }
        }
    }
}
--------------------------------------------
Logic: The logic is very simple once you have decided to go with the use of structure and have defined the correct structure. The idea is to take each player data in a structure and after that comparing team of each structure.
Remarks:
1. Usually taking data of all players by user is not feasible if the count of players is more. In that case player data can be taken from a file. How this is done will be shown in next posts.

program 58: calculate total salary from basic


The need:
    This is a simple program to calculate total salary from basic. This program was given to me as assignment in lab.
The code:
--------------------------------------------
#include<stdio.h>
float total_sal(float );
main()
{
     int i,k;
     char z;
     struct employee
     {
            char name[30],ID[15],Dep[40];
            float basic,DA,HRA,total_salary;
     } emp[10];
     printf("Enter the number of employees you want to calculate data for..");
     scanf("%d",&k);
     for(i=0;i",i+1);
          gets (emp[i].name);
          printf("Enter ID of employee%d\t=>",i+1);
          gets (emp[i].ID);
          printf("Enter Department of employee%d\t=>",i+1);
          gets (emp[i].Dep);
          printf("Enter Basic-Salary of employee%d\t=>",i+1);
          scanf("%f",&emp[i].basic);
          emp[i].DA=0.4*emp[i].basic;
          emp[i].HRA=0.25*emp[i].basic;
          emp[i].total_salary=total_sal(emp[i].basic);
     }
     for(i=0;i ");
          puts (emp[i].name);
          printf("ID\t\t => ");
          puts (emp[i].ID);
          printf("Department\t => ");
          puts (emp[i].Dep);
          printf("BASIC\t\t => %.2f\n",emp[i].basic);
          printf("DA\t\t => ");
          printf("%.2f",emp[i].DA);
          printf("\nHRA\t\t => ");
          printf("%.2f",emp[i].HRA);
          printf("\nTotal Salary\t => ");
          printf("%.2f\n",emp[i].total_salary);
     }
}

float total_sal(float bs)
{
     float da=0.4*bs;
     float hra=0.25*bs;
     float total=bs+da+hra;
     return(total);
}
--------------------------------------------


Remarks:

1. This is only a sample program. There may be other allowances and benefits associated depending upon the employee of different types.


04 June, 2011

program 57: reading a file in reverse order in C

The need:
    This is a simple program to show functions to traverse through a file. This program shows how ftell() and fseek() functions are used to move file pointer through a file. this program first takes some text input from user and prints to a file. Then the program tells the position of each character in the file and prints the file contents in reverse order on the terminal.

The code:
-------------------------------------------- 
#include<stdio.h>
main()
{
    FILE *fp;
    int i,j;
    char c;
    fp=fopen("RANDOM.txt","w");
    printf("Enter the file contents to write to.\n");
    while((c=getchar())!='\n')
    putc(c,fp);
    j =ftell(fp);
    printf("Number of characters entered = %d\n", j);
    fclose(fp);
    i=0;
    fp=fopen("RANDOM.txt","r");
    while(feof(fp)==0)
    {
        fseek(fp,i,0);
        if((c=getc(fp))!=EOF)
        printf("position of %c is %d\n",c,ftell(fp));
        i++;
    }
    printf("\nReversrd order.\n");
    fseek(fp,-1,1);
    do
        {
        printf("%c",getc(fp));
        }
    while((fseek(fp,-2,1))==0);
    putchar('\n');
    fclose(fp);
}

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

The approach:
    First run the program after that try to understand the code. This program is intended to illustrate the use of feof(), fseek() and ftell() functions. feof() returns 0 if end of file has not reached else return non-zero. The function fseek() introduced in post59 is illustrated here. The function ftell() returns the relative position of a file pointer from the beginning of the file. Taking text and printing that to file is trivial. getchar() takes a character from the user and putc() can write a character to the file. For printing the file in reverse order first we move our file pointer to last printable character ( because the last character of every file is EOF by default which is neither printable nor do we want it to be printed.)
    One important point which I skipped in previous posts is: "the file pointer is automatically incremented accordingly as it goes on reading data. For example the file pointer is automatically incremented by one if a character is read from the file." So each time we print a character the pointer points to the character next to it. So to print a file in reverse order we start scanning from last printable character and each time go 2 character back to scan character left to just scanned character.


Remarks:

1. This program is inspired from the example 12.5 of the book "Let us C" by Balagurusamy.

program 56: sorting odd and even

The need:
    This is a simple program to show some more functions to access a file. This program shows how getw() and putw() functions can be used to get and print integers to and from a file respectively.

The code:
-------------------------------------------- 
#include<stdio.h>
#include<stdlib.h>
main()
{
    FILE *f1,*f2,*f3;
    int i,j=0;
    f1=fopen("Numbers.txt","w");
    printf("Enter some integers. Enter -1 to end.\n");
    while(j<20)
    {
        scanf("%d",&i);
        j++;
        if(i==-1)
        break;
        putw(i,f1);           
    }
    fclose(f1);   
    f1=fopen("Numbers.txt","r");
    f2=fopen("Odd.txt","w");
    f3=fopen("Even.txt","w");
    while((i=getw(f1))!=EOF)
    {
        if(i%2==0)
        putw(i,f3);                   
        else
        putw(i,f2);                   
    }
    fclose(f1);
    fclose(f2);
    fclose(f3);
    f1=fopen("Numbers.txt","r");
    f2=fopen("Odd.txt","r");
    f3=fopen("Even.txt","r");
    printf("content of file Number");
    while((i=getw(f1))!=EOF)
        printf("%4d",i);
    printf("\n\ncontent of file Odd");
    while((i=getw(f2))!=EOF)
        printf("%4d",i);
    printf("\n\ncontent of file Even");
    while((i=getw(f3))!=EOF)
        printf("%4d",i);
        printf("\n\n");
    fclose(f1);
    fclose(f2);
    fclose(f3);
}
--------------------------------------------

The approach:
    First the program asks user to input some integers (max 20) and takes until user enters -1 or 20 numbers are entered. These numbers are then written to a file called numbers.txt which was opened in write mode. After that the numbers.txt is closed. Again numbers.txt is opened in read mode and each number is scanned from file. Meanwhile files odd.txt and even.txt are opened in write mode and each number which was scanned from numbers.txt is checked for odd and even (if condition does the task) and put in the corresponding file.



Remarks:

1. All of you will get correct output on the terminal but some of you may not be able to see the correct content in files created. getw() and putw() sometime face this problem due to different encoding of characters.

program 55: reading a file in C

The need:
 In previous post we wrote some data to a file. This program will read that data and print on the output screen. So this program is only a rehearsal of reading a file during more complex programs.

The code:
-------------------------------------------- 
#include<stdio.h>
#include<stdlib.h>
#define ITEMS 1
main()
{
    FILE *fp;
    int number,quantity,i;
    float price, value;
    char item[10],filename[20];
    printf("Enter file name in which you have your data. => ");
    gets(filename);
    fp=fopen(filename,"r");
    if(!fp)
    {
        printf("No such file found. Exiting..\n");
        exit(0);
    }
    printf("Item_name\tnumber\tprice\t      quantity\tvalue\n");
    for(i=0;i<ITEMS;i++)
    {
        fscanf(fp,"%s %d %f %d",item,&number,&price,&quantity);
        value=price*quantity;
        fprintf(stdout,"%-15s\t%-5d\t%-10.2f\t%-5d\t%-10.2f\n",item,number,price,quantity,value);
    }
    fclose(fp);
    printf("\n");
}
--------------------------------------------

Remarks:

1. This program first asks user to give a file name in which the data was previously stored then opens the file with given file name in read mode. Note that when a file is opened in read mode, the file pointer fp gets pointer to first character of file if the file is existing otherwise NULL is assigned to fp.
2. If program tries to access location pointed by variable having value NULL, UNIX gives segmentation fault and in WINDOWS the program stops working. To avoid these situations I have checked the value of fp and if it is found NULL (means the file was not opened successfully) the program exits.
3. After passing the test of if statement the program reads the data from the file. fscanf() is the function used to do this. This function works in exact same manner as scanf() but takes an extra argument file pointer so that it can recognize the file from which the data is to be read.
4. After the data is read from the file in suitable variable, it can be used in whatever way we want.
5. The program calculates the cost of purchase by multiplying quantity and price of one item and assigns to variable named value.
6. Now all the previous data with one extra column (value) is printed on the screen.

program 54: writing to a file in C

The need:
 In previous post I talked of file handling. Reading and writing both are important operations on a file. This program will take some content from user and store that in a file. So this program is only a rehearsal of writing a file during more complex programs.

The code:
-------------------------------------------- 
#include<stdio.h>
#include<stdlib.h>
#define ITEMS 1
main()
{
    FILE *fp;
    int number,quantity,i;
    float price, value;
    char item[10],filename[20];
    printf("Enter file name in which you want to save your data. => ");
    gets(filename);
    fp=fopen(filename,"w");   //opening file
    printf("Input file data.\n");
    for(i=0;i<ITEMS;i++)
    {
        printf("Item_name =>\t");
        scanf("%s",item);
        printf("number =>\t");
        scanf("%d",&number);
        printf("price =>\t");
        scanf("%f",&price);
        printf("quantity =>\t");
        scanf("%d",&quantity);
        fflush(stdin);
        fprintf(fp,"%s %d %f %d\n",item,number,price,quantity);
    }
    fprintf(stdout,"\nAll data has been entered in file %s\n",filename);
    fclose(fp);
}
--------------------------------------------

Remarks:

1. This program first opens a file with given file name in write mode. Note that when a file is opened in write mode, the previous file with same name is overwritten is existed otherwise a new file is created.
2. ITEM is defined as 1 so the program takes data for only one item.
3. Data about the item is taken from the user by 4 scan operations.
4. After that the data is written on the file. fprintf() is the function used to do this. This function works in exact same manner as printf() but takes an extra argument file pointer so that it can recognize the file in which the data is to be written.
5. The second last statement is a replacement simple printf() statement (recall stdout is default file pointer to output window).
6. Last statement closes the file.
7. After the program terminates we can see the output file in the same folder in which the program was build and run. We can see the contents of file by opening it with notepad (in windows) or gedit (in unix based OS).

03 June, 2011

FILE HANDLING in C (pointers to files)

The need: 
      You people have made a lot of programs till now. You have taken inputs, printed outputs through your programs. Did you ever think what happens to your inputs and outputs when the program terminates and you close the terminal (program window). All those variables, values are lost somewhere in the memory. Now suppose you have to make an inventory program, a catalog or something else which required permanent storage, how you can do that ? The idea is simple we can store the values somewhere else where they can be found later even after the program is terminated. Files are such locations. We have methods by which we can write necessary data into a file and can read back from file. This is a whole branch of C called FILE HANDLING in C. 
   Some points about file handling:
1.  We use a pointer variable to point to a file. This variable is of type FILE and is technically called "file pointer". Ex.
FILE *fp;     //declaration of a file pointer fp
2.  Common sense says that to work with files we need to do some operations which are following: read, write, append, create and delete.
3.  For read, write or append operation to a file first we have to open that file. This is done in the following manner.
fp=fopen(filename,"r");     //using fp to open a file
Here fopen is a built-in function which takes 2 arguments. This function opens a file whose name is stored in a string variable filename and returns a pointer value to fp. The name of file can also be directly given but in that case name should be enclosed in double quotes. The second argument to this function is mode of opening the file. Here r in double quotes implies that the file is opened only for reading.
We have three modes:
    a. read --- "r"
    b. write --- "w"
    c. append --- "a" 
We can also open a file in more than one mode.
4.  When program reads a file it may or may not read sequentially depending on the need. If it does not read sequentially, it will require jumps (file pointer has to seek through file for that). We have built-in function fseek for this purpose . The syntax is:
fseek(fp,2,1);    //to jump 2 characters ahead in file from the current position
This fseek function takes 3 arguments. First is file pointer of concerned file, second is number of characters to jump (+ve for going ahead -ve for going back) and third is the reference position( 0 for start, 1 for current, 2 for end).
5.  For all these built-in functions header file <stdlib.h> should be included.
6. The most important point is introduction of the character EOF. As the character NULL signifies the end of a string, the character EOF signifies the end of the file. This non-printable character is by default added at the end each file.
    More points will be added as more programs are added in upcoming posts.

Remarks:


You may skip remark below for now if it seems confusing to you.
    One question can arise here which is: "where does file pointer point?"
Answer to this question you may not be able to find on internet or may be you can find. But my observation says that file pointer points to some location in the memory and that memory location holds the record of current position of cursor(actually I should say imaginary cursor because there is no cursor visible). This can be verified with following code...

----------------------------------------------
#include<stdio.h>
#include<stdlib.h>
main()
{
    FILE *fp;
    char c;
    fp=fopen("check.txt","r");
    printf("fp is %d\t *fp is %d\n",fp,*fp);
    c=getc(fp);
    printf("fp is %d\t *fp is %d\n",fp,*fp);
    c=getc(fp);
    printf("fp is %d\t *fp is %d\n",fp,*fp);
    c=getc(fp);
    printf("fp is %d\t *fp is %d\n",fp,*fp);
    c=getc(fp);
    printf("fp is %d\t *fp is %d\n",fp,*fp);
}

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

when you run the above code make sure that you have a test file check.txt in the same folder in which above code resides.

program 53: center of mass of a triangle (user defined function)

The need: 
      This is a program to calculate the center of mass of a triangle. This is same previous program with only difference of user defined function. This program shows how a structure can be returned by a function by using pointers.

The code: 
--------------------------------------------
#include<stdio.h>
struct p       //defining structure p
{
    float x;
    float y;
};
typedef struct p point;       //defining data-type point
point * com_tri(point a,point b,point c);
main()
{
    int i;
    point p1,p2,p3;      //declaration of point variables
    point *com;         //declaration of pointer com of type point
    printf("program to find Center of Mass of a triangle.\n");
    printf("Enter vertices => \n");
    printf("x1 => \t");
    scanf("%f",&p1.x);
    printf("y1 => \t");
    scanf("%f",&p1.y);
    printf("x2 => \t");
    scanf("%f",&p2.x);
    printf("y2 => \t");
    scanf("%f",&p2.y);
    printf("x3 => \t");
    scanf("%f",&p3.x);
    printf("y3 => \t");
    scanf("%f",&p3.y);
    com=com_tri(p1,p2,p3);
    printf("\nCOM is (%.2f,%.2f) .\n",com->x,com->y);
}
point * com_tri(point a,point b,point c)
{
    point temp_com;
    temp_com.x=(a.x+b.x+c.x)/3;
    temp_com.y=(a.y+b.y+c.y)/3;
    return(&temp_com);        //address of temp_com is returned
}
--------------------------------------------

The approach: 
First of all copy, paste, compile and run the program. This is a simple program just to show how pointers can be used to return a struct data-type (in our case point is derived data-type which consist of two floats). Here com_tri is a function which is defined to take 3 arguments of type point and return a pointer of type point. If you see the definition of function, you'll see that the function declares a point variable in which the calculated values of COM is stored. This variable is stored somewhere in the memory. In the end program returns the address of variable this variable. When in main program this function is called, this returns that address to a pointer variable com. Now there is one noticeable point here. Which is accessing of individual components of pointer variable com. When we access individual components of a structure from its pointer, we use an arrow (->) as separator in place of a dot (.).

02 June, 2011

program 52: center of mass of a triangle (use of typedef)

The need: 
      This is a program to calculate the center of mass of a triangle. Finding COM is a trivial problem but the program is not trivial because this is the program which tells you how you can define your own data-type in C.

The code: 
--------------------------------------------
#include<stdio.h>
struct p       //defining structure p
{
    float x;
    float y;
};
typedef struct p point;       //defining data-type point

main()
{
    int i;
    point p1,p2,p3,com;      //declaration of point variables
    printf("program to find Center of Mass of a triangle.\n");
    printf("Enter vertices => \n");
    printf("x1 => \t");
    scanf("%f",&p1.x);
    printf("y1 => \t");
    scanf("%f",&p1.y);
    printf("x2 => \t");
    scanf("%f",&p2.x);
    printf("y2 => \t");
    scanf("%f",&p2.y);
    printf("x3 => \t");
    scanf("%f",&p3.x);
    printf("y3 => \t");
    scanf("%f",&p3.y);
    com.x=(p1.x+p2.x+p3.x)/3;
    com.y=(p1.y+p2.y+p3.y)/3;
    printf("\nCOM is (%.2f,%.2f) .\n",com.x,com.y);
}
--------------------------------------------

The approach: 
First of all copy, paste, compile and run the program. This is a simple program just to show how structures can be used to define a new derived data-type (in our case point is derived data-type which consist of two floats). After data-type point is defined, it can be used to declare  variables in the same way as built-in data-types are used. Else the logic is simpler. You people already know the formula of center of mass of a triangle. Only thing done here is to take input, use the formula to calculate output and print back for user.