I this post we have provided part 3 of the C programs most commonly asked in interview along with answers. We recommend you to try to answer the questions, before referring to the given answer. If you find any mistake or a better alternate solution we are happy to see your suggestions and comments

1. Write a function to trim trailing space

char * trimr(char *str)
{
   char *end = str + strlen(str) - 1;
   while(end >= str)
   {
      if('\n' == *end || '\t' == *end ||
            '\r' == *end || ' ' == *end)
         end--;
      else break;
   }
   end[1] = 0;
   return str;
}

2. Write the implementation of toupper() function

int toupper(int ch)
{
   if('a' <= ch && ch <= 'z')
      return 'A' +  ch - 'a';
   return ch;
}

3. Write the implementation of tolower() function

int tolower(int ch)
{
   if('A' <= ch && ch <= 'Z')
      return 'a' + ch - 'A';
   return ch;
}

4. Write the implementation of strdup() function

char * strdup(const char *str)
{
   int len = 0;
   while(str[len++]);
   char *dup = (char *)malloc(len);
   if(NULL == dup) return NULL;
   char *itr = dup;
   while(*itr++ = *str++);
   return dup;
}

5. Write a function to allocate for a 2D int array

int ** Alloc_2D(int ncol, int nrow)
{
   int **Arr_2D = 0;
   Arr_2D = (int **)malloc(ncol * sizeof(int *));
   if(NULL == Arr_2D) return NULL;
   for(int r = 0; r < nrow; r++)
   {
      Arr_2D[r] = (int *)malloc(nrow * sizeof(int));
      if(NULL == Arr_2D[r])
      {
         for(int J = 0; J < I; J++)
            free(Arr_2D[J]);
         free(Arr_2D);
         return NULL;
      }
   }
   return Arr_2D;
}

6. Write a function to reverse the digits of a integer

int reverse(int num)
{
   int rem = 0;
   int rev = 0;
   //while(rem = num % 10)
   while(num)
   {
      rem = num % 10;
      rev *= 10;
      rev += rem;
      num /= 10;
   }
   return rev;
}

7. Write the implementation of strtok() function

char * strtok(char *str, char sep)
{
   static char *pos = 0;
   static char *cpy = 0;

   if(str) pos = cpy = str;
   if(0 == (cpy = pos)) return 0;
   pos = strchr(pos, sep);
   if(pos) { pos[0] = 0; pos++; }

   return cpy;
}