Loading....
Coupon Accepted Successfully!

 

Question 31

How to swap the two nibbles in a byte ?


Try this


#include 

unsigned char swap_nibbles(unsigned char c)
{
  unsigned char temp1, temp2;
  temp1 = c & 0x0F;
  temp2 = c & 0xF0;
  temp1=temp1 <   temp2=temp2 >> 4;  

  return(temp2|temp1); //adding the bits
}

int main(void)
{
  char ch=0x34;
  printf("\nThe exchanged value is %x",swap_nibbles(ch));
  return 0;
}




Question 32

How to scan a string till we hit a new line using scanf()?


Use



scanf("%[^\n]", address);



Question 33

Write pseudocode to compare versions (like 115.10.1 vs 115.11.5).


This question is also quite popular, because it has real practical uses, specially during patching when version comparison is required

The pseudocode is something like


while(both version strings are not NULL)
{
  // Extract the next version segment from Version string1.
  // Extract the next version segment from Version string2.

  // Compare these segments, if they are equal, continue 
  // to check the next version segments.

  // If they are not equal, return appropriate code depending
  // on which segment is greater.
}




And here is some code in PL-SQL


---------------------------------------------------------------------
compare_versions()

Function to compare releases. Very useful when comparing file versions!

This function compare two versions in pl-sql language. This function can compare
Versions like 115.10.1 vs. 115.10.2 (and say 115.10.2 is greater), 115.10.1 vs. 115.10 (and say
115.10.1 is greater), 115.10 vs. 115.10 (and say both are equal) 
---------------------------------------------------------------------

function compare_releases(release_1 in varchar2, release_2 in varchar2) 
return boolean is 

  release_1_str varchar2(132); 
  release_2_str varchar2(132); 
  release_1_ver number; 
  release_2_ver number; 
  ret_status boolean := TRUE; 

begin 

  release_1_str := release_1 || '.'; 
  release_2_str := release_2 || '.'; 
  
  while release_1_str is not null or release_2_str is not null loop 

    -- Parse out a current version segment from release_1 

    if (release_1_str is null) then 
       release_1_ver := 0; 
    else 
      release_1_ver := nvl(to_number(substr(release_1_str,1, instr(release_1_str,'.')-1)),-1); 
      release_1_str := substr(release_1_str,instr(release_1_str,'.')+1); 
    end if; 

    -- Next parse out a version segment from release_2 
    if (release_2_str is null) then 
       release_2_ver := 0; 
    else 
       release_2_ver := nvl(to_number(substr(release_2_str,1, instr(release_2_str,'.')-1)),-1); 
       release_2_str := substr(release_2_str,instr(release_2_str,'.')+1); 
    end if; 
   

     if (release_1_ver > release_2_ver) then 
        ret_status := FALSE; 
        exit; 
     elsif (release_1_ver          exit; 
     end if; 
 
     -- Otherwise continue to loop. 
   end loop; 

   return(ret_status); 

end compare_releases;



Question 34

Write a C program to reverse the words in a sentence in place.


That is, given a sentence like this


I am a good boy


The in place reverse would be


boy good a am I



Method1

First reverse the whole string and then individually reverse the words


I am a good boy
<------------->

yob doog  a   ma   I
<->  <->  <-> <->

boy good a am I




Here is some C code to do the same ....


/*
  Algorithm..
  
  1. Reverse whole sentence first.
  2. Reverse each word individually.

  All the reversing happens in-place.
*/

#include 

void rev(char *l, char *r);


int main(int argc, char *argv[])
{
   char buf[] = "the world will go on forever";
   char *end, *x, *y;
      
   // Reverse the whole sentence first..
   for(end=buf; *end; end++);
   rev(buf,end-1); 


   // Now swap each word within sentence...
   x = buf-1; 
   y = buf; 

   while(x++     {
      if(*x == '\0' || *x == ' ')
      {
        rev(y,x-1);
        y = x+1;
      }
   }   
   
   // Now print the final string....
   printf("%s\n",buf);
   
   return(0);
}


// Function to reverse a string in place...
void rev(char *l,char *r)
{
   char t;
   while(l    { 
      t    = *l; 
      *l++ = *r; 
      *r-- = t; 
   }
}






Method2
Another way to do it is, allocate as much memory as the input for the final output. Start from the right of the string and copy the words one by one to the output.


Input  : I am a good boy
                     <--
                <-------
              <---------
           <------------
         <--------------
  

Output : boy
       : boy good
       : boy good a 
       : boy good a am 
       : boy good a am I 



The only problem to this solution is the extra space required for the output and one has to write this code really well as we are traversing the string in the reverse direction and there is no null at the start of the string to know we have reached the start of the string!. One can use the strtok() function to breakup the string into multiple words and rearrange them in the reverse order later.


Method3

Create a linked list like


+---+    +----------+    +----+    +----------+    +---+    +----------+ 
| I | -> |  | -> | am | -> |  | -> | a | -> |  | --+
+---+    +----------+    +----+    +----------+    +---+    +----------+   |
                                                                           |
                                                                           |
 +-------------------------------------------------------------------------+
 |
 |     +------+    +----------+    +-----+    +------+
 +---> | good | -> |  | -> | boy | -> | NULL | 
       +------+    +----------+    +-----+    +------+




Now its a simple question of reversing the linked list!. There are plenty of algorithms to reverse a linked list easily. This also keeps track of the number of spaces between the words. Note that the linked list algorithm, though inefficient, handles multiple spaces between the words really well.

I really dont know what is the use of reversing a string or a sentence like this!, but its still asked. Can someone tell me a really practical application of this? Please!


Question 35

How do you get the line numbers in C?


Use the following Macros


__FILE__ Source file name (string constant) format "patx.c" 
__LINE__ Current source line number (integer) 
__DATE__ Date compiled (string constant)format "Dec 14 1985" 
__TIME__ Time compiled (string constant) format "15:24:26" 
__TIMESTAMP__ Compile date/time (string constant)format "Tue Nov 19 11:39:12 1997" 



Usage example


static char stamp[] =    "***\nmodule " __FILE__    "\ncompiled " __TIMESTAMP__     "\n***";

...

int main()
{   
   ...
   
   if ( (fp = fopen(fl,"r")) == NULL )   
   {      
      printf( "open failed, line %d\n%s\n",__LINE__, stamp );      
      exit( 4 );   
   }

   ...
}



And the output is something like


*** open failed, line 67 
******
module myfile.c 
compiled Mon Jan 15 11:15:56 1999 
*** 



Question 36

How to fast multiply a number by 7?


Try


(num<<3 - num)


This is same as


num*8 - num = num * (8-1) = num * 7



Question 37

Write a simple piece of code to split a string at equal intervals


Suppose you have a big string


This is a big string which I want to split at equal intervals, without caring about the words.


Now, to split this string say into smaller strings of 20 characters each, try this


#define maxLineSize 20

split(char *string)
{
  int i, length;
  char dest[maxLineSize + 1];

  i           = 0;
  length      = strlen(string);

  while((i+maxLineSize) <= length)
  {
     strncpy(dest, (string+i), maxLineSize);
     dest[maxLineSize - 1] = '\0';
     i = i + strlen(dest) - 1;
     printf("\nChunk : [%s]\n", dest);
  }

  strcpy(dest, (string + i));
  printf("\nChunk : [%s]\n", dest);
}



Question 38

Is there a way to multiply matrices in lesser than o(n^3) time complexity?


Yes. Divide and conquer method suggests Strassen's matrix multiplication method to be used. If we follow this method, the time complexity is O(n^2.81) times rather O(n^3) times.

Here are some more details about this method.

Suppose we want to multiply two matrices of size N x N: for example A x B = C


[C11 C12]   [A11 A12] [B11 B12]
[C21 C22] = [A21 A22] [B21 B22]



Now, this guy called Strassen's somehow :) came up with a bunch of equations to calculate the 4 elements of the resultant matrix


C11 = a11*b11 + a12*b21 
C12 = a11*b12 + a12*b22 
C21 = a21*b11 + a22*b21 
C22 = a21*b12 + a22*b22




If you are aware, the rudimentary matrix multiplication goes something like this


void matrix_mult()
{
  for (i = 1; i <= N; i++) 
  {                                                                  
     for (j = 1; j <= N; j++) 
     {                  
        compute Ci,j;                                                           
     }
  } 
}



So, essentially, a 2x2 matrix multiplication can be accomplished using 8 multiplications. And the complexity becomes


2^log 8 =2^3


Strassen showed that 2x2 matrix multiplication can be accomplished in 7 multiplications and 18 additions or subtractions. So now the complexity becomes


2^log7 =2^2.807


This is how he did it


P1 = (A11+ A22)(B11+B22) 
P2 = (A21 + A22) * B11 
P3 = A11 * (B12 - B22) 
P4 = A22 * (B21 - B11) 
P5 = (A11 + A12) * B22 
P6 = (A21 - A11) * (B11 + B12) 
P7 = (A12 - A22) * (B21 + B22) 

C11 = P1 + P4 - P5 + P7
C12 = P3 + P5 
C21 = P2 + P4 
C22 = P1 + P3 - P2 + P6 



Now, there is no need to memorize this stuff!


Question 39

Write a program to have the output go two places at once (to the screen and to a file also)


You can write a wrapper function for printf() which prints twice.


myprintf(...)
{
  // printf();        -> To screen.
  // write_to_file(); -> To file.
}



A command in shell, called tee does have this functionality!


Question 40

Write code to round numbers


Use something like


(int)(num)






Test Your Skills Now!
Take a Quiz now
Reviewer Name