Chapter 10 - String Handling

I. Fill in the blanks

  1. strcmp
  2. 2 bytes one for A and other one for null character.
  3. Because scanf() takes whitespace character as end of input for a field.
  4. Return value will be greater than 0 as first string is bigger than second string.
  5. printf("%s",name) will display the value of name and puts(name) will display name followed by new line.

II. Write programs

  1. Accept a string and display string in uppercase without using functions in string.h.
    
    main()
    {
       char st[20];
       int i;
    
         /* accept a string */
         printf("Enter a string : ");
         gets(st);
    
         /* display it in upper case */
         for ( i = 0 ; st[i] != '\0';  i++)
    	  if ( st[i] >= 'a'  &&  st[i] <= 'z' )
    	       putch( st[i] - 32);
    	  else
    	       putch( st[i]);
    }
    
    
  2. Accept a string and display it in reverse without using string.h.
    main()
    {
       char st[20];
       int i;
    
         /* accept a string */
         printf("Enter a string : ");
         gets(st);
    
         /* get length of the string */
         for ( i = 0 ; st[i] != '\0';  i++) ;
    
    
         /* display it in reverse order */
        
         for ( i -- ; i >= 0 ; i --)
                putch(st[i]);
    
    }
    
    
  3. Accept a string and a character. And display how many times that character occurs in string.
    
    #include <stdio.h>
    
    main()
    {
       char st[20];
       int i, count = 0;
       char ch;
    
         /* accept a string */
         printf("Enter a string : ");
         gets(st);
    
    
         /* accept character */
         printf("Enter a character : ");
         ch = getchar();
    
         /* count */
         for ( i = 0 ; st[i] != '\0';  i++)
    	  if ( st[i] >== ch)
                  count ++;
    
         printf("No. of words : %d ", count);
    
    }
    
    
  4. Take a sentence and display the number of words in it. You can assume that words are separated by only one space. Try to do this without this assumption also.
    #include <stdio.h>
    
    main()
    {
       char st[20];
       int i,count =0;
    
    
         /* accept a string */
         printf("Enter a string : ");
         gets(st);
    
    
         /* count words  */
    
         for ( i = 0 ; st[i] != '\0';  i++)
    	  if ( st[i] == ' ' )
    		count ++;
    
         printf(" No. of words :  %d", count + 1);
    
    }
    
  5. Take a string, source character and target character. Replace every occurrence of source character with target character.
    #include <stdio.h>
    
    main()
    {
       char st[20];
       int i;
       char sch,tch;
    
    
         /* accept a string */
         printf("Enter a string : ");
         gets(st);
    
         /* accept source and target character */
         printf("Enter source character : ");
         sch = getchar();
    
         fflush(stdin); /* remove characters from keyboard buffer */
    
         printf("Enter target character : ");
         tch = getchar();
    
    
         /* display it in upper order */
         for ( i = 0 ; st[i] != '\0';  i++)
    	  if ( st[i] == sch)
    		st[i] = tch;
    
         printf(" String after conversion : %s ", st);
    }
    
    
  6. Accept 10 strings and display the biggest of 10 strings.
    
    main()
    {
       char  st[10][20];
       int i, hpos=0;
    
    
          /* take strings */
          for (i = 0 ; i < 10 ; i ++)
          {
    	  printf("Enter a string :");
    	  gets( st[i]);
    
    	  if  ( strcmp(st[i],st[hpos]) > 0 )
    	       hpos = i;
    
          }
    
          printf(" %s is the biggest string",  st[hpos]);
    }
    

Chapter 11 - User-defined Functions

I. Fill in the blanks

  1. only one
  2. return
  3. int
  4. Function declaration is optional
  5. Function declaration should be given first and then function definition.
  6. It is called as recursion
  7. User-defined function can have any name whereas main is predefined name. Function main() is the first fuction to be automatically called whereas user-defined function is to explicitly called.

II. Write Functions

  1. Write a function that takes a number as parameter and returns the next odd number.
    int  nextodd(int num)
    {
       if ( num % 2 == 0 )
           return  num + 1;
       else
           return  num + 2;
    }
    
    
  2. Write a function to take a string as parameter and display it in lowercase.
    void  lowerstring( char st[100])
    {
      int i;
    
        for ( i = 0 ; st[i] != '\0'; i ++)
             putch( tolower( st[i]));
    
    }
    
  3. Write a function to take a number and return 1 if it is a prime number otherwise 0.
    int  prime(int num)
    {
       int i;
    
          for ( i = 0 ; i <= num/2 ; i ++)
            if ( num % i == 0 )   /* not a prime number */
                 return 0;
    
          /* if control comes here, it means prime number */
    
          return 1;
    }
    
  4. Write a function to take a string and return the number of digits the string contains.
    int  nodigits( char st[100])
    {
      int count = 0, i;
    
          for ( i = 0 ; st[i] != '\0'; i ++)
               if (  isdigit (st[i]) )
                        count ++;
    
          return count;
    }
    
    
  5. Write a function to take a number and return factorial of the given number. Use recursion.
    main()
    {
        printf(" Fact : %d ", fact(4));
    }
    
    int fact(int n)
    {
       if ( n > 1 )
           return ( n * fact( n-1));
       else
           return 1;
    }
    
    

Chapter 12 - Storage Classes

I. Fill in the blanks

  1. static
  2. scope
  3. extern
  4. static
  5. By declaring another variable in a block with the same name as the one to be hidden.
    fun()
    {
      int i;
       
         if (   )
         {
           int i;  /* outer i is hidden here */
    
         }
    }
    
    
  6. Yes

Chapter 13 - Pointers

I. Fill in the blanks

  1. &
  2. *
  3. 2 bytes.
  4. A pointer

II. Write programs

  1. Declare two int variables , take values into them and display the values and addresses of those variables.
    main()
    {
      int n1,n2;
    
        printf("Enter two values : ");
        scanf("%d%d", &n1,&n2);
    
        printf("Values %d %d ", n1,n2);
        printf("\n Addresses %p %p", &n1,&n2);
    }
    
  2. Write a function that takes 2 numbers and sets both of them to the smallest of two. Use pass by reference.
    
    void settosmall(int  * n1, int * n2)
    {
    
        if ( *n1 < *n2 )
             *n2 = *n1;
        else
             *n1 = * n2;
    }
    
    
  3. Write a function to take three numbers and return minimum and maximum values. Use pass by reference.
    
    void smallbig(int n1,int n2, int n3,int * big, int * small)
    {
    
        /* get biggest */
    
        *big = n2 > n1 ? n2 : n1;
    
        *big = n3 > *big ? n3 : *big;
    
    
        /* get samllest */
    
        *samll = n2 < n1 ? n2 : n1;
    
        *samll = n3 <  *samll ? n3 : *small;
    
    }
    
    main()
    {
     int n1, n2, n3, small, big;
    
      
            smallbig(n1,n2,n3, &big, &small);
    
    }
     
    
  4. Write a function to take an array and return smallest and largest values of the array. Use pass by reference.
    
    void smallbig(int * ar,int * big, int * small)
    {
     int i;
    
       *big = *small = ar[0];
    
       for( i = 1 ; i < 10 ; i ++)
       {
            if ( ar[i] > * big )
                 *big = ar[i];
               
            if ( ar[i]  < *small)
                 *small = ar[i];
    }
    
    
  5. Write a function to take an array of 10 integers and set all of them to 0. Use pass by reference
    
    void settozeroes(int * ar)
    {
     int i;
    
    
       for( i = 0	 ; i < 10 ; i ++)
       {
             ar[i] = 0;
       }
    
    }
    
    

Chapter 14 - Pointer vs. Array

Write programs

  1. Take an array of 20 elements and make a pointer pointing to it. Then display the array in reverse order using array notation, pointer with pointer notation, array with pointer notation.
    #include <stdlib.h>
    
    main()
    {
       int a[20];
       int  * p;
       int i;
    
         clrscr();
    
         /* fill array here */
         for ( i = 0 ; i < 20 ; i ++)
    	 a[i] = random(100);
    
    
         /* display using in reverse order using array notaion */
    
         for ( i = 19 ; i >= 0 ; i --)
           printf("%d ", a[i]);
    
         printf("\n Pointer \n");
    
         /* display using in reverse order using pointer notaion */
    
         p = &a[19];  /* make pointer pointing to 20th element */
    
         for ( i = 19 ; i >= 0 ; i --, p-- )
    	    printf("%d ", *p);
    
         printf("\n Array pointer \n");
         /* display using in reverse order using pointer notaion using array */
    
         for ( i = 19 ; i >= 0 ; i -- )
           printf("%d ", *(a+i));
    
    }     
    
  2. Write a function that takes an array and number of elements as parameters and sorts the array in the ascending order.
    
    void sortarray( int * ar, int nel)
    {
     int i,j;
    
         /* sort array in descending order */
    
          for ( i = 0 ; i < nel - 1 ; i++)
          {
               for ( j = i+1; j < nel ; j +=)
               {
                 if ( ar[j] > ar[i])
                 {
                    /* interchange */
    
                    temp  = ar[j];
                    ar[j] = ar[i];
                    ar[i] = temp;
                 }
    
               } /* end of  j loop */
    
           } /* end of i loop */
    
    
    }
    
    main()
    {
       int ar[10]; 
       int i, j, temp;
    
          for (i = 0 ; i < 10 ; i++)
          {
             printf("Enter number for [%d] element : ",i);
             scanf("%d", &ar[i]);
          }
    
          sortarray(ar,10);
    
           /* display sorted array */
     
          for ( i = 0 ; i < 10 ; i++)
          {
             printf("%d\n", ar[i]);
          }    
    
    }
    
  3. Write a function that takes a pointer to an integer and two arrays of 10 elements each. Make the pointer pointing to the array whose sum of elements is the largest.
    
    void bigarray( int * a1, int * a2, int ** p)
    {
     int i,sum1,sum2;
    
    
          sum1  = 0;
    
          for ( i = 0 ; i < 10 ; i++)
          {
            sum1 += a1[i];
    
          } /* end of i loop */
    
    
    
          sum2  = 0;
    
          for ( i = 0 ; i < 10 ; i++)
          {
            sum2 += a2[i];
    
          } /* end of i loop */
    
          if ( sum1 > sum2 )
               *p = a1;
          else
               *p = a2;
    
    }
    
    main()
    {
      int a1[]= { 110,20,30,40,50,30,30,30,2,22};
      int a2[]= {21,20,30,40,60,29,39,28,24,1};
    
      int *p;
      int i;
    
          clrscr();
    
          /* pass address of pointer as pointer is to be modified */
    
          bigarray(a1,a2,&p);
    
          /* display the big array */
          for ( i = 0 ; i < 5 ; i ++)
    	  printf("%d ", p[i]);
    }
    
    
    
  4. Take month number from user and display the name of the month. Use an array of strings, which contains the names of all months.
    main()
    {
       int mn;
    
       char * months[] = {"January",  "Feburary", "March",    "April",
    		      "May",      "June",     "July",     "August",
    		      "September","October",  "November", "December"};
    
    
       printf("Enter month number :");
       scanf("%d",&mn);
    
    
       printf(" Month name : %s", months[ mn - 1]);
    }
    
    

Chapter 15 - Structures

Write programs

  1. Take details of 10 students ( student number, name, total marks) and display details in ascending order of total marks.
    
    #include <stdio.h>
    
    struct student
    {
       int no; 
       char name[30];
       int tm;
    };
    
    main()
    {
    
      struct student  s[10], temp;
      int i,j;
      
      
         for ( i = 0 ; i < 10 ; i ++)
         {
            
            printf("Enter student number : ");
            scanf("%d", & s[i].no);
    
            fflush(stdin);
    
            printf("Enter student name   : ");
            gets( s[i].name);
    
            printf("Enter total marks    : ");
            scanf("%d",& s[i].tm);
        }
    
        /* sort the array */
    
        for ( i = 0 ; i < 9 ; i ++)
          for ( j = i + 1 ; j < 10 ; j ++)
    
               if ( s[i].tm > s[j].tm)
               {
                    temp = s[i];
    	        s[i] = s[j];
    	        s[j] = temp;
               }
    
    
        /* display sorted details */
    
         clrscr();
    
         for ( i = 0 ; i < 10 ; i ++)
         {
            
            printf("\n %5d %-20s %5d", s[i].no, s[i].name, s[i].tm);
              
         }
    
    } /* end of main*/
    
    
  2. Write a program to take 10 times ( HH:MM:SS) and display the smallest time. Allow user to enter time in HH:MM:SS format. Hint: Use %d:%d:%d with scanf().
    struct time
    {
        int h,m,s;
    };
    
    
    /* returns > 0 if t1 > t2
       < 0  if t1 < t2
       0  if t1 == t2 
    */
    
    int compare(struct time t1, struct time t2)
    {
        return   (t1.h * 60 * 60 + t1.m * 60 + t1.s) - (t2.h * 60 * 60 + t2.m * 60 + t2.s);
    
    }
    
    main()
    {
      struct time t[10], st;
      int i;
    
    
         /* accept 10 times */
    
         for ( i = 0 ; i < 10 ; i ++)
         {
            printf("Enter time in hh:mm:ss format :");
            scanf("%d:%d:%d", & t[i].h, &t[i].m, &t[i].s);
         }
    
         /* get the smallest time */
    
         st = t[0];
    
         for ( i = 1;  i < 10 ; i ++)
         {
               if ( compare( t[i], st ) < 0 )  /* if time is less than smallest time */
                     st = t [i];
         }
    
         printf("Smallest Time : %d:%d:%d", st.h, st.m, st.s);
    
    
    }
    
         
    
  3. Write a function to take a parameter of struct time and return the next second of the given time. Return value is also a struct time.
    
    struct time
    {
      int h,m,s;
    };
    
    struct time  nextsecond(struct time t)
    {
        t.s ++; /* increment seconds */
    
        if ( t.s > 59 )
        {
            t.s = 0;
            t.m ++;
        
            if ( t.m > 59 )
            {
               t.m = 0;
               t.h ++;
                
               if ( t.h > 23 )
                     t.h = 0;
            }  
        }
    
        return t;
    }
    
    
  4. What is the difference between *p.x and (*p).x assuming p is declared as struct point *, and x as a member of struct point. *p.x is taken as *(p.x). That means p.x is taken first and then indirection operator is used.
    (*p).x is to treat p as pointer and member x of the structure pointed by p is taken.

    You must use paraentheses to evaluate the expression correctly as . (member operator) has higher precedence than * (indirection operator).

  5. What is the difference between structure declaration and structure variable declaration?.

    In Structure declaration only members of the structure are declared. No space is allocated to member.

    In Structure variable declaration, we declare a variable of the structure and that variable is allocated memory.

Chapter 16 - Union,typedef and enumeration

Fill in the blanks

  1. What is the difference between structure and union?

    All members in a structure are allocated memory whereas only the largest member of a union is allocated memory.

  2. What is the use of assigning a value to an item in enum type?

    The value is assigned to the item instead of the default value. If nothing is specified enum starts assigning from zero onwards.

  3. How do you create STRING data type for char *.
    typedef  char * STRING;
    
    

Chapter 17 - Pre-processor commands

Answer the following

  1. What is the difference between including file in <> and in "" with #include?

    In case of angle brakets (<>) C searches for the file only in standard include directory. In caes of double quotes C searches for header file in the current directory first and if it is not found then searches for the file in the standard include directory.

  2. Why a macro is used instead of a function?

    A macro will improve performance because it will not have the overheads of calling a function.

  3. Design a macro called odd to take a number and return 1 if it is odd and 0 if even.
    #define  odd(n)  n % 2
    

Chapter 18 - File handling

I.Fill in the blanks

  1. fgets()
  2. NULL pointer
  3. r+
  4. No. of files closed
  5. stdio.h

Write programs.

  1. Accept a filename and display only uppercase characters of the file.
    #include <stdio.h>
    #include <ctype.h>
    
    main()
    {
       char fn[30];
       int ch;
       FILE * fp;
    
         printf("Enter filename :");
         gets(fn);
    
         fp = fopen(fn,"r");
    
         if ( fp == NULL)
         {
             printf("File not found.");
             exit(1);
         }
    
         while ( !feof(fp) )
         {
           ch = fgetc(fp);
           if ( isupper(ch))
                 putchar(ch);
         }
    
         fclose(fp);
    } /* end of main */
    
    
  2. Accept source filename and target filename and copy the contents of source file to target file.
    
    #include <stdio.h>
    
    
    main()
    {
       char sfn[30],tfn[30];
       int ch;
       FILE * sfp, * tfp;
    
         printf("Enter source filename :");
         gets(sfn);
    
         printf("Enter target filename :");
         gets(tfn);
    
         sfp = fopen(sfn,"r");
    
         if ( sfp == NULL)
         {
             printf("Source file not found.");
             exit(1);
         }
    
         tfp = fopen(tfn,"w");
    
         if ( tfp == NULL)
         {
             printf("Target file not found.");
             exit(1);
         }
    
         while ( !feof(sfp) )
         {
           ch = fgetc(sfp);
           fputc(ch, tfp);
           
         }
    
         fcloseall();  /* close both the files */
    
    
    } /* end of main */
    
    
  3. Accept the filename and display the number of lines.
    
    #include <stdio.h>
    
    main()
    {
       char fn[30];
       int ch;
       FILE * fp;
       int  lines=0;
    
         printf("Enter filename :");
         gets(fn);
    
         fp = fopen(fn,"r");
    
         if ( fp == NULL)
         {
             printf("File not found.");
             exit(1);
         }
    
         while ( !feof(fp) )
         {
           ch = fgetc(fp);
    
           if ( ch == '\n')
                  lines ++;
         }
    
         fclose(fp);
    
         printf("No. of lines : %d", lines);
    
    } /* end of main */
    
    
  4. Accept filename and convert the contents to lowercase and write converted contents under the same filename.
    
    #include <stdio.h>
    #include <ctype.h>
    
    main()
    {
       char sfn[30];
       int ch;
       FILE * sfp, * tfp;
    
         printf("Enter source filename :");
         gets(sfn);
    
         sfp = fopen(sfn,"r");
    
         if ( sfp == NULL)
         {
             printf("Source file not found.");
             exit(1);
         }
    
         tfp = fopen("temp.txt","w");
    
         if ( tfp == NULL)
         {
             printf("Temporary file creation failed.");
             exit(1);
         }
    
         while ( !feof(sfp) )
         {
           ch = fgetc(sfp);
           fputc( tolower(ch), tfp);
           
         }
    
         fcloseall();  /* close both the files */
    
    
         /* remove source file */
    
         remove(sfn);
    
         /* rename temporary file to source file name */
    
         rename("temp.txt", sfn);
    
    
    } /* end of main */
    
    
  5. Accept lines from keyboard till END is given and write all lines into file called LINES.TXT.
    
    #include <stdio.h>
    
    main()
    {
       char line[100];
       FILE * fp;
    
    
         fp = fopen("lines.txt","w");
    
         if ( fp == NULL)
         {
             printf("LINES.TXT could not be created.");
             exit(1);
         }
    
    
         while (1)
         {
           printf("Enter a line and END to stop :");
           gets(line);
    
           if ( strcmp(line,"END") == 0 )
                  break;
    
           fputs(line,fp);
           
         }
    
         fclose(fp);  /* close the file */
    
    
    } /* end of main */
    
    

Chapter 19 - Binary files and random access

I. Write programs

  1. Accept details of a collection of students and write details into STUDENT.DAT.
    
    #include <stdio.h>
    
    
    struct student
    {
        int sno;
        char name[30];
        int  tf, fp;
    };
    
    main()
    {
       
       struct student s;
       FILE * fp;
    
          fp = fopen("student.dat","wb");  /* open in write and binary mode */
    
          while(1)
          {
             fflush(stdin);
    
             printf("Enter student number [0 to stop]: ");
             scanf("%d", & s.sno);
    
             if ( s.sno == 0 )  
    		break;
    
             fflush(stdin);
    
             printf("Enter student name : ");
             gets(s.name);
    
             printf("Enter total fee    : ");
             scanf("%d", & s.tf); 
    
             printf("Enter fee paid     : ");
             scanf("%d", & s.fp);
    
             /* write record to file */
    
             fwrite(&s,sizeof(s),1,fp);
          }
    
          fclose(fp);
    
    }
    
    
    
  2. Display the details of all students who have not paid complete amount by using the data in STUDENT.DAT.
    
    #include <stdio.h>
    
    
    struct student
    {
        int sno;
        char name[30];
        int  tf, fp;
    };
    
    main()
    {
       
       struct student s;
       FILE * fp;
       int count;
    
          fp = fopen("student.dat","rb");  /* open in read and binary mode */
    
          /* read record */
    
          count = fread(&s,sizeof(s),1,fp);
    
          while( count != 0 )
          {
    
             if ( s.tf > s.fp )
             printf("%d %s %d %d ", s.sno, s.name, s.tf, s.fp);
    
             count = fread(&s,sizeof(s),1,fp);
          }
    
          fclose(fp);
    
    }
    
    
    
  3. Accept record number and display that record from STUDENT.DAT.
    
    #include <stdio.h>
    
    
    struct student
    {
        int sno;
        char name[30];
        int  tf, fp;
    };
    
    main()
    {
       
       struct student s;
       FILE * fp;
       int recno;
    
          fp = fopen("student.dat","rb");  /* open in read and binary mode */
    
          /* read record number */
    
          printf("Enter record number. Record number starts with 0 : ");
          scanf("%d",&recno);
    
          /* move to the record with the given record number */
          fseek ( fp,  sizeof(s) * recno , 0); 
    
          /* read the record */
    
          fread(&s,sizeof(s),1,fp);
    
          printf("%d %s %d %d ", s.sno, s.name, s.tf, s.fp);
    
          fclose(fp);
    
    }
    
    
  4. Accept record number, amount paid and increment fp (fee paid) in that record by amount paid. Hint: Open file in r+ (read and write) mode. Read record, change the data in memory, and write record back to file. But make sure you move record pointer back before you write modified record.
    
    #include <stdio.h>
    
    struct student
    {
        int sno;
        char name[30];
        int  tf, fp;
    };
    
    main()
    {
       
       struct student s;
       FILE * fp;
       int recno;
    
          fp = fopen("student.dat","r+b");  /* open in update and binary mode */
    
          /* read record number */
    
          printf("Enter record number. Record number starts with 0 : ");
          scanf("%d",&recno);
    
          printf("Enter Amount paid : ");
          scanf("%d",&amt);
    
    
          /* move to the record with the given record number */
          fseek ( fp,  sizeof(s) * recno , 0); 
    
          /* read the record */
          fread(&s,sizeof(s),1,fp);
    
          /* update structure in memory */
          s.fp += amt;
    
          /* move back to the previous record */
          fseek ( fp,  sizeof(s) * -1l, 1); 
    
          /* write new record back to file */
          fwrite(&s,sizeof(s),1,fp);
    
          printf("Updation is complete");
    
          fclose(fp);
    
    }
    
    

Chapter 20 - Command line arguments

I. Write program

  1. Take source file and target file on command line and place source file contents into target file after converting contents to lowercase.
    #include <stdio.h>
    
    main(int argc, char * argv[] )
    {
       int ch;
       FILE * sfp, * tfp;
    
    
         if ( argc < 3 )
         {
           /* display syntax of the program. Assuming file name is LOWER.C */
           printf("LOWER  source target"); 
           exit(1);
         }
    
         sfp = fopen(argv[1],"r");
    
         if ( sfp == NULL)
         {
             printf("Source file not found.");
             exit(2);
         }
    
         tfp = fopen(tfn,"w");
    
         if ( tfp == NULL)
         {
             printf("Target file not found.");
             exit(3);
         }
    
         while ( !feof(sfp) )
         {
           ch = fgetc(sfp);
           fputc( tolower(ch), tfp);
           
         }
    
         fcloseall();  /* close both the files */
    
    
    } /* end of main */
    
    
  2. Take filename and a string on the command line and display all lines of the file that contain the given string along with line numbers.
    
    /* program to search for a string a file and display
       line where string is found along with line numbers  */
    
    #include <stdio.h>
    
    main()
    {
       FILE * fp;
       char line[100], word[30] , fn[30];
       int ln=1;
    
    
         /* take input from user */
         printf("Enter filename : ");
         gets(fn);
    
         printf("Enter string to search for : ");
         gets(word);
    
         /* open file */
    
         fp = fopen(fn,"r");
    
         ln = 1;
    
         while( !feof(fp))
         {
    	 fgets(line,100,fp);
    
    	 if ( strstr(line,word) != NULL )
    	    printf("%4d:%s", ln, line);
    
    	 ln++;
         }
    
         fclose(fp);
    }
    
    
  3. Take a target file and source file(s) and place the contents of source files in target file.
    Example: c:\>concat t.txt a.txt b.txt
    Places contents of a.txt and b.txt one after another into t.txt.
    
    #include <stdio.h>
    
    
    main(int argc, char * argv[] )
    {
       int ch;
       FILE * sfp, * tfp;
       int i;
    
    
         if ( argc < 3 )
         {
           /* display syntax of the program. Assuming file name is COPYALL.C */
           printf("COPYALL  target  source ..."); 
           exit(1);
         }
    
         /* open target file */
         tfp = fopen(argv[1],"w");
    
         if ( tfp == NULL)
         {
             printf("Target file open error.");
             exit(2);
         }
    
         for ( i = 2; i < argc ;i ++)
         {
           /* open source file */
    
           sfp = fopen( argv[i], "r");
     
           if ( sfp == NULL)
           {
             printf("Error while opening file %s ", argv[i]);
             exit(3);
           }
    
           while ( !feof(sfp) )
           {
            ch = fgetc(sfp);
            fputc( ch, tfp);
           }
    
           /* close current source file */
           
           fclose(sfp);
    
         } /* end of for loop */
       
         fclose(tfp);   /* close target file */
    
    } /* end of main */
    
    

Chapter 21 - Dynamic memory allocation

I. Fill in the blanks

  1. void *
  2. free()
  3. void *
  4. Because the default return type is void *, which is a pointer that points to no specific data type.

II. Write Programs

  1. Accept 10 strings from user and store them in an array of char *. Hint: You have to take one string at a time and then allocate a block in memory and copy the string to that block. All such strings that are dynamically allocated should be pointed by an array of 10 char *.
    
    
    /* Take a collection of strings and store them in an array of char *
       Memory for strings is allocated dynamically  */
    
    main()
    {
      char *  a[10];
      char st[100];
      int i;
    
    
          /* take 10 strings */
          clrscr();
    
          for ( i = 0 ; i < 5 ; i ++)
          {
    	  printf("Enter a string :");
    	  gets(st);
    
    	  /* allocate memory for the given string */
    	  a[i] = (char * ) malloc( strlen(st));
    
    	  /* copy string into newly allocated space */
    	  strcpy(a[i],st);
          }
    
          /* display all strings */
    
          for ( i = 0 ; i < 5 ; i ++)
    	 puts( a[i]);
    
    }
    
    
    

Chapter 22 - Linked list

I. Write programs

  1. Write a program to take the content of a file into a linked list and display the content in the reverse order. Hint: Create a list that works like a stack and not a queue.
    #include <stdio.h>
    
    
    /* create a structure for node */
    
    typedef struct node
    {
       char line[100];
       struct node  * prev;
    } NODE;
    
    
    main()
    {
      NODE * root= NULL ,*current;
      char fn[10],line[100];
      FILE * fp;
    
         clrscr();
         printf("Enter filename :");
         gets(fn);
    
         fp = fopen(fn,"r");
    
         while ( !feof(fp))
         {
           fgets(line,100,fp);
           printf(line);
    
           current  = (NODE * ) malloc(sizeof(NODE));
    
           if ( current == NULL)
           {
    	  printf("Memory allocation error. ");
    	  exit(1);
           }
    
           /* copy data into node */
    
           strcpy( current -> line, line);
    
    
           current -> prev = root;
           root = current;
    
        } /* end of while */
    
        fclose(fp);
    
       /* display the content of the file */
    
       current = root;
       while ( current != NULL)
       {
           printf(current-> line);
           current = current -> prev;
       }  /* end of while */
    
    
    } /* end of main */
    
    
    
  2. Write a program to create a linked list to take all lines from the given file. While creating the list ensure the nodes in the list are in the ascending order. Then display the sorted list.
    /* take the content of the file and sort it */
    #include 
    #include 
    
    struct node
    {
       char line[100];
       struct node * next;
    } * root;
    
    struct node * findpos(char *);
    
    
    main()
    {
     struct node * cur, * prev;
     char fn[30],line[100];
    
     FILE * fp;
    
    
          printf("Enter filename : ");
          gets(fn);
     
          fp = fopen(fn,"rt");
          if ( fp == NULL)
          {
                printf("File not found. ");
                exit(1);
          }
    
          /* add a dummy node at the beginning */
    
          cur = (struct node * ) malloc(sizeof(struct node ));
          cur -> next = NULL;
          cur->line[0] = '\0';  /* value is empty string */
    
          root = cur;
    
          while ( fgets(line,100,fp) != NULL )
          {
    	  cur = ( struct node  * ) malloc( sizeof(struct node));
    	  strcpy( cur-> line, line);
    
    	  prev = findpos(line);
    	  cur-> next = prev-> next;
    	  prev -> next = cur;
         }
    
         fclose(fp);
    
    
         /* display the list */
         clrscr();
         cur = root;
         while ( cur != NULL)
         {
    	  printf("%s", cur->line);
    	  cur = cur -> next;
         }
    
    }
    
    struct node * findpos( char * line)
    {
       struct node * cur, * prev;
    
           prev =  root;
           cur = root -> next;
    
           while ( cur != NULL )
           {
    	   if ( strcmp(cur-> line, line) > 0 )
    	       break;
    	   prev = cur;
    	   cur = cur -> next;
           }
           return prev;
    }
    
    
    
  3. Create a function called search that takes the root node and the name to search for. It must return the address of the node if the name is found in the list otherwise NULL pointer.
    
    
    #include <alloc.h>
    
    /* create a structure for node */
    
    typedef struct node
    {
       char line[100];
       struct node  * next;
    
    } NODE;
    
    
    NODE * search(NODE * root, char name[20] )
    {
     NODE *  current;
    
    
       current = root;
       while ( current != NULL)
       {
           if (  strcmp( current-> line, name) == 0 )
    		  return current;
    
    	current = current -> next;
       }
    
       return NULL; /* value not found */
    } /* end of function */