This C code will create a new mirror copy tree.
mynode *copy(mynode *root)
{
mynode *temp;
if(root==NULL)return(NULL);
temp = (mynode *) malloc(sizeof(mynode));
temp>value = root>value;
temp>left = copy(root>right);
temp>right = copy(root>left);
return(temp);
}
This code will will only print the mirror of the tree
void tree_mirror(struct node* node)
{
struct node *temp;
if (node==NULL)
{
return;
}
else
{
tree_mirror(node>left);
tree_mirror(node>right);
// Swap the pointers in this node
temp = node>left;
node>left = node>right;
node>right = temp;
}
}
Wednesday, August 15, 2007
Write a C program to compute the maximum depth in a tree?
int maxDepth(struct node* node)
{
if (node==NULL)
{
return(0);
}
else
{
int leftDepth = maxDepth(node>left);
int rightDepth = maxDepth(node>right);
if (leftDepth > rightDepth) return(leftDepth+1);
else return(rightDepth+1);
}
}
{
if (node==NULL)
{
return(0);
}
else
{
int leftDepth = maxDepth(node>left);
int rightDepth = maxDepth(node>right);
if (leftDepth > rightDepth) return(leftDepth+1);
else return(rightDepth+1);
}
}
Write a C program to find the mininum value in a binary search tree.
Here is some sample C code. The idea is to keep on moving till you hit the left most node in the tree
int minValue(struct node* node)
{
struct node* current = node;
while (current>left != NULL)
{
current = current>left;
}
return(current>data);
}
On similar lines, to find the maximum value, keep on moving till you hit the right most node of the tree.
int minValue(struct node* node)
{
struct node* current = node;
while (current>left != NULL)
{
current = current>left;
}
return(current>data);
}
On similar lines, to find the maximum value, keep on moving till you hit the right most node of the tree.
Write C code to determine if two trees are identical .
Here is a C program using recursion
int identical(struct node* a, struct node* b)
{
if (a==NULL && b==NULL){return(true);}
else if (a!=NULL && b!=NULL)
{
return(a>data == b>data &&
identical(a>left, b>left) &&
identical(a>right, b>right));
}
else return(false);
}
int identical(struct node* a, struct node* b)
{
if (a==NULL && b==NULL){return(true);}
else if (a!=NULL && b!=NULL)
{
return(a>data == b>data &&
identical(a>left, b>left) &&
identical(a>right, b>right));
}
else return(false);
}
Write a C program to delete a tree (i.e, free up its nodes)
Free up the nodes using Postorder traversal!.
Write a C program to determine the number of elements (or size) in a tree.
int tree_size(struct node* node)
{
if (node==NULL)
{
return(0);
}
else
{
return(tree_size(node>left) + tree_size(node>right) + 1);
}
}
{
if (node==NULL)
{
return(0);
}
else
{
return(tree_size(node>left) + tree_size(node>right) + 1);
}
}
Write a C program to find the depth or height of a tree.
Here is some C code to get the height of the three
tree_height(mynode *p)
{
if(p==NULL)return(0);
if(p>left){h1=tree_height(p>left);}
if(p=>right){h2=tree_height(p>right);}
return(max(h1,h2)+1);
}
The degree of the leaf is zero. The degree of a tree is the max of its element degrees. A binary tree of height n, h > 0, has at least h and at most (2^h 1) elements in it. The height of a binary tree that contains n, n>0, elements is at most n and atleast log(n+1) to the base 2.
Log(n+1) to the base 2 = h
n = (2^h  1)
tree_height(mynode *p)
{
if(p==NULL)return(0);
if(p>left){h1=tree_height(p>left);}
if(p=>right){h2=tree_height(p>right);}
return(max(h1,h2)+1);
}
The degree of the leaf is zero. The degree of a tree is the max of its element degrees. A binary tree of height n, h > 0, has at least h and at most (2^h 1) elements in it. The height of a binary tree that contains n, n>0, elements is at most n and atleast log(n+1) to the base 2.
Log(n+1) to the base 2 = h
n = (2^h  1)
Write your own trim() or squeeze() function to remove the spaces from a string.
#include < stdio.h >
char *trim(char *s);
int main(int argc, char *argv[])
{
char str1[]=" Hello I am Good ";
printf("\n\nBefore trimming : [%s]", str1);
printf("\n\nAfter trimming : [%s]", trim(str1));
getch();
}
// The trim() function...
char *trim(char *s)
{
char *p, *ps;
for (ps = p = s; *s != '\0'; s++)
{
if (!isspace(*s))
{
*p++ = *s;
}
}
*p = '\0';
return(ps);
}
And here is the output...
Before trimming : [ Hello I am Good ]
After trimming : [HelloIamGood]
Another version of this question requires one to reduce multiple spaces, tabs etc to single spaces...
char *trim(char *s);
int main(int argc, char *argv[])
{
char str1[]=" Hello I am Good ";
printf("\n\nBefore trimming : [%s]", str1);
printf("\n\nAfter trimming : [%s]", trim(str1));
getch();
}
// The trim() function...
char *trim(char *s)
{
char *p, *ps;
for (ps = p = s; *s != '\0'; s++)
{
if (!isspace(*s))
{
*p++ = *s;
}
}
*p = '\0';
return(ps);
}
And here is the output...
Before trimming : [ Hello I am Good ]
After trimming : [HelloIamGood]
Another version of this question requires one to reduce multiple spaces, tabs etc to single spaces...
How to add two numbers without using the plus operator?
Actually,
SUM = A XOR B
CARRY = A AND B
On a wicked note, you can add two numbers wihtout using the + operator as follows
a  ( b)
SUM = A XOR B
CARRY = A AND B
On a wicked note, you can add two numbers wihtout using the + operator as follows
a  ( b)
How to generate prime numbers? How to generate the next prime after a given prime?
This is a very vast subject. There are numerous methods to generate primes or to find out if a given number is a prime number or not. Here are a few of them. I strongly recommend you to search on the Internet for more elaborate information.
Brute Force
Test each number starting with 2 and continuing up to the number of primes we want to generate. We divide each numbr by all divisors upto the square root of that number. If no factors are found, its a prime.
Using only primes as divisors
Test each candidate only with numbers that have been already proven to be prime. To do so, keep a list of already found primes (probably using an array, a file or bit fields).
Test with odd candidates only
We need not test even candidates at all. We could make 2 a special case and just print it, not include it in the list of primes and start our candidate search with 3 and increment by 2 instead of one everytime.
Table method
Suppose we want to find all the primes between 1 and 64. We write out a table of these numbers, and proceed as follows. 2 is the first integer greater than 1, so its obviously prime. We now cross out all multiples of two. The next number we haven't crossed out is 3. We circle it and cross out all its multiples. The next noncrossed number is 5, sp we circle it and cross all its mutiples. We only have to do this for all numbers less than the square root of our upper limit, since any composite in the table must have atleast one factor less than the square root of the upper limit. Whats left after this process of elimination is all the prime numbers between 1 and 64.
Brute Force
Test each number starting with 2 and continuing up to the number of primes we want to generate. We divide each numbr by all divisors upto the square root of that number. If no factors are found, its a prime.
Using only primes as divisors
Test each candidate only with numbers that have been already proven to be prime. To do so, keep a list of already found primes (probably using an array, a file or bit fields).
Test with odd candidates only
We need not test even candidates at all. We could make 2 a special case and just print it, not include it in the list of primes and start our candidate search with 3 and increment by 2 instead of one everytime.
Table method
Suppose we want to find all the primes between 1 and 64. We write out a table of these numbers, and proceed as follows. 2 is the first integer greater than 1, so its obviously prime. We now cross out all multiples of two. The next number we haven't crossed out is 3. We circle it and cross out all its multiples. The next noncrossed number is 5, sp we circle it and cross all its mutiples. We only have to do this for all numbers less than the square root of our upper limit, since any composite in the table must have atleast one factor less than the square root of the upper limit. Whats left after this process of elimination is all the prime numbers between 1 and 64.
Write a program to print numbers from 1 to 100 without using loops!
Another "Yeah, I am a jerk, kick me! kind of a question. I simply dont know why they ask these questions.
Nevertheless, for the benefit of mankind...
Method1 (Using recursion)
void printUp(int startNumber, int endNumber)
{
if (startNumber > endNumber)
return;
printf("[%d]\n", startNumber++);
printUp(startNumber, endNumber);
}
Method2 (Using goto)
void printUp(int startNumber, int endNumber)
{
start:
if (startNumber > endNumber)
{
goto end;
}
else
{
printf("[%d]\n", startNumber++);
goto start;
}
end:
return;
}
Nevertheless, for the benefit of mankind...
Method1 (Using recursion)
void printUp(int startNumber, int endNumber)
{
if (startNumber > endNumber)
return;
printf("[%d]\n", startNumber++);
printUp(startNumber, endNumber);
}
Method2 (Using goto)
void printUp(int startNumber, int endNumber)
{
start:
if (startNumber > endNumber)
{
goto end;
}
else
{
printf("[%d]\n", startNumber++);
goto start;
}
end:
return;
}
Monday, July 9, 2007
Write a program to check if the stack grows up or down.
Try noting down the address of a local variable. Call another function with a local variable declared in it and check the address of that local variable and compare!.
#include < stdio.h >
#include < stdlib.h >
void stack(int *local1);
int main()
{
int local1;
stack(&local1);
exit(0);
}
void stack(int *local1)
{
int local2;
printf("\nAddress of first local : [%u]", local1);
printf("\nAddress of second local : [%u]", &local2);
if(local1 < &local2)
{
printf("\nStack is growing downwards.\n");
}
else
{
printf("\nStack is growing upwards.\n");
}
printf("\n\n");
}
#include < stdio.h >
#include < stdlib.h >
void stack(int *local1);
int main()
{
int local1;
stack(&local1);
exit(0);
}
void stack(int *local1)
{
int local2;
printf("\nAddress of first local : [%u]", local1);
printf("\nAddress of second local : [%u]", &local2);
if(local1 < &local2)
{
printf("\nStack is growing downwards.\n");
}
else
{
printf("\nStack is growing upwards.\n");
}
printf("\n\n");
}
Given two strings A and B, how would you find out if the characters in B were a subset of the characters in A?
Here is a simple, yet efficient C program to accomplish the same...
#include < stdio.h >
#include < conio.h >
int isSubset(char *a, char *b);
int main()
{
char str1[]="defabc";
char str2[]="abcfed";
if(isSubset(str1, str2)==0)
{
printf("\nYes, characters in B=[%s] are a subset of characters in A=[%s]\n",str2,str1);
}
else
{
printf("\nNo, characters in B=[%s] are not a subset of characters in A=[%s]\n",str2,str1);
}
getch();
return(0);
}
// Function to check if characters in "b" are a subset
// of the characters in "a"
int isSubset(char *a, char *b)
{
int letterPresent[256];
int i;
for(i=0; i < 256; i++)
letterPresent[i]=0;
for(i=0; a[i]!='\0'; i++)
letterPresent[a[i]]++;
for(i=0; b[i]!='\0'; i++)
if(!letterPresent[b[i]])
return(1);
return(0);
}
#include < stdio.h >
#include < conio.h >
int isSubset(char *a, char *b);
int main()
{
char str1[]="defabc";
char str2[]="abcfed";
if(isSubset(str1, str2)==0)
{
printf("\nYes, characters in B=[%s] are a subset of characters in A=[%s]\n",str2,str1);
}
else
{
printf("\nNo, characters in B=[%s] are not a subset of characters in A=[%s]\n",str2,str1);
}
getch();
return(0);
}
// Function to check if characters in "b" are a subset
// of the characters in "a"
int isSubset(char *a, char *b)
{
int letterPresent[256];
int i;
for(i=0; i < 256; i++)
letterPresent[i]=0;
for(i=0; a[i]!='\0'; i++)
letterPresent[a[i]]++;
for(i=0; b[i]!='\0'; i++)
if(!letterPresent[b[i]])
return(1);
return(0);
}
How can we sum the digits of a given number in single statement?
Try something like this
# include < stdio.h >
void main()
{
int num=123456;
int sum=0;
for(;num > 0;sum+=num%10,num/=10); // This is the "single line".
printf("\nsum = [%d]\n", sum);
}
If there is a simpler way to do this, let me know!
# include < stdio.h >
void main()
{
int num=123456;
int sum=0;
for(;num > 0;sum+=num%10,num/=10); // This is the "single line".
printf("\nsum = [%d]\n", sum);
}
If there is a simpler way to do this, let me know!
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!
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!
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);
}
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);
}
How to fast multiply a number by 7?
Try
(num << 3  num)
This is same as
num*8  num = num * (81) = num * 7
(num << 3  num)
This is same as
num*8  num = num * (81) = num * 7
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
***
__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
***
How to swap the two nibbles in a byte ?
Try this
#include < stdio.h >
unsigned char swap_nibbles(unsigned char c)
{
unsigned char temp1, temp2;
temp1 = c & 0x0F;
temp2 = c & 0xF0;
temp1=temp1 << 4;
temp2=temp2 >> 4;
return(temp2temp1); //adding the bits
}
int main(void)
{
char ch=0x34;
printf("\nThe exchanged value is %x",swap_nibbles(ch));
return 0;
}
#include < stdio.h >
unsigned char swap_nibbles(unsigned char c)
{
unsigned char temp1, temp2;
temp1 = c & 0x0F;
temp2 = c & 0xF0;
temp1=temp1 << 4;
temp2=temp2 >> 4;
return(temp2temp1); //adding the bits
}
int main(void)
{
char ch=0x34;
printf("\nThe exchanged value is %x",swap_nibbles(ch));
return 0;
}
Is there something we can do in C but not in C++?
I have a really funny answer
Declare variable names that are keywords in C++ but not C.
#include < stdio.h >
int main(void)
{
int old, new=3;
return 0;
}
This will compile in C, but not in C++!
Declare variable names that are keywords in C++ but not C.
#include < stdio.h >
int main(void)
{
int old, new=3;
return 0;
}
This will compile in C, but not in C++!
How do you compare floating point numbers?
This is Wrong!.
double a, b;
if(a == b)
{
...
}
The above code might not work always. Thats because of the way floating point numbers are stored.
A good way of comparing two floating point numbers is to have a accuracy threshold which is relative to the magnitude of the two floating point numbers being compared.
#include < math.h >
if(fabs(a  b) <= accurary_threshold * fabs(a))
There is a lot of material on the net to know how floating point numbers can be compared. Got for it if you really want to understand.
Another way which might work is something like this. I have not tested it!
int compareFloats(float f1, float f2)
{
char *b1, *b2;
int i;
b1 = (char *)&f1;
b2 = (char *)&f2;
/* Assuming sizeof(float) is 4 bytes) */
for (i = 0; i < 4; i++, b1++, b2++)
{
if (*b1 != *b2)
{
return(NOT_EQUAL); /* You must have defined this before */
}
}
return(EQUAL);
}
double a, b;
if(a == b)
{
...
}
The above code might not work always. Thats because of the way floating point numbers are stored.
A good way of comparing two floating point numbers is to have a accuracy threshold which is relative to the magnitude of the two floating point numbers being compared.
#include < math.h >
if(fabs(a  b) <= accurary_threshold * fabs(a))
There is a lot of material on the net to know how floating point numbers can be compared. Got for it if you really want to understand.
Another way which might work is something like this. I have not tested it!
int compareFloats(float f1, float f2)
{
char *b1, *b2;
int i;
b1 = (char *)&f1;
b2 = (char *)&f2;
/* Assuming sizeof(float) is 4 bytes) */
for (i = 0; i < 4; i++, b1++, b2++)
{
if (*b1 != *b2)
{
return(NOT_EQUAL); /* You must have defined this before */
}
}
return(EQUAL);
}
Write a program to add two long positive numbers (each represented by linked lists).
Check out this simple implementation
mynode *long_add(mynode *h1, mynode *h2, mynode *h3)
{
mynode *c, *c1, *c2;
int sum, carry, digit;
carry = 0;
c1 = h1>next;
c2 = h2>next;
while(c1 != h1 && c2 != h2)
{
sum = c1>value + c2>value + carry;
digit = sum % 10;
carry = sum / 10;
h3 = insertNode(digit, h3);
c1 = c1>next;
c2 = c2>next;
}
if(c1 != h1)
{
c = c1;
h = h1;
}
else
{
c = c2;
h = h2;
}
while(c != h)
{
sum = c>value + carry;
digit = sum % 10;
carry = sum / 10;
h3 = insertNode(digit, h3);
c = c>next;
}
if(carry==1)
{
h3 = insertNode(carry, h3);
}
return(h3);
}
mynode *long_add(mynode *h1, mynode *h2, mynode *h3)
{
mynode *c, *c1, *c2;
int sum, carry, digit;
carry = 0;
c1 = h1>next;
c2 = h2>next;
while(c1 != h1 && c2 != h2)
{
sum = c1>value + c2>value + carry;
digit = sum % 10;
carry = sum / 10;
h3 = insertNode(digit, h3);
c1 = c1>next;
c2 = c2>next;
}
if(c1 != h1)
{
c = c1;
h = h1;
}
else
{
c = c2;
h = h2;
}
while(c != h)
{
sum = c>value + carry;
digit = sum % 10;
carry = sum / 10;
h3 = insertNode(digit, h3);
c = c>next;
}
if(carry==1)
{
h3 = insertNode(carry, h3);
}
return(h3);
}
Write code to add two polynomials.
Here is some pseudocode
mynode *polynomial_add(mynode *h1, mynode *h2, mynode *h3)
{
mynode *p1, *p2;
int x1, x2, y1, y2, cf1, cf2, cf;
p1 = h1>next;
while(p1!=h1)
{
x1 = p1>px;
y1 = p1>py;
cf1 = p1>cf;
// Search for this term in the second polynomial
p2 = h2>next;
while(p2 != h2)
{
x2 = p2>px;
y2 = p2>py;
cf2 = p2>cf;
if(x1 == x2 && y1 == y2)break;
p2 = p2>next;
}
if(p2 != h2)
{
// We found something in the second polynomial.
cf = cf1 + cf2;
p2>flag = 1;
if(cf!=0){h3=addNode(cf,x1,y1,h3);}
}
else
{
h3=addNode(cf,x1,y1,h3);
}
p1 = p1>next;
}//while
// Add the remaining elements of the second polynomail to the result
while(p2 != h2)
{
if(p2 > flag ==0)
{
h3=addNode(p2>cf, p2>px, p2>py, h3);
}
p2=p2>next;
}
return(h3);
}
mynode *polynomial_add(mynode *h1, mynode *h2, mynode *h3)
{
mynode *p1, *p2;
int x1, x2, y1, y2, cf1, cf2, cf;
p1 = h1>next;
while(p1!=h1)
{
x1 = p1>px;
y1 = p1>py;
cf1 = p1>cf;
// Search for this term in the second polynomial
p2 = h2>next;
while(p2 != h2)
{
x2 = p2>px;
y2 = p2>py;
cf2 = p2>cf;
if(x1 == x2 && y1 == y2)break;
p2 = p2>next;
}
if(p2 != h2)
{
// We found something in the second polynomial.
cf = cf1 + cf2;
p2>flag = 1;
if(cf!=0){h3=addNode(cf,x1,y1,h3);}
}
else
{
h3=addNode(cf,x1,y1,h3);
}
p1 = p1>next;
}//while
// Add the remaining elements of the second polynomail to the result
while(p2 != h2)
{
if(p2 > flag ==0)
{
h3=addNode(p2>cf, p2>px, p2>py, h3);
}
p2=p2>next;
}
return(h3);
}
Write C code to implement the Binary Search algorithm.
Here is a C function
int binarySearch(int arr[],int size, int item)
{
int left, right, middle;
left = 0;
right = size1;
while(left <= right)
{
middle = ((left + right)/2);
if(item == arr[middle])
{
return(middle);
}
if(item > arr[middle])
{
left = middle+1;
}
else
{
right = middle1;
}
}
return(1);
}
Note that the Binary Search algorithm has a prerequisite that the array passed to it must be already sorted in ascending order. This will not work on an unsorted array. The complexity of this algorithm is O(log(n)).
int binarySearch(int arr[],int size, int item)
{
int left, right, middle;
left = 0;
right = size1;
while(left <= right)
{
middle = ((left + right)/2);
if(item == arr[middle])
{
return(middle);
}
if(item > arr[middle])
{
left = middle+1;
}
else
{
right = middle1;
}
}
return(1);
}
Note that the Binary Search algorithm has a prerequisite that the array passed to it must be already sorted in ascending order. This will not work on an unsorted array. The complexity of this algorithm is O(log(n)).
Write a C program to check for palindromes.
An example of a palidrome is "avon sees nova"
There a number of ways in which we can find out if a string is a palidrome or not. Here are a few sample C programs...
Method1
#include < stdio.h >
#include < string.h >
#include < stdlib.h >
#include < ctype.h >
void isPalindrome(char *string);
int main()
{
isPalindrome("avon sees nova");
isPalindrome("a");
isPalindrome("avon sies nova");
isPalindrome("aa");
isPalindrome("abc");
isPalindrome("aba");
isPalindrome("3a2");
exit(0);
}
void isPalindrome(char *string)
{
char *start, *end;
if(string)
{
start = string;
end = string + strlen(string)  1;
while((*start == *end) && (start!=end))
{
if(start < end)start++;
if(end > start)end;
}
if(*start!=*end)
{
printf("\n[%s]  This is not a palidrome!\n", string);
}
else
{
printf("\n[%s]  This is a palidrome!\n", string);
}
}
printf("\n\n");
}
Method2
#include < stdio.h >
#include < string.h >
#include < stdlib.h >
#include < ctype.h >
int isPalindrome(char string[]);
int main()
{
isPalindrome("avon sees nova");
isPalindrome("a");
isPalindrome("avon sies nova");
isPalindrome("aa");
isPalindrome("abc");
isPalindrome("aba");
isPalindrome("3a2");
return(0);
}
int isPalindrome(char string[])
{
int count, countback, end, N;
N = strlen(string);
end = N1;
for((count=0, countback = end); count <= (end/2); ++count,countback)
{
if(string[count]!=string[countback])
{
return(1);
}
}
printf("\n[%s] is a palidrome!\n", string);
return(0);
}
There a number of ways in which we can find out if a string is a palidrome or not. Here are a few sample C programs...
Method1
#include < stdio.h >
#include < string.h >
#include < stdlib.h >
#include < ctype.h >
void isPalindrome(char *string);
int main()
{
isPalindrome("avon sees nova");
isPalindrome("a");
isPalindrome("avon sies nova");
isPalindrome("aa");
isPalindrome("abc");
isPalindrome("aba");
isPalindrome("3a2");
exit(0);
}
void isPalindrome(char *string)
{
char *start, *end;
if(string)
{
start = string;
end = string + strlen(string)  1;
while((*start == *end) && (start!=end))
{
if(start < end)start++;
if(end > start)end;
}
if(*start!=*end)
{
printf("\n[%s]  This is not a palidrome!\n", string);
}
else
{
printf("\n[%s]  This is a palidrome!\n", string);
}
}
printf("\n\n");
}
Method2
#include < stdio.h >
#include < string.h >
#include < stdlib.h >
#include < ctype.h >
int isPalindrome(char string[]);
int main()
{
isPalindrome("avon sees nova");
isPalindrome("a");
isPalindrome("avon sies nova");
isPalindrome("aa");
isPalindrome("abc");
isPalindrome("aba");
isPalindrome("3a2");
return(0);
}
int isPalindrome(char string[])
{
int count, countback, end, N;
N = strlen(string);
end = N1;
for((count=0, countback = end); count <= (end/2); ++count,countback)
{
if(string[count]!=string[countback])
{
return(1);
}
}
printf("\n[%s] is a palidrome!\n", string);
return(0);
}
Write a C program to multiply two matrices.
Are you sure you know this? A lot of people think they already know this, but guess what? So take a good look at this C program. Its asked in most of the interviews as a warm up question.
// Matrix A (m*n)
// Matrix B (n*k)
// Matrix C (m*k)
for(i=0; i < m; i++)
{
for(j=0;j < k;j++)
{
c[i][j]=0;
for(l=0;l < n;l++)
c[i][j] += a[i][l] * b[l][j];
}
}
// Matrix A (m*n)
// Matrix B (n*k)
// Matrix C (m*k)
for(i=0; i < m; i++)
{
for(j=0;j < k;j++)
{
c[i][j]=0;
for(l=0;l < n;l++)
c[i][j] += a[i][l] * b[l][j];
}
}
How would you find the size of structure without using sizeof()?
Try using pointers
struct MyStruct
{
int i;
int j;
};
int main()
{
struct MyStruct *p=0;
int size = ((char*)(p+1))((char*)p);
printf("\nSIZE : [%d]\nSIZE : [%d]\n", size);
return 0;
}
struct MyStruct
{
int i;
int j;
};
int main()
{
struct MyStruct *p=0;
int size = ((char*)(p+1))((char*)p);
printf("\nSIZE : [%d]\nSIZE : [%d]\n", size);
return 0;
}
Write C code to dynamically allocate one, two and three dimensional arrays (using malloc()).
Its pretty simple to do this in the C language if you know how to use C pointers. Here are some example C code snipptes....
One dimensional array
int *myarray = malloc(no_of_elements * sizeof(int));
//Access elements as myarray[i]
Two dimensional array
Method1
int **myarray = (int **)malloc(no_of_rows * sizeof(int *));
for(i = 0; i < no_of_rows; i++)
{
myarray[i] = malloc(no_of_columns * sizeof(int));
}
// Access elements as myarray[i][j]
Method2 (keep the array's contents contiguous)
int **myarray = (int **)malloc(no_of_rows * sizeof(int *));
myarray[0] = malloc(no_of_rows * no_of_columns * sizeof(int));
for(i = 1; i < no_of_rows; i++)
myarray[i] = myarray[0] + (i * no_of_columns);
// Access elements as myarray[i][j]
Method3
int *myarray = malloc(no_of_rows * no_of_columns * sizeof(int));
// Access elements using myarray[i * no_of_columns + j].
Three dimensional array
#define MAXX 3
#define MAXY 4
#define MAXZ 5
main()
{
int ***p,i,j;
p=(int ***) malloc(MAXX * sizeof(int ***));
for(i=0;i < MAXX;i++)
{
p[i]=(int **)malloc(MAXY * sizeof(int *));
for(j=0;j < MAXY;j++)
p[i][j]=(int *)malloc(MAXZ * sizeof(int));
}
for(k=0;k < MAXZ;k++)
for(i=0;i < MAXX;i++)
for(j=0;j < MAXY;j++)
p[i][j][k]= < something >;
}
One dimensional array
int *myarray = malloc(no_of_elements * sizeof(int));
//Access elements as myarray[i]
Two dimensional array
Method1
int **myarray = (int **)malloc(no_of_rows * sizeof(int *));
for(i = 0; i < no_of_rows; i++)
{
myarray[i] = malloc(no_of_columns * sizeof(int));
}
// Access elements as myarray[i][j]
Method2 (keep the array's contents contiguous)
int **myarray = (int **)malloc(no_of_rows * sizeof(int *));
myarray[0] = malloc(no_of_rows * no_of_columns * sizeof(int));
for(i = 1; i < no_of_rows; i++)
myarray[i] = myarray[0] + (i * no_of_columns);
// Access elements as myarray[i][j]
Method3
int *myarray = malloc(no_of_rows * no_of_columns * sizeof(int));
// Access elements using myarray[i * no_of_columns + j].
Three dimensional array
#define MAXX 3
#define MAXY 4
#define MAXZ 5
main()
{
int ***p,i,j;
p=(int ***) malloc(MAXX * sizeof(int ***));
for(i=0;i < MAXX;i++)
{
p[i]=(int **)malloc(MAXY * sizeof(int *));
for(j=0;j < MAXY;j++)
p[i][j]=(int *)malloc(MAXZ * sizeof(int));
}
for(k=0;k < MAXZ;k++)
for(i=0;i < MAXX;i++)
for(j=0;j < MAXY;j++)
p[i][j][k]= < something >;
}
How do you initialize a pointer inside a function?
This is one of the very popular interview questions, so take a good look at it!.
myfunction(int *ptr)
{
int myvar = 100;
ptr = &myvar;
}
main()
{
int *myptr;
myfunction(myptr);
//Use pointer myptr.
}
Do you think this works? It does not!.
Arguments in C are passed by value. The called function changed the passed copy of the pointer, and not the actual pointer.
There are two ways around this problem
Method1
Pass in the address of the pointer to the function (the function needs to accept a pointertoapointer).
calling_function()
{
char *string;
return_string(/* Pass the address of the pointer */&string);
printf(?\n[%s]\n?, string);
}
boolean return_string(char **mode_string /*Pointer to a pointer! */)
{
*string = (char *) malloc(100 * sizeof(char)); // Allocate memory to the pointer passed, not its copy.
DISCARD strcpy((char *)*string, (char *)?Something?);
}
Method2
Make the function return the pointer.
char *myfunc()
{
char *temp = "string";
return temp;
}
int main()
{
puts(myfunc());
}
myfunction(int *ptr)
{
int myvar = 100;
ptr = &myvar;
}
main()
{
int *myptr;
myfunction(myptr);
//Use pointer myptr.
}
Do you think this works? It does not!.
Arguments in C are passed by value. The called function changed the passed copy of the pointer, and not the actual pointer.
There are two ways around this problem
Method1
Pass in the address of the pointer to the function (the function needs to accept a pointertoapointer).
calling_function()
{
char *string;
return_string(/* Pass the address of the pointer */&string);
printf(?\n[%s]\n?, string);
}
boolean return_string(char **mode_string /*Pointer to a pointer! */)
{
*string = (char *) malloc(100 * sizeof(char)); // Allocate memory to the pointer passed, not its copy.
DISCARD strcpy((char *)*string, (char *)?Something?);
}
Method2
Make the function return the pointer.
char *myfunc()
{
char *temp = "string";
return temp;
}
int main()
{
puts(myfunc());
}
Sunday, July 8, 2007
Write code to remove duplicates in a sorted array.
There are a number of ways to remove duplicates from a sorted array. Here are a few C programs...
Method1
In this simple C program, we change the original array and also send the new size of the array back to the caller.
#include < stdio.h >
int removeDuplicates(int a[], int array_size);
// The main function
int main()
{
// Different test cases..
int my_array1[] = {1, 1, 2, 3, 5, 6, 6, 7, 10, 25, 100, 123, 123};
int my_array1_size = 13;
int my_array2[] = {1, 2, 3, 5, 6};
int my_array2_size = 5;
int my_array3[] = {1, 1, 1, 1, 1};
int my_array3_size = 5;
int my_array4[] = {123, 123};
int my_array4_size = 2;
int my_array5[] = {1, 123, 123};
int my_array5_size = 3;
int my_array6[] = {123, 123, 166};
int my_array6_size = 3;
int my_array7[] = {1, 2, 8, 8 , 24, 60, 60, 60, 60, 75, 100, 100, 123};
int my_array7_size = 13;
my_array1_size = removeDuplicates(my_array1, my_array1_size);
my_array2_size = removeDuplicates(my_array2, my_array2_size);
my_array3_size = removeDuplicates(my_array3, my_array3_size);
my_array4_size = removeDuplicates(my_array4, my_array4_size);
my_array5_size = removeDuplicates(my_array5, my_array5_size);
my_array6_size = removeDuplicates(my_array6, my_array6_size);
my_array7_size = removeDuplicates(my_array7, my_array7_size);
return(0);
}
// Function to remove the duplicates
int removeDuplicates(int a[], int array_size)
{
int i, j;
j = 0;
// Print old array...
printf("\n\nOLD : ");
for(i = 0; i < array_size; i++)
{
printf("[%d] ", a[i]);
}
// Remove the duplicates ...
for (i = 1; i < array_size; i++)
{
if (a[i] != a[j])
{
j++;
a[j] = a[i]; // Move it to the front
}
}
// The new array size..
array_size = (j + 1);
// Print new array...
printf("\n\nNEW : ");
for(i = 0; i < array_size; i++)
{
printf("[%d] ", a[i]);
}
printf("\n\n");
// Return the new size...
return(j + 1);
}
And here is the output...
OLD : [1] [1] [2] [3] [5] [6] [6] [7] [10] [25] [100] [123] [123]
NEW : [1] [2] [3] [5] [6] [7] [10] [25] [100] [123]
OLD : [1] [2] [3] [5] [6]
NEW : [1] [2] [3] [5] [6]
OLD : [1] [1] [1] [1] [1]
NEW : [1]
OLD : [123] [123]
NEW : [123]
OLD : [1] [123] [123]
NEW : [1] [123]
OLD : [123] [123] [166]
NEW : [123] [166]
OLD : [1] [2] [8] [8] [24] [60] [60] [60] [60] [75] [100] [100] [123]
NEW : [1] [2] [8] [24] [60] [75] [100] [123]
Method2
If we dont want to change the input array and just want to print the array without any duplicates, the solution is very simple. Check out the removeDuplicatesNoModify() function in the program below. It keeps a track of the most recently seen number and does not print any duplicates of it when traversing the sorted array.
#include < stdio.h >
void removeDuplicatesNoModify(int my_array[], int my_array1_size);
void print_array(int array[], int array_size, int current_pos, int dup_start, int dup_end);
// The main function
int main()
{
// Different inputs...
int my_array1[] = {1, 1, 2, 3, 5, 6, 6, 7, 10, 25, 100, 123, 123};
int my_array1_size = 13;
int my_array2[] = {1, 2, 3, 5, 6};
int my_array2_size = 5;
int my_array3[] = {1, 1, 1, 1, 1};
int my_array3_size = 5;
int my_array4[] = {123, 123};
int my_array4_size = 2;
int my_array5[] = {1, 123, 123};
int my_array5_size = 3;
int my_array6[] = {123, 123, 166};
int my_array6_size = 3;
int my_array7[] = {1, 2, 8, 8 , 24, 60, 60, 60, 60, 75, 100, 100, 123};
int my_array7_size = 13;
removeDuplicatesNoModify(my_array1, my_array1_size);
removeDuplicatesNoModify(my_array2, my_array2_size);
removeDuplicatesNoModify(my_array3, my_array3_size);
removeDuplicatesNoModify(my_array4, my_array4_size);
removeDuplicatesNoModify(my_array5, my_array5_size);
removeDuplicatesNoModify(my_array6, my_array6_size);
removeDuplicatesNoModify(my_array7, my_array7_size);
return(0);
}
// This function just prints the array without duplicates.
// It does not modify the original array!
void removeDuplicatesNoModify(int array[], int array_size)
{
int i, last_seen_unique;
if(array_size <= 1){return;}
last_seen_unique = array[0];
printf("\n\nOld : ", array_size);
for(i = 0; i < array_size; i++)
{
printf("[%2d] ", array[i]);
}
printf("\nNew : ", array_size);
printf("[%2d] ", array[0]);
for(i=1; i < array_size; i++)
{
if(array[i]!=last_seen_unique)
{
printf("[%2d] ", array[i]);
last_seen_unique = array[i];
}
}
printf("\n");
}
And here is the output..
Old : [ 1] [ 1] [ 2] [ 3] [ 5] [ 6] [ 6] [ 7] [10] [25] [100] [123] [123]
New : [ 1] [ 2] [ 3] [ 5] [ 6] [ 7] [10] [25] [100] [123]
Old : [ 1] [ 2] [ 3] [ 5] [ 6]
New : [ 1] [ 2] [ 3] [ 5] [ 6]
Old : [ 1] [ 1] [ 1] [ 1] [ 1]
New : [ 1]
Old : [123] [123]
New : [123]
Old : [ 1] [123] [123]
New : [ 1] [123]
Old : [123] [123] [166]
New : [123] [166]
Old : [ 1] [ 2] [ 8] [ 8] [24] [60] [60] [60] [60] [75] [100] [100] [123]
New : [ 1] [ 2] [ 8] [24] [60] [75] [100] [123]
Method3
Here is a slightly compilcated, but more visual version of the removeDuplicates() function. It shrinks the original array as and when it find duplicates. It is also optimized to identify continuous strings of duplicates and eliminate them at one shot.
#include < stdio.h >
void removeDuplicates(int array[], int *array_size) ;
void print_array(int array[], int array_size, int current_pos, int dup_start, int dup_end);
// The main function
int main()
{
// Different inputs...
int my_array1[] = {1, 1, 2, 3, 5, 6, 6, 7, 10, 25, 100, 123, 123};
int my_array1_size = 13;
int my_array2[] = {1, 2, 3, 5, 6};
int my_array2_size = 5;
int my_array3[] = {1, 1, 1, 1, 1};
int my_array3_size = 5;
int my_array4[] = {123, 123};
int my_array4_size = 2;
int my_array5[] = {1, 123, 123};
int my_array5_size = 3;
int my_array6[] = {123, 123, 166};
int my_array6_size = 3;
int my_array7[] = {1, 2, 8, 8 , 24, 60, 60, 60, 60, 75, 100, 100, 123};
int my_array7_size = 13;
removeDuplicates(my_array1, &my_array1_size);
removeDuplicates(my_array2, &my_array2_size);
removeDuplicates(my_array3, &my_array3_size);
removeDuplicates(my_array4, &my_array4_size);
removeDuplicates(my_array5, &my_array5_size);
removeDuplicates(my_array6, &my_array6_size);
removeDuplicates(my_array7, &my_array7_size);
return(0);
}
// Changes the original array and resets the size of the array if duplicates
// have been removed.
void removeDuplicates(int array[], int *array_size)
{
int i, j, k, l;
int current_pos;
int dup_start;
int dup_end;
printf("\nInitial array (size : [%d])\n\n", *array_size);
for(i = 0; i < *array_size; i++)
{
printf("[%2d] ", array[i]);
}
printf("\n\n\n\n");
if(*array_size == 1){return;}
// Remove the dups...
for (i = 0; (i < *array_size); i++)
{
//Start with the next element in the array and check if its a duplicate...
for(j = i+1; (j < *array_size); j++)
{
if(array[i]!=array[j])
{
// No duplicate, just continue...
break;
}
else
{
// The next element is a duplicate.
// See if there are more duplicates, as we want to optimize here.
//
// That is, if we have something like
//
// Array : [1, 1, 1, 2]
//
// then, we want to copy 2 directly in the second position and reduce the
// array to
//
// Array : [1, 2].
//
// in a single iteration.
current_pos = i;
dup_start = j;
j++;
while((array[i]==array[j]) && (j < *array_size))
{
j++;
}
dup_end = j1;
print_array(array, *array_size, current_pos, dup_start, dup_end);
// Now remove elements of the array from "dup_start" to "dup_end"
// and shrink the size of the array.
for(k = (dup_end + 1), l = dup_start ; k < *array_size;)
{
array[l++]=array[k++];
}
// Reduce the array size by the number of elements removed.
*array_size = *array_size  (dup_end  dup_start + 1);
}
}
}
printf("\n\n");
printf("\n\nFinal array (size : [%d])\n\n", *array_size);
for(i = 0; i < *array_size; i++)
{
printf("[%2d] ", array[i]);
}
printf("\n\n");
}
// This function prints the array with some special pointers to the numbers that
// are duplicated.
//
// Dont bother too much about this function, it just helps in understanding
// how and where the duplicates are being removed from.
void print_array(int array[], int array_size, int current_pos, int dup_start, int dup_end)
{
int i;
printf("\n\n");
for(i = 0; i < array_size; i++)
{
printf("[%2d] ", array[i]);
}
printf("\n");
for(i = 0; i < array_size; i++)
{
if((i == current_pos) 
(i == dup_start && i == dup_end) 
((i == dup_start  i == dup_end) && (dup_start != dup_end)))
{
printf(" ^ ");
}
else
{
printf(" ");
}
}
printf("\n");
for(i = 0; i < array_size; i++)
{
if((i == current_pos) 
(i == dup_start && i == dup_end) 
((i == dup_start  i == dup_end) && (dup_start != dup_end)))
{
printf("  ");
}
else
{
printf(" ");
}
}
printf("\n");
for(i = 0; i < array_size; i++)
{
if(i == current_pos)
{
printf(" C ");
}
else if(i == dup_start && i == dup_end)
{
printf(" S/E ");
}
else if((i == dup_start  i == dup_end) && (dup_start != dup_end))
{
if(i == dup_start)
{
printf(" S");
}
else
{
printf("E ");
}
}
else if(i > dup_start && i < dup_end)
{
printf("");
}
else
{
printf(" ");
}
}
}
And here is the output (for one of the inputs)...
C  Current position.
S  Start of duplicates.
E  End of duplicates.
Old : [ 1] [ 2] [ 8] [ 8] [24] [60] [60] [60] [60] [75] [100] [100] [123]

[ 1] [ 2] [ 8 (C) ] [ 8 (S/E) ] [24] [60] [60] [60] [60] [75] [100] [100] [123]
[ 1] [ 2] [ 8] [24] [60 (C)] [60 (S)] [60 (E)] [60] [75] [100] [100] [123]
[ 1] [ 2] [ 8] [24] [60] [75] [100 (C)] [100 (S/E)] [123]

New : [ 1] [ 2] [ 8] [24] [60] [75] [100] [123]
If there are other elegant methods of removing duplicate numbers from an array, please let me know!.
Method1
In this simple C program, we change the original array and also send the new size of the array back to the caller.
#include < stdio.h >
int removeDuplicates(int a[], int array_size);
// The main function
int main()
{
// Different test cases..
int my_array1[] = {1, 1, 2, 3, 5, 6, 6, 7, 10, 25, 100, 123, 123};
int my_array1_size = 13;
int my_array2[] = {1, 2, 3, 5, 6};
int my_array2_size = 5;
int my_array3[] = {1, 1, 1, 1, 1};
int my_array3_size = 5;
int my_array4[] = {123, 123};
int my_array4_size = 2;
int my_array5[] = {1, 123, 123};
int my_array5_size = 3;
int my_array6[] = {123, 123, 166};
int my_array6_size = 3;
int my_array7[] = {1, 2, 8, 8 , 24, 60, 60, 60, 60, 75, 100, 100, 123};
int my_array7_size = 13;
my_array1_size = removeDuplicates(my_array1, my_array1_size);
my_array2_size = removeDuplicates(my_array2, my_array2_size);
my_array3_size = removeDuplicates(my_array3, my_array3_size);
my_array4_size = removeDuplicates(my_array4, my_array4_size);
my_array5_size = removeDuplicates(my_array5, my_array5_size);
my_array6_size = removeDuplicates(my_array6, my_array6_size);
my_array7_size = removeDuplicates(my_array7, my_array7_size);
return(0);
}
// Function to remove the duplicates
int removeDuplicates(int a[], int array_size)
{
int i, j;
j = 0;
// Print old array...
printf("\n\nOLD : ");
for(i = 0; i < array_size; i++)
{
printf("[%d] ", a[i]);
}
// Remove the duplicates ...
for (i = 1; i < array_size; i++)
{
if (a[i] != a[j])
{
j++;
a[j] = a[i]; // Move it to the front
}
}
// The new array size..
array_size = (j + 1);
// Print new array...
printf("\n\nNEW : ");
for(i = 0; i < array_size; i++)
{
printf("[%d] ", a[i]);
}
printf("\n\n");
// Return the new size...
return(j + 1);
}
And here is the output...
OLD : [1] [1] [2] [3] [5] [6] [6] [7] [10] [25] [100] [123] [123]
NEW : [1] [2] [3] [5] [6] [7] [10] [25] [100] [123]
OLD : [1] [2] [3] [5] [6]
NEW : [1] [2] [3] [5] [6]
OLD : [1] [1] [1] [1] [1]
NEW : [1]
OLD : [123] [123]
NEW : [123]
OLD : [1] [123] [123]
NEW : [1] [123]
OLD : [123] [123] [166]
NEW : [123] [166]
OLD : [1] [2] [8] [8] [24] [60] [60] [60] [60] [75] [100] [100] [123]
NEW : [1] [2] [8] [24] [60] [75] [100] [123]
Method2
If we dont want to change the input array and just want to print the array without any duplicates, the solution is very simple. Check out the removeDuplicatesNoModify() function in the program below. It keeps a track of the most recently seen number and does not print any duplicates of it when traversing the sorted array.
#include < stdio.h >
void removeDuplicatesNoModify(int my_array[], int my_array1_size);
void print_array(int array[], int array_size, int current_pos, int dup_start, int dup_end);
// The main function
int main()
{
// Different inputs...
int my_array1[] = {1, 1, 2, 3, 5, 6, 6, 7, 10, 25, 100, 123, 123};
int my_array1_size = 13;
int my_array2[] = {1, 2, 3, 5, 6};
int my_array2_size = 5;
int my_array3[] = {1, 1, 1, 1, 1};
int my_array3_size = 5;
int my_array4[] = {123, 123};
int my_array4_size = 2;
int my_array5[] = {1, 123, 123};
int my_array5_size = 3;
int my_array6[] = {123, 123, 166};
int my_array6_size = 3;
int my_array7[] = {1, 2, 8, 8 , 24, 60, 60, 60, 60, 75, 100, 100, 123};
int my_array7_size = 13;
removeDuplicatesNoModify(my_array1, my_array1_size);
removeDuplicatesNoModify(my_array2, my_array2_size);
removeDuplicatesNoModify(my_array3, my_array3_size);
removeDuplicatesNoModify(my_array4, my_array4_size);
removeDuplicatesNoModify(my_array5, my_array5_size);
removeDuplicatesNoModify(my_array6, my_array6_size);
removeDuplicatesNoModify(my_array7, my_array7_size);
return(0);
}
// This function just prints the array without duplicates.
// It does not modify the original array!
void removeDuplicatesNoModify(int array[], int array_size)
{
int i, last_seen_unique;
if(array_size <= 1){return;}
last_seen_unique = array[0];
printf("\n\nOld : ", array_size);
for(i = 0; i < array_size; i++)
{
printf("[%2d] ", array[i]);
}
printf("\nNew : ", array_size);
printf("[%2d] ", array[0]);
for(i=1; i < array_size; i++)
{
if(array[i]!=last_seen_unique)
{
printf("[%2d] ", array[i]);
last_seen_unique = array[i];
}
}
printf("\n");
}
And here is the output..
Old : [ 1] [ 1] [ 2] [ 3] [ 5] [ 6] [ 6] [ 7] [10] [25] [100] [123] [123]
New : [ 1] [ 2] [ 3] [ 5] [ 6] [ 7] [10] [25] [100] [123]
Old : [ 1] [ 2] [ 3] [ 5] [ 6]
New : [ 1] [ 2] [ 3] [ 5] [ 6]
Old : [ 1] [ 1] [ 1] [ 1] [ 1]
New : [ 1]
Old : [123] [123]
New : [123]
Old : [ 1] [123] [123]
New : [ 1] [123]
Old : [123] [123] [166]
New : [123] [166]
Old : [ 1] [ 2] [ 8] [ 8] [24] [60] [60] [60] [60] [75] [100] [100] [123]
New : [ 1] [ 2] [ 8] [24] [60] [75] [100] [123]
Method3
Here is a slightly compilcated, but more visual version of the removeDuplicates() function. It shrinks the original array as and when it find duplicates. It is also optimized to identify continuous strings of duplicates and eliminate them at one shot.
#include < stdio.h >
void removeDuplicates(int array[], int *array_size) ;
void print_array(int array[], int array_size, int current_pos, int dup_start, int dup_end);
// The main function
int main()
{
// Different inputs...
int my_array1[] = {1, 1, 2, 3, 5, 6, 6, 7, 10, 25, 100, 123, 123};
int my_array1_size = 13;
int my_array2[] = {1, 2, 3, 5, 6};
int my_array2_size = 5;
int my_array3[] = {1, 1, 1, 1, 1};
int my_array3_size = 5;
int my_array4[] = {123, 123};
int my_array4_size = 2;
int my_array5[] = {1, 123, 123};
int my_array5_size = 3;
int my_array6[] = {123, 123, 166};
int my_array6_size = 3;
int my_array7[] = {1, 2, 8, 8 , 24, 60, 60, 60, 60, 75, 100, 100, 123};
int my_array7_size = 13;
removeDuplicates(my_array1, &my_array1_size);
removeDuplicates(my_array2, &my_array2_size);
removeDuplicates(my_array3, &my_array3_size);
removeDuplicates(my_array4, &my_array4_size);
removeDuplicates(my_array5, &my_array5_size);
removeDuplicates(my_array6, &my_array6_size);
removeDuplicates(my_array7, &my_array7_size);
return(0);
}
// Changes the original array and resets the size of the array if duplicates
// have been removed.
void removeDuplicates(int array[], int *array_size)
{
int i, j, k, l;
int current_pos;
int dup_start;
int dup_end;
printf("\nInitial array (size : [%d])\n\n", *array_size);
for(i = 0; i < *array_size; i++)
{
printf("[%2d] ", array[i]);
}
printf("\n\n\n\n");
if(*array_size == 1){return;}
// Remove the dups...
for (i = 0; (i < *array_size); i++)
{
//Start with the next element in the array and check if its a duplicate...
for(j = i+1; (j < *array_size); j++)
{
if(array[i]!=array[j])
{
// No duplicate, just continue...
break;
}
else
{
// The next element is a duplicate.
// See if there are more duplicates, as we want to optimize here.
//
// That is, if we have something like
//
// Array : [1, 1, 1, 2]
//
// then, we want to copy 2 directly in the second position and reduce the
// array to
//
// Array : [1, 2].
//
// in a single iteration.
current_pos = i;
dup_start = j;
j++;
while((array[i]==array[j]) && (j < *array_size))
{
j++;
}
dup_end = j1;
print_array(array, *array_size, current_pos, dup_start, dup_end);
// Now remove elements of the array from "dup_start" to "dup_end"
// and shrink the size of the array.
for(k = (dup_end + 1), l = dup_start ; k < *array_size;)
{
array[l++]=array[k++];
}
// Reduce the array size by the number of elements removed.
*array_size = *array_size  (dup_end  dup_start + 1);
}
}
}
printf("\n\n");
printf("\n\nFinal array (size : [%d])\n\n", *array_size);
for(i = 0; i < *array_size; i++)
{
printf("[%2d] ", array[i]);
}
printf("\n\n");
}
// This function prints the array with some special pointers to the numbers that
// are duplicated.
//
// Dont bother too much about this function, it just helps in understanding
// how and where the duplicates are being removed from.
void print_array(int array[], int array_size, int current_pos, int dup_start, int dup_end)
{
int i;
printf("\n\n");
for(i = 0; i < array_size; i++)
{
printf("[%2d] ", array[i]);
}
printf("\n");
for(i = 0; i < array_size; i++)
{
if((i == current_pos) 
(i == dup_start && i == dup_end) 
((i == dup_start  i == dup_end) && (dup_start != dup_end)))
{
printf(" ^ ");
}
else
{
printf(" ");
}
}
printf("\n");
for(i = 0; i < array_size; i++)
{
if((i == current_pos) 
(i == dup_start && i == dup_end) 
((i == dup_start  i == dup_end) && (dup_start != dup_end)))
{
printf("  ");
}
else
{
printf(" ");
}
}
printf("\n");
for(i = 0; i < array_size; i++)
{
if(i == current_pos)
{
printf(" C ");
}
else if(i == dup_start && i == dup_end)
{
printf(" S/E ");
}
else if((i == dup_start  i == dup_end) && (dup_start != dup_end))
{
if(i == dup_start)
{
printf(" S");
}
else
{
printf("E ");
}
}
else if(i > dup_start && i < dup_end)
{
printf("");
}
else
{
printf(" ");
}
}
}
And here is the output (for one of the inputs)...
C  Current position.
S  Start of duplicates.
E  End of duplicates.
Old : [ 1] [ 2] [ 8] [ 8] [24] [60] [60] [60] [60] [75] [100] [100] [123]

[ 1] [ 2] [ 8 (C) ] [ 8 (S/E) ] [24] [60] [60] [60] [60] [75] [100] [100] [123]
[ 1] [ 2] [ 8] [24] [60 (C)] [60 (S)] [60 (E)] [60] [75] [100] [100] [123]
[ 1] [ 2] [ 8] [24] [60] [75] [100 (C)] [100 (S/E)] [123]

New : [ 1] [ 2] [ 8] [24] [60] [75] [100] [123]
If there are other elegant methods of removing duplicate numbers from an array, please let me know!.
Finding a duplicated integer problem.
Given an array of n integers from 1 to n with one integer repeated..
Here is the simplest of C programs (kind of dumb)
#include < stdio.h >
#include < stdlib.h >
#include < conio.h >
int i,j=0,k,a1[10];
main()
{
printf("Enter the array of numbers between 1 and 100(you can repeat the numbers):");
for(i=0;i <= 9;i++)
{
scanf("%d",&a1[i]);
}
while(j < 10)
{
for(k=0;k < 10;k++)
{
if(a1[j]==a1[k] && j!=k)
{
printf("Duplicate found!");
printf("The duplicate is %d\n",a1[j]);
getch();
}
}
j=j+1;
}
getch();
return(0);
}
Here is the simplest of C programs (kind of dumb)
#include < stdio.h >
#include < stdlib.h >
#include < conio.h >
int i,j=0,k,a1[10];
main()
{
printf("Enter the array of numbers between 1 and 100(you can repeat the numbers):");
for(i=0;i <= 9;i++)
{
scanf("%d",&a1[i]);
}
while(j < 10)
{
for(k=0;k < 10;k++)
{
if(a1[j]==a1[k] && j!=k)
{
printf("Duplicate found!");
printf("The duplicate is %d\n",a1[j]);
getch();
}
}
j=j+1;
}
getch();
return(0);
}
Write a C program to find the GCD of two numbers.
Here is a C program ....
#include < stdio.h >
int gcd(int a, int b);
int gcd_recurse(int a, int b);
int main()
{
printf("\nGCD(%2d,%2d) = [%d]", 6,4, gcd(6,4));
printf("\nGCD(%2d,%2d) = [%d]", 4,6, gcd(4,6));
printf("\nGCD(%2d,%2d) = [%d]", 3,17, gcd(3,17));
printf("\nGCD(%2d,%2d) = [%d]", 17,3, gcd(17,3));
printf("\nGCD(%2d,%2d) = [%d]", 1,6, gcd(1,6));
printf("\nGCD(%2d,%2d) = [%d]", 10,1, gcd(10,1));
printf("\nGCD(%2d,%2d) = [%d]", 10,6, gcd(10,6));
printf("\nGCD(%2d,%2d) = [%d]", 6,4, gcd_recurse(6,4));
printf("\nGCD(%2d,%2d) = [%d]", 4,6, gcd_recurse(4,6));
printf("\nGCD(%2d,%2d) = [%d]", 3,17, gcd_recurse(3,17));
printf("\nGCD(%2d,%2d) = [%d]", 17,3, gcd_recurse(17,3));
printf("\nGCD(%2d,%2d) = [%d]", 1,6, gcd_recurse(1,6));
printf("\nGCD(%2d,%2d) = [%d]", 10,1, gcd_recurse(10,1));
printf("\nGCD(%2d,%2d) = [%d]", 10,6, gcd_recurse(10,6));
getch();
getch();
return(0);
}
// Iterative algorithm
int gcd(int a, int b)
{
int temp;
while(b)
{
temp = a % b;
a = b;
b = temp;
}
return(a);
}
// Recursive algorithm
int gcd_recurse(int a, int b)
{
int temp;
temp = a % b;
if (temp == 0)
{
return(b);
}
else
{
return(gcd_recurse(b, temp));
}
}
And here is the output ...
Iterative

GCD( 6, 4) = [2]
GCD( 4, 6) = [2]
GCD( 3,17) = [1]
GCD(17, 3) = [1]
GCD( 1, 6) = [1]
GCD(10, 1) = [1]
GCD(10, 6) = [2]
Recursive

GCD( 6, 4) = [2]
GCD( 4, 6) = [2]
GCD( 3,17) = [1]
GCD(17, 3) = [1]
GCD( 1, 6) = [1]
GCD(10, 1) = [1]
GCD(10, 6) = [2]
Note that you should add error handling to check if someone has passed negative numbers and zero.
#include < stdio.h >
int gcd(int a, int b);
int gcd_recurse(int a, int b);
int main()
{
printf("\nGCD(%2d,%2d) = [%d]", 6,4, gcd(6,4));
printf("\nGCD(%2d,%2d) = [%d]", 4,6, gcd(4,6));
printf("\nGCD(%2d,%2d) = [%d]", 3,17, gcd(3,17));
printf("\nGCD(%2d,%2d) = [%d]", 17,3, gcd(17,3));
printf("\nGCD(%2d,%2d) = [%d]", 1,6, gcd(1,6));
printf("\nGCD(%2d,%2d) = [%d]", 10,1, gcd(10,1));
printf("\nGCD(%2d,%2d) = [%d]", 10,6, gcd(10,6));
printf("\nGCD(%2d,%2d) = [%d]", 6,4, gcd_recurse(6,4));
printf("\nGCD(%2d,%2d) = [%d]", 4,6, gcd_recurse(4,6));
printf("\nGCD(%2d,%2d) = [%d]", 3,17, gcd_recurse(3,17));
printf("\nGCD(%2d,%2d) = [%d]", 17,3, gcd_recurse(17,3));
printf("\nGCD(%2d,%2d) = [%d]", 1,6, gcd_recurse(1,6));
printf("\nGCD(%2d,%2d) = [%d]", 10,1, gcd_recurse(10,1));
printf("\nGCD(%2d,%2d) = [%d]", 10,6, gcd_recurse(10,6));
getch();
getch();
return(0);
}
// Iterative algorithm
int gcd(int a, int b)
{
int temp;
while(b)
{
temp = a % b;
a = b;
b = temp;
}
return(a);
}
// Recursive algorithm
int gcd_recurse(int a, int b)
{
int temp;
temp = a % b;
if (temp == 0)
{
return(b);
}
else
{
return(gcd_recurse(b, temp));
}
}
And here is the output ...
Iterative

GCD( 6, 4) = [2]
GCD( 4, 6) = [2]
GCD( 3,17) = [1]
GCD(17, 3) = [1]
GCD( 1, 6) = [1]
GCD(10, 1) = [1]
GCD(10, 6) = [2]
Recursive

GCD( 6, 4) = [2]
GCD( 4, 6) = [2]
GCD( 3,17) = [1]
GCD(17, 3) = [1]
GCD( 1, 6) = [1]
GCD(10, 1) = [1]
GCD(10, 6) = [2]
Note that you should add error handling to check if someone has passed negative numbers and zero.
Write C code to check if an integer is a power of 2 or not in a single line?
Even this is one of the most frequently asked interview questions. I really dont know whats so great in it. Nevertheless, here is a C program
Method1
if(!(num & (num  1)) && num)
{
// Power of 2!
}
Method2
if(((~i+1)&i)==i)
{
//Power of 2!
}
I leave it up to you to find out how these statements work.
Method1
if(!(num & (num  1)) && num)
{
// Power of 2!
}
Method2
if(((~i+1)&i)==i)
{
//Power of 2!
}
I leave it up to you to find out how these statements work.
Write a C progam to convert from decimal to any base (binary, hex, oct etc...).
Here is some really cool C code
#include < stdio.h >
int main()
{
decimal_to_anybase(10, 2);
decimal_to_anybase(255, 16);
getch();
}
decimal_to_anybase(int n, int base)
{
int i, m, digits[1000], flag;
i=0;
printf("\n\n[%d] converted to base [%d] : ", n, base);
while(n)
{
m=n%base;
digits[i]="0123456789abcdefghijklmnopqrstuvwxyz"[m];
n=n/base;
i++;
}
//Eliminate any leading zeroes
for(i;i >= 0;i)
{
if(!flag && digits[i]!='0')flag=1;
if(flag)printf("%c",digits[i]);
}
}
#include < stdio.h >
int main()
{
decimal_to_anybase(10, 2);
decimal_to_anybase(255, 16);
getch();
}
decimal_to_anybase(int n, int base)
{
int i, m, digits[1000], flag;
i=0;
printf("\n\n[%d] converted to base [%d] : ", n, base);
while(n)
{
m=n%base;
digits[i]="0123456789abcdefghijklmnopqrstuvwxyz"[m];
n=n/base;
i++;
}
//Eliminate any leading zeroes
for(i;i >= 0;i)
{
if(!flag && digits[i]!='0')flag=1;
if(flag)printf("%c",digits[i]);
}
}
Write a C program which produces its own source code as its output.
This is one of the most famous interview questions
One of the famous C programs is...
char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";main(){printf(s,34,s,34);}
So how does it work?
It's not difficult to understand this program. In the following statement,
printf(f,34,f,34,10);
the parameter "f" not only acts as the format string, but also as a value for the %s specifier. The ASCII value of double quotes is 34, and that of newline is 10. With these fact ready, the solution is just a matter of tracing the program.
One of the famous C programs is...
char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";main(){printf(s,34,s,34);}
So how does it work?
It's not difficult to understand this program. In the following statement,
printf(f,34,f,34,10);
the parameter "f" not only acts as the format string, but also as a value for the %s specifier. The ASCII value of double quotes is 34, and that of newline is 10. With these fact ready, the solution is just a matter of tracing the program.
Write C code to return a string from a function.
This is one of the most popular interview questions
This C program wont work!
char *myfunction(int n)
{
char buffer[20];
sprintf(buffer, "%d", n);
return retbuf;
}
This wont work either!
char *myfunc1()
{
char temp[] = "string";
return temp;
}
char *myfunc2()
{
char temp[] = {'s', 't', 'r', 'i', 'n', 'g', '\0'};
return temp;
}
int main()
{
puts(myfunc1());
puts(myfunc2());
}
The returned pointer should be to a static buffer (like static char buffer[20];), or to a buffer passed in by the caller function, or to memory obtained using malloc(), but not to a local array.
This will work
char *myfunc()
{
char *temp = "string";
return temp;
}
int main()
{
puts(someFun());
}
So will this
calling_function()
{
char *string;
return_string(&string);
printf(?\n[%s]\n?, string);
}
boolean return_string(char **mode_string /*Pointer to a pointer! */)
{
*string = (char *) malloc(100 * sizeof(char));
DISCARD strcpy((char *)*string, (char *)?Something?);
}
This C program wont work!
char *myfunction(int n)
{
char buffer[20];
sprintf(buffer, "%d", n);
return retbuf;
}
This wont work either!
char *myfunc1()
{
char temp[] = "string";
return temp;
}
char *myfunc2()
{
char temp[] = {'s', 't', 'r', 'i', 'n', 'g', '\0'};
return temp;
}
int main()
{
puts(myfunc1());
puts(myfunc2());
}
The returned pointer should be to a static buffer (like static char buffer[20];), or to a buffer passed in by the caller function, or to memory obtained using malloc(), but not to a local array.
This will work
char *myfunc()
{
char *temp = "string";
return temp;
}
int main()
{
puts(someFun());
}
So will this
calling_function()
{
char *string;
return_string(&string);
printf(?\n[%s]\n?, string);
}
boolean return_string(char **mode_string /*Pointer to a pointer! */)
{
*string = (char *) malloc(100 * sizeof(char));
DISCARD strcpy((char *)*string, (char *)?Something?);
}
Write C code to solve the Tower of Hanoi problem.
Here is an example C program to solve the Tower Of Hanoi problem...
main()
{
towers_of_hanio(n,'L','R','C');
}
towers_of_hanio(int n, char from, char to, char temp)
{
if(n > 0)
{
tower_of_hanio(n1, from, temp, to);
printf("\nMove disk %d from %c to %c\n", n, from, to);
tower_of_hanio(n1, temp, to, from);
}
}
main()
{
towers_of_hanio(n,'L','R','C');
}
towers_of_hanio(int n, char from, char to, char temp)
{
if(n > 0)
{
tower_of_hanio(n1, from, temp, to);
printf("\nMove disk %d from %c to %c\n", n, from, to);
tower_of_hanio(n1, temp, to, from);
}
}
What LittleEndian and BigEndian? How can I determine whether a machine's byte order is bigendian or little endian? How can we convert from one to a
First of all, Do you know what LittleEndian and BigEndian mean?
Little Endian means that the lower order byte of the number is stored in memory at the lowest address, and the higher order byte is stored at the highest address. That is, the little end comes first.
For example, a 4 byte, 32bit integer
Byte3 Byte2 Byte1 Byte0
will be arranged in memory as follows:
Base_Address+0 Byte0
Base_Address+1 Byte1
Base_Address+2 Byte2
Base_Address+3 Byte3
Intel processors use "Little Endian" byte order.
"Big Endian" means that the higher order byte of the number is stored in memory at the lowest address, and the lower order byte at the highest address. The big end comes first.
Base_Address+0 Byte3
Base_Address+1 Byte2
Base_Address+2 Byte1
Base_Address+3 Byte0
Motorola, Solaris processors use "Big Endian" byte order.
In "Little Endian" form, code which picks up a 1, 2, 4, or longer byte number proceed in the same way for all formats. They first pick up the lowest order byte at offset 0 and proceed from there. Also, because of the 1:1 relationship between address offset and byte number (offset 0 is byte 0), multiple precision mathematic routines are easy to code. In "Big Endian" form, since the highorder byte comes first, the code can test whether the number is positive or negative by looking at the byte at offset zero. Its not required to know how long the number is, nor does the code have to skip over any bytes to find the byte containing the sign information. The numbers are also stored in the order in which they are printed out, so binary to decimal routines are particularly efficient.
Here is some code to determine what is the type of your machine
int num = 1;
if(*(char *)&num == 1)
{
printf("\nLittleEndian\n");
}
else
{
printf("BigEndian\n");
}
And here is some code to convert from one Endian to another.
int myreversefunc(int num)
{
int byte0, byte1, byte2, byte3;
byte0 = (num & x000000FF) >> 0 ;
byte1 = (num & x0000FF00) >> 8 ;
byte2 = (num & x00FF0000) >> 16 ;
byte3 = (num & xFF000000) >> 24 ;
return((byte0 << 24)  (byte1 << 16)  (byte2 << 8)  (byte3 << 0));
}
Little Endian means that the lower order byte of the number is stored in memory at the lowest address, and the higher order byte is stored at the highest address. That is, the little end comes first.
For example, a 4 byte, 32bit integer
Byte3 Byte2 Byte1 Byte0
will be arranged in memory as follows:
Base_Address+0 Byte0
Base_Address+1 Byte1
Base_Address+2 Byte2
Base_Address+3 Byte3
Intel processors use "Little Endian" byte order.
"Big Endian" means that the higher order byte of the number is stored in memory at the lowest address, and the lower order byte at the highest address. The big end comes first.
Base_Address+0 Byte3
Base_Address+1 Byte2
Base_Address+2 Byte1
Base_Address+3 Byte0
Motorola, Solaris processors use "Big Endian" byte order.
In "Little Endian" form, code which picks up a 1, 2, 4, or longer byte number proceed in the same way for all formats. They first pick up the lowest order byte at offset 0 and proceed from there. Also, because of the 1:1 relationship between address offset and byte number (offset 0 is byte 0), multiple precision mathematic routines are easy to code. In "Big Endian" form, since the highorder byte comes first, the code can test whether the number is positive or negative by looking at the byte at offset zero. Its not required to know how long the number is, nor does the code have to skip over any bytes to find the byte containing the sign information. The numbers are also stored in the order in which they are printed out, so binary to decimal routines are particularly efficient.
Here is some code to determine what is the type of your machine
int num = 1;
if(*(char *)&num == 1)
{
printf("\nLittleEndian\n");
}
else
{
printf("BigEndian\n");
}
And here is some code to convert from one Endian to another.
int myreversefunc(int num)
{
int byte0, byte1, byte2, byte3;
byte0 = (num & x000000FF) >> 0 ;
byte1 = (num & x0000FF00) >> 8 ;
byte2 = (num & x00FF0000) >> 16 ;
byte3 = (num & xFF000000) >> 24 ;
return((byte0 << 24)  (byte1 << 16)  (byte2 << 8)  (byte3 << 0));
}
Solve the Rat In A Maze problem using backtracking.
This is one of the classical problems of computer science. There is a rat trapped in a maze. There are multiple paths in the maze from the starting point to the ending point. There is some cheese at the exit. The rat starts from the entrance of the maze and wants to get to the cheese.
This problem can be attacked as follows.
Have a m*m matrix which represents the maze.
For the sake of simplifying the implementation, have a boundary around your matrix and fill it up with all ones. This is so that you know when the rat is trying to go out of the boundary of the maze. In the real world, the rat would know not to go out of the maze, but hey! So, initially the matrix (I mean, the maze) would be something like (the ones represent the "exra" boundary we have added). The ones inside specify the obstacles.
111111111111111111111
100000000000000000001
100000010000000000001
100000010000000000001
100000000100001000001
100001000010000000001
100000000100000000001
100000000000000000001
111111111111111111111
The rat can move in four directions at any point in time (well, right, left, up, down). Please note that the rat can't move diagonally. Imagine a real maze and not a matrix. In matrix language
Moving right means adding {0,1} to the current coordinates.
Moving left means adding {0,1} to the current coordinates.
Moving up means adding {1,0} to the current coordinates.
Moving right means adding {1,0} to the current coordinates.
The rat can start off at the first row and the first column as the entrance point.
From there, it tries to move to a cell which is currently free. A cell is free if it has a zero in it.
It tries all the 4 options onebyone, till it finds an empty cell. If it finds one, it moves to that cell and marks it with a 1 (saying it has visited it once). Then it continues to move ahead from that cell to other cells.
If at a particular cell, it runs out of all the 4 options (that is it cant move either right, left, up or down), then it needs to backtrack. It backtracks till a point where it can move ahead and be closer to the exit.
If it reaches the exit point, it gets the cheese, ofcourse.
The complexity is O(m*m).
Here is some pseudocode to chew upon
findpath()
{
Position offset[4];
Offset[0].row=0; offset[0].col=1;//right;
Offset[1].row=1; offset[1].col=0;//down;
Offset[2].row=0; offset[2].col=1;//left;
Offset[3].row=1; offset[3].col=0;//up;
// Initialize wall of obstacles around the maze
for(int i=0; i < m+1;i++)
maze[0][i] = maze[m+1][i]=1; maze[i][0] = maze[i][m+1]=1;
Position here;
Here.row=1;
Here.col=1;
maze[1][1]=1;
int option = 0;
int lastoption = 3;
while(here.row!=m  here.col!=m)
{
//Find a neighbor to move
int r,c;
while (option <= LastOption)
{
r=here.row + offset[position].row;
c=here.col + offset[option].col;
if(maze[r][c]==0)break;
option++;
}
//Was a neighbor found?
if(option <= LastOption)
{
path>Add(here);
here.row=r;here.col=c;
maze[r][c]=1;
option=0;
}
else
{
if(path>Empty())return(False);
Position next;
Path>Delete(next);
If(new.row==here.row)
Option=2+next.col  here.col;
Else { option = 3 + next.row  here.col;}
Here=next;
}
return(TRUE);
}
}
This problem can be attacked as follows.
Have a m*m matrix which represents the maze.
For the sake of simplifying the implementation, have a boundary around your matrix and fill it up with all ones. This is so that you know when the rat is trying to go out of the boundary of the maze. In the real world, the rat would know not to go out of the maze, but hey! So, initially the matrix (I mean, the maze) would be something like (the ones represent the "exra" boundary we have added). The ones inside specify the obstacles.
111111111111111111111
100000000000000000001
100000010000000000001
100000010000000000001
100000000100001000001
100001000010000000001
100000000100000000001
100000000000000000001
111111111111111111111
The rat can move in four directions at any point in time (well, right, left, up, down). Please note that the rat can't move diagonally. Imagine a real maze and not a matrix. In matrix language
Moving right means adding {0,1} to the current coordinates.
Moving left means adding {0,1} to the current coordinates.
Moving up means adding {1,0} to the current coordinates.
Moving right means adding {1,0} to the current coordinates.
The rat can start off at the first row and the first column as the entrance point.
From there, it tries to move to a cell which is currently free. A cell is free if it has a zero in it.
It tries all the 4 options onebyone, till it finds an empty cell. If it finds one, it moves to that cell and marks it with a 1 (saying it has visited it once). Then it continues to move ahead from that cell to other cells.
If at a particular cell, it runs out of all the 4 options (that is it cant move either right, left, up or down), then it needs to backtrack. It backtracks till a point where it can move ahead and be closer to the exit.
If it reaches the exit point, it gets the cheese, ofcourse.
The complexity is O(m*m).
Here is some pseudocode to chew upon
findpath()
{
Position offset[4];
Offset[0].row=0; offset[0].col=1;//right;
Offset[1].row=1; offset[1].col=0;//down;
Offset[2].row=0; offset[2].col=1;//left;
Offset[3].row=1; offset[3].col=0;//up;
// Initialize wall of obstacles around the maze
for(int i=0; i < m+1;i++)
maze[0][i] = maze[m+1][i]=1; maze[i][0] = maze[i][m+1]=1;
Position here;
Here.row=1;
Here.col=1;
maze[1][1]=1;
int option = 0;
int lastoption = 3;
while(here.row!=m  here.col!=m)
{
//Find a neighbor to move
int r,c;
while (option <= LastOption)
{
r=here.row + offset[position].row;
c=here.col + offset[option].col;
if(maze[r][c]==0)break;
option++;
}
//Was a neighbor found?
if(option <= LastOption)
{
path>Add(here);
here.row=r;here.col=c;
maze[r][c]=1;
option=0;
}
else
{
if(path>Empty())return(False);
Position next;
Path>Delete(next);
If(new.row==here.row)
Option=2+next.col  here.col;
Else { option = 3 + next.row  here.col;}
Here=next;
}
return(TRUE);
}
}
How to generate fibonacci numbers? How to find out if a given number is a fibonacci number or not? Write C programs to do both.
Lets first refresh ourselves with the Fibonacci sequence
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, .....
Fibonacci numbers obey the following rule
F(n) = F(n1) + F(n2)
Here is an iterative way to generate fibonacci numbers and also return the nth number.
int fib(int n)
{
int f[n+1];
f[1] = f[2] = 1;
printf("\nf[1] = %d", f[1]);
printf("\nf[2] = %d", f[2]);
for (int i = 3; i <= n; i++)
{
f[i] = f[i1] + f[i2];
printf("\nf[%d] = [%d]",i,f[i]);
}
return f[n];
}
Here is a recursive way to generate fibonacci numbers.
int fib(int n)
{
if (n <= 2) return 1
else return fib(n1) + fib(n2)
}
Here is an iterative way to just compute and return the nth number (without storing the previous numbers).
int fib(int n)
{
int a = 1, b = 1;
for (int i = 3; i <= n; i++)
{
int c = a + b;
a = b;
b = c;
}
return a;
}
There are a few slick ways to generate fibonacci numbers, a few of them are listed below
Method1
If you know some basic math, its easy to see that
n
[ 1 1 ] = [ F(n+1) F(n) ]
[ 1 0 ] [ F(n) F(n1) ]
or
(f(n) f(n+1)) [ 0 1 ] = (f(n+1) f(n+2))
[ 1 1 ]
or
n
(f(0) f(1)) [ 0 1 ] = (f(n) f(n+1))
[ 1 1 ]
The nth power of the 2 by 2 matrix can be computed efficiently in O(log n) time. This implies an O(log n) algorithm for computing the nth Fibonacci number.
Here is the pseudocode for this
int Matrix[2][2] = {{1,0}{0,1}}
int fib(int n)
{
matrixpower(n1);
return Matrix[0][0];
}
void matrixpower(int n)
{
if (n > 1)
{
matrixpower(n/2);
Matrix = Matrix * Matrix;
}
if (n is odd)
{
Matrix = Matrix * {{1,1}{1,0}}
}
}
And here is a program in C which calculates fib(n)
#include
int M[2][2]={{1,0},{0,1}};
int A[2][2]={{1,1},{1,0}};
int C[2][2]={{0,0},{0,0}}; // Temporary matrix used for multiplication.
void matMul(int n);
void mulM(int m);
int main()
{
int n;
n=6;
matMul(n1);
// The nth fibonacci will be stored in M[0][0]
printf("\n%dth Fibonaci number : [%d]\n\n", n, M[0][0]);
return(0);
}
// Recursive function with divide and conquer strategy
void matMul(int n)
{
if(n > 1)
{
matMul(n/2);
mulM(0); // M * M
}
if(n%2!=0)
{
mulM(1); // M * {{1,1}{1,0}}
}
}
// Function which does some basic matrix multiplication.
void mulM(int m)
{
int i,j,k;
if(m==0)
{
// C = M * M
for(i=0;i < 2;i++)
for(j=0;j < 2;j++)
{
C[i][j]=0;
for(k=0;k < 2;k++)
C[i][j]+=M[i][k]*M[k][j];
}
}
else
{
// C = M * {{1,1}{1,0}}
for(i=0;i < 2;i++)
for(j=0;j < 2;j++)
{
C[i][j]=0;
for(k=0;k < 2;k++)
C[i][j]+=A[i][k]*M[k][j];
}
}
// Copy back the temporary matrix in the original matrix M
for(i=0;i < 2;i++)
for(j=0;j < 2;j++)
{
M[i][j]=C[i][j];
}
}
Method2
f(n) = (1/sqrt(5)) * (((1+sqrt(5))/2) ^ n  ((1sqrt(5))/2) ^ n)
So now, how does one find out if a number is a fibonacci or not?.
The cumbersome way is to generate fibonacci numbers till this number and see if this number is one of them. But there is another slick way to check if a number is a fibonacci number or not.
N is a Fibonacci number if and only if (5*N*N + 4) or (5*N*N  4) is a perfect square!
Dont believe me?
3 is a Fibonacci number since (5*3*3 + 4) is 49 which is 7*7
5 is a Fibonacci number since (5*5*5  4) is 121 which is 11*11
4 is not a Fibonacci number since neither (5*4*4 + 4) = 84 nor (5*4*4  4) = 76 are perfect squares.
To check if a number is a perfect square or not, one can take the square root, round it to the nearest integer and then square the result. If this is the same as the original whole number then the original was a perfect square.
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, .....
Fibonacci numbers obey the following rule
F(n) = F(n1) + F(n2)
Here is an iterative way to generate fibonacci numbers and also return the nth number.
int fib(int n)
{
int f[n+1];
f[1] = f[2] = 1;
printf("\nf[1] = %d", f[1]);
printf("\nf[2] = %d", f[2]);
for (int i = 3; i <= n; i++)
{
f[i] = f[i1] + f[i2];
printf("\nf[%d] = [%d]",i,f[i]);
}
return f[n];
}
Here is a recursive way to generate fibonacci numbers.
int fib(int n)
{
if (n <= 2) return 1
else return fib(n1) + fib(n2)
}
Here is an iterative way to just compute and return the nth number (without storing the previous numbers).
int fib(int n)
{
int a = 1, b = 1;
for (int i = 3; i <= n; i++)
{
int c = a + b;
a = b;
b = c;
}
return a;
}
There are a few slick ways to generate fibonacci numbers, a few of them are listed below
Method1
If you know some basic math, its easy to see that
n
[ 1 1 ] = [ F(n+1) F(n) ]
[ 1 0 ] [ F(n) F(n1) ]
or
(f(n) f(n+1)) [ 0 1 ] = (f(n+1) f(n+2))
[ 1 1 ]
or
n
(f(0) f(1)) [ 0 1 ] = (f(n) f(n+1))
[ 1 1 ]
The nth power of the 2 by 2 matrix can be computed efficiently in O(log n) time. This implies an O(log n) algorithm for computing the nth Fibonacci number.
Here is the pseudocode for this
int Matrix[2][2] = {{1,0}{0,1}}
int fib(int n)
{
matrixpower(n1);
return Matrix[0][0];
}
void matrixpower(int n)
{
if (n > 1)
{
matrixpower(n/2);
Matrix = Matrix * Matrix;
}
if (n is odd)
{
Matrix = Matrix * {{1,1}{1,0}}
}
}
And here is a program in C which calculates fib(n)
#include
int M[2][2]={{1,0},{0,1}};
int A[2][2]={{1,1},{1,0}};
int C[2][2]={{0,0},{0,0}}; // Temporary matrix used for multiplication.
void matMul(int n);
void mulM(int m);
int main()
{
int n;
n=6;
matMul(n1);
// The nth fibonacci will be stored in M[0][0]
printf("\n%dth Fibonaci number : [%d]\n\n", n, M[0][0]);
return(0);
}
// Recursive function with divide and conquer strategy
void matMul(int n)
{
if(n > 1)
{
matMul(n/2);
mulM(0); // M * M
}
if(n%2!=0)
{
mulM(1); // M * {{1,1}{1,0}}
}
}
// Function which does some basic matrix multiplication.
void mulM(int m)
{
int i,j,k;
if(m==0)
{
// C = M * M
for(i=0;i < 2;i++)
for(j=0;j < 2;j++)
{
C[i][j]=0;
for(k=0;k < 2;k++)
C[i][j]+=M[i][k]*M[k][j];
}
}
else
{
// C = M * {{1,1}{1,0}}
for(i=0;i < 2;i++)
for(j=0;j < 2;j++)
{
C[i][j]=0;
for(k=0;k < 2;k++)
C[i][j]+=A[i][k]*M[k][j];
}
}
// Copy back the temporary matrix in the original matrix M
for(i=0;i < 2;i++)
for(j=0;j < 2;j++)
{
M[i][j]=C[i][j];
}
}
Method2
f(n) = (1/sqrt(5)) * (((1+sqrt(5))/2) ^ n  ((1sqrt(5))/2) ^ n)
So now, how does one find out if a number is a fibonacci or not?.
The cumbersome way is to generate fibonacci numbers till this number and see if this number is one of them. But there is another slick way to check if a number is a fibonacci number or not.
N is a Fibonacci number if and only if (5*N*N + 4) or (5*N*N  4) is a perfect square!
Dont believe me?
3 is a Fibonacci number since (5*3*3 + 4) is 49 which is 7*7
5 is a Fibonacci number since (5*5*5  4) is 121 which is 11*11
4 is not a Fibonacci number since neither (5*4*4 + 4) = 84 nor (5*4*4  4) = 76 are perfect squares.
To check if a number is a perfect square or not, one can take the square root, round it to the nearest integer and then square the result. If this is the same as the original whole number then the original was a perfect square.
How do you calculate the maximum subarray of a list of numbers?
This is a very popular question
You are given a large array X of integers (both positive and negative) and you need to find the maximum sum found in any contiguous subarray of X.
Example X = [11, 12, 15, 3, 8, 9, 1, 8, 10, 2]
Answer is 30.
There are various methods to solve this problem, some are listed below
Brute force
maxSum = 0
for L = 1 to N
{
for R = L to N
{
sum = 0
for i = L to R
{
sum = sum + X[i]
}
maxSum = max(maxSum, sum)
}
}
O(N^3)
Quadratic
Note that sum of [L..R] can be calculated from sum of [L..R1] very easily.
maxSum = 0
for L = 1 to N
{
sum = 0
for R = L to N
{
sum = sum + X[R]
maxSum = max(maxSum, sum)
}
}
Using divideandconquer
O(N log(N))
maxSum(L, R)
{
if L > R then
return 0
if L = R then
return max(0, X[L])
M = (L + R)/2
sum = 0; maxToLeft = 0
for i = M downto L do
{
sum = sum + X[i]
maxToLeft = max(maxToLeft, sum)
}
sum = 0; maxToRight = 0
for i = M to R do
{
sum = sum + X[i]
maxToRight = max(maxToRight, sum)
}
maxCrossing = maxLeft + maxRight
maxInA = maxSum(L,M)
maxInB = maxSum(M+1,R)
return max(maxCrossing, maxInA, maxInB)
}
Here is working C code for all the above cases
#include < stdio.h >
#define N 10
int maxSubSum(int left, int right);
int list[N] = {11, 12, 15, 3, 8, 9, 1, 8, 10, 2};
int main()
{
int i,j,k;
int maxSum, sum;
/*
* CUBIC  O(n*n*n)
**/
maxSum = 0;
for(i=0; i < N; i++)
{
for(j=i; j < N; j++)
{
sum = 0;
for(k=i ; k < j; k++)
{
sum = sum + list[k];
}
maxSum = (maxSum > sum)?maxSum:sum;
}
}
printf("\nmaxSum = [%d]\n", maxSum);
/*
* Quadratic  O(n*n)
*  */
maxSum = 0;
for(i=0; i < N; i++)
{
sum=0;
for(j=i; j < N ;j++)
{
sum = sum + list[j];
maxSum = (maxSum > sum)?maxSum:sum;
}
}
printf("\nmaxSum = [%d]\n", maxSum);
/*
* Divide and Conquer  O(nlog(n))
*  */
printf("\nmaxSum : [%d]\n", maxSubSum(0,9));
return(0);
}
int maxSubSum(int left, int right)
{
int mid, sum, maxToLeft, maxToRight, maxCrossing, maxInA, maxInB;
int i;
if(left > right){return 0;}
if(left==right){return((0 > list[left])?0:list[left]);}
mid = (left + right)/2;
sum=0;
maxToLeft=0;
for(i=mid; i >= left; i)
{
sum = sum + list[i];
maxToLeft = (maxToLeft > sum)?maxToLeft:sum;
}
sum=0;
maxToRight=0;
for(i=mid+1; i <= right; i++)
{
sum = sum + list[i];
maxToRight = (maxToRight > sum)?maxToRight:sum;
}
maxCrossing = maxToLeft + maxToRight;
maxInA = maxSubSum(left,mid);
maxInB = maxSubSum(mid+1,right);
return(((maxCrossing > maxInA)?maxCrossing:maxInA) > maxInB?((maxCrossing>maxInA)?maxCrossing:maxInA):maxInB);
}
Note that, if the array has all negative numbers, then this code will return 0. This is wrong because it should return the maximum sum, which is the least negative integer in the array. This happens because we are setting maxSum to 0 initially. A small change in this code can be used to handle such cases.
You are given a large array X of integers (both positive and negative) and you need to find the maximum sum found in any contiguous subarray of X.
Example X = [11, 12, 15, 3, 8, 9, 1, 8, 10, 2]
Answer is 30.
There are various methods to solve this problem, some are listed below
Brute force
maxSum = 0
for L = 1 to N
{
for R = L to N
{
sum = 0
for i = L to R
{
sum = sum + X[i]
}
maxSum = max(maxSum, sum)
}
}
O(N^3)
Quadratic
Note that sum of [L..R] can be calculated from sum of [L..R1] very easily.
maxSum = 0
for L = 1 to N
{
sum = 0
for R = L to N
{
sum = sum + X[R]
maxSum = max(maxSum, sum)
}
}
Using divideandconquer
O(N log(N))
maxSum(L, R)
{
if L > R then
return 0
if L = R then
return max(0, X[L])
M = (L + R)/2
sum = 0; maxToLeft = 0
for i = M downto L do
{
sum = sum + X[i]
maxToLeft = max(maxToLeft, sum)
}
sum = 0; maxToRight = 0
for i = M to R do
{
sum = sum + X[i]
maxToRight = max(maxToRight, sum)
}
maxCrossing = maxLeft + maxRight
maxInA = maxSum(L,M)
maxInB = maxSum(M+1,R)
return max(maxCrossing, maxInA, maxInB)
}
Here is working C code for all the above cases
#include < stdio.h >
#define N 10
int maxSubSum(int left, int right);
int list[N] = {11, 12, 15, 3, 8, 9, 1, 8, 10, 2};
int main()
{
int i,j,k;
int maxSum, sum;
/*
* CUBIC  O(n*n*n)
**/
maxSum = 0;
for(i=0; i < N; i++)
{
for(j=i; j < N; j++)
{
sum = 0;
for(k=i ; k < j; k++)
{
sum = sum + list[k];
}
maxSum = (maxSum > sum)?maxSum:sum;
}
}
printf("\nmaxSum = [%d]\n", maxSum);
/*
* Quadratic  O(n*n)
*  */
maxSum = 0;
for(i=0; i < N; i++)
{
sum=0;
for(j=i; j < N ;j++)
{
sum = sum + list[j];
maxSum = (maxSum > sum)?maxSum:sum;
}
}
printf("\nmaxSum = [%d]\n", maxSum);
/*
* Divide and Conquer  O(nlog(n))
*  */
printf("\nmaxSum : [%d]\n", maxSubSum(0,9));
return(0);
}
int maxSubSum(int left, int right)
{
int mid, sum, maxToLeft, maxToRight, maxCrossing, maxInA, maxInB;
int i;
if(left > right){return 0;}
if(left==right){return((0 > list[left])?0:list[left]);}
mid = (left + right)/2;
sum=0;
maxToLeft=0;
for(i=mid; i >= left; i)
{
sum = sum + list[i];
maxToLeft = (maxToLeft > sum)?maxToLeft:sum;
}
sum=0;
maxToRight=0;
for(i=mid+1; i <= right; i++)
{
sum = sum + list[i];
maxToRight = (maxToRight > sum)?maxToRight:sum;
}
maxCrossing = maxToLeft + maxToRight;
maxInA = maxSubSum(left,mid);
maxInB = maxSubSum(mid+1,right);
return(((maxCrossing > maxInA)?maxCrossing:maxInA) > maxInB?((maxCrossing>maxInA)?maxCrossing:maxInA):maxInB);
}
Note that, if the array has all negative numbers, then this code will return 0. This is wrong because it should return the maximum sum, which is the least negative integer in the array. This happens because we are setting maxSum to 0 initially. A small change in this code can be used to handle such cases.
Write a C program which does wildcard pattern matching algorithm.
Here is an example C program...
#include < stdio.h >
#define TRUE 1
#define FALSE 0
int wildcard(char *string, char *pattern);
int main()
{
char *string = "hereheroherr";
char *pattern = "*hero*";
if(wildcard(string, pattern)==TRUE)
{
printf("\nMatch Found!\n");
}
else
{
printf("\nMatch not found!\n");
}
return(0);
}
int wildcard(char *string, char *pattern)
{
while(*string)
{
switch(*pattern)
{
case '*': do {++pattern;}while(*pattern == '*');
if(!*pattern) return(TRUE);
while(*string){if(wildcard(pattern,string++)==TRUE)return(TRUE);}
return(FALSE);
default : if(*string!=*pattern)return(FALSE); break;
}
++pattern;
++string;
}
while (*pattern == '*') ++pattern;
return !*pattern;
}
#include < stdio.h >
#define TRUE 1
#define FALSE 0
int wildcard(char *string, char *pattern);
int main()
{
char *string = "hereheroherr";
char *pattern = "*hero*";
if(wildcard(string, pattern)==TRUE)
{
printf("\nMatch Found!\n");
}
else
{
printf("\nMatch not found!\n");
}
return(0);
}
int wildcard(char *string, char *pattern)
{
while(*string)
{
switch(*pattern)
{
case '*': do {++pattern;}while(*pattern == '*');
if(!*pattern) return(TRUE);
while(*string){if(wildcard(pattern,string++)==TRUE)return(TRUE);}
return(FALSE);
default : if(*string!=*pattern)return(FALSE); break;
}
++pattern;
++string;
}
while (*pattern == '*') ++pattern;
return !*pattern;
}
Write a C program to calculate pow(x,n)?
There are again different methods to do this in C
Brute force C program
int pow(int x, int y)
{
if(y == 1) return x ;
return x * pow(x, y1) ;
}
Divide and Conquer C program
#include < stdio.h >
int main(int argc, char*argv[])
{
printf("\n[%d]\n",pow(5,4));
}
int pow(int x, int n)
{
if(n==0)return(1);
else if(n%2==0)
{
return(pow(x,n/2)*pow(x,(n/2)));
}
else
{
return(x*pow(x,n/2)*pow(x,(n/2)));
}
}
Also, the code above can be optimized still by calculating pow(z, (n/2)) only one time (instead of twice) and using its value in the two return() expressions above.
Brute force C program
int pow(int x, int y)
{
if(y == 1) return x ;
return x * pow(x, y1) ;
}
Divide and Conquer C program
#include < stdio.h >
int main(int argc, char*argv[])
{
printf("\n[%d]\n",pow(5,4));
}
int pow(int x, int n)
{
if(n==0)return(1);
else if(n%2==0)
{
return(pow(x,n/2)*pow(x,(n/2)));
}
else
{
return(x*pow(x,n/2)*pow(x,(n/2)));
}
}
Also, the code above can be optimized still by calculating pow(z, (n/2)) only one time (instead of twice) and using its value in the two return() expressions above.
Write a C program generate permutations.
Iterative C program
#include < stdio.h >
#define SIZE 3
int main(char *argv[],int argc)
{
char list[3]={'a','b','c'};
int i,j,k;
for(i=0;i < SIZE;i++)
for(j=0;j < SIZE;j++)
for(k=0;k < SIZE;k++)
if(i!=j && j!=k && i!=k)
printf("%c%c%c\n",list[i],list[j],list[k]);
return(0);
}
Recursive C program
#include < stdio.h >
#define N 5
int main(char *argv[],int argc)
{
char list[5]={'a','b','c','d','e'};
permute(list,0,N);
return(0);
}
void permute(char list[],int k, int m)
{
int i;
char temp;
if(k==m)
{
/* PRINT A FROM k to m! */
for(i=0;i < N;i++){printf("%c",list[i]);}
printf("\n");
}
else
{
for(i=k;i < m;i++)
{
/* swap(a[i],a[m1]); */
temp=list[i];
list[i]=list[m1];
list[m1]=temp;
permute(list,k,m1);
/* swap(a[m1],a[i]); */
temp=list[m1];
list[m1]=list[i];
list[i]=temp;
}
}
}
#include < stdio.h >
#define SIZE 3
int main(char *argv[],int argc)
{
char list[3]={'a','b','c'};
int i,j,k;
for(i=0;i < SIZE;i++)
for(j=0;j < SIZE;j++)
for(k=0;k < SIZE;k++)
if(i!=j && j!=k && i!=k)
printf("%c%c%c\n",list[i],list[j],list[k]);
return(0);
}
Recursive C program
#include < stdio.h >
#define N 5
int main(char *argv[],int argc)
{
char list[5]={'a','b','c','d','e'};
permute(list,0,N);
return(0);
}
void permute(char list[],int k, int m)
{
int i;
char temp;
if(k==m)
{
/* PRINT A FROM k to m! */
for(i=0;i < N;i++){printf("%c",list[i]);}
printf("\n");
}
else
{
for(i=k;i < m;i++)
{
/* swap(a[i],a[m1]); */
temp=list[i];
list[i]=list[m1];
list[m1]=temp;
permute(list,k,m1);
/* swap(a[m1],a[i]); */
temp=list[m1];
list[m1]=list[i];
list[i]=temp;
}
}
}
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 inplace.
*/
#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,end1);
// Now swap each word within sentence...
x = buf1;
y = buf;
while(x++ < end)
{
if(*x == '\0'  *x == ' ')
{
rev(y,x1);
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 < r)
{
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  >  < spaces >  >  am  >  < spaces >  >  a  >  < spaces >  >  good  >  < spaces >  >  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 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 inplace.
*/
#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,end1);
// Now swap each word within sentence...
x = buf1;
y = buf;
while(x++ < end)
{
if(*x == '\0'  *x == ' ')
{
rev(y,x1);
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 < r)
{
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  >  < spaces >  >  am  >  < spaces >  >  a  >  < spaces >  >  good  >  < spaces >  >  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.
Saturday, July 7, 2007
Write a C program to reverse a string.
There are a number of ways one can reverse strings. Here are a few of them. These should be enough to impress the interviewer! The methods span from recursive to nonrecursive (iterative).
Also note that there is a similar question about reversing the words in a sentence, but still keeping the words in place. That is
I am a good boy
would become
boy good a am I
This is dealt with in another question. Here I only concentrate on reversing strings. That is
I am a good boy
would become
yob doog a ma I
Here are some sample C programs to do the same
Method1 (Recursive)
#include
static char str[]="STRING TO REVERSE";
int main(int argc, char *argv)
{
printf("\nOriginal string : [%s]", str);
// Call the recursion function
reverse(0);
printf("\nReversed string : [%s]", str);
return(0);
}
int reverse(int pos)
{
// Here I am calculating strlen(str) everytime.
// This can be avoided by doing this computation
// earlier and storing it somewhere for later use.
if(pos<(strlen(str)/2))
{
char ch;
// Swap str[pos] and str[strlen(str)pos1]
ch = str[pos];
str[pos]=str[strlen(str)pos1];
str[strlen(str)pos1]=ch;
// Now recurse!
reverse(pos+1);
}
}
Method2
#include
#include
#include
void ReverseStr ( char *buff, int start, int end )
{
char tmp ;
if ( start >= end )
{
printf ( "\n%s\n", buff );
return;
}
tmp = *(buff + start);
*(buff + start) = *(buff + end);
*(buff + end) = tmp ;
ReverseStr (buff, ++start, end );
}
int main()
{
char buffer[]="This is Test";
ReverseStr(buffer,0,strlen(buffer)1);
return 0;
}
Method3
public static String reverse(String s)
{
int N = s.length();
if (N <= 1) return s;
String left = s.substring(0, N/2);
String right = s.substring(N/2, N);
return reverse(right) + reverse(left);
}
Method4
for(int i = 0, j = reversed.Length  1; i < j; i++, j)
{
char temp = reversed[i];
reversed[i] = reversed[j];
reversed[j] = temp;
}
return new String(reversed);
Method5
public static String reverse(String s)
{
int N = s.length();
String reverse = "";
for (int i = 0; i < N; i++)
reverse = s.charAt(i) + reverse;
return reverse;
}
Method6
public static String reverse(String s)
{
int N = s.length();
char[] a = new char[N];
for (int i = 0; i < N; i++)
a[i] = s.charAt(Ni1);
String reverse = new String(a);
return reverse;
}
Isn't that enough?
Also note that there is a similar question about reversing the words in a sentence, but still keeping the words in place. That is
I am a good boy
would become
boy good a am I
This is dealt with in another question. Here I only concentrate on reversing strings. That is
I am a good boy
would become
yob doog a ma I
Here are some sample C programs to do the same
Method1 (Recursive)
#include
static char str[]="STRING TO REVERSE";
int main(int argc, char *argv)
{
printf("\nOriginal string : [%s]", str);
// Call the recursion function
reverse(0);
printf("\nReversed string : [%s]", str);
return(0);
}
int reverse(int pos)
{
// Here I am calculating strlen(str) everytime.
// This can be avoided by doing this computation
// earlier and storing it somewhere for later use.
if(pos<(strlen(str)/2))
{
char ch;
// Swap str[pos] and str[strlen(str)pos1]
ch = str[pos];
str[pos]=str[strlen(str)pos1];
str[strlen(str)pos1]=ch;
// Now recurse!
reverse(pos+1);
}
}
Method2
#include
#include
#include
void ReverseStr ( char *buff, int start, int end )
{
char tmp ;
if ( start >= end )
{
printf ( "\n%s\n", buff );
return;
}
tmp = *(buff + start);
*(buff + start) = *(buff + end);
*(buff + end) = tmp ;
ReverseStr (buff, ++start, end );
}
int main()
{
char buffer[]="This is Test";
ReverseStr(buffer,0,strlen(buffer)1);
return 0;
}
Method3
public static String reverse(String s)
{
int N = s.length();
if (N <= 1) return s;
String left = s.substring(0, N/2);
String right = s.substring(N/2, N);
return reverse(right) + reverse(left);
}
Method4
for(int i = 0, j = reversed.Length  1; i < j; i++, j)
{
char temp = reversed[i];
reversed[i] = reversed[j];
reversed[j] = temp;
}
return new String(reversed);
Method5
public static String reverse(String s)
{
int N = s.length();
String reverse = "";
for (int i = 0; i < N; i++)
reverse = s.charAt(i) + reverse;
return reverse;
}
Method6
public static String reverse(String s)
{
int N = s.length();
char[] a = new char[N];
for (int i = 0; i < N; i++)
a[i] = s.charAt(Ni1);
String reverse = new String(a);
return reverse;
}
Isn't that enough?
Write a C program to print a square matrix helically.
Here is a C program to print a matrix helically. Printing a matrix helically means printing it in this spiral fashion.
This is a simple program to print a matrix helically.
#include
/* HELICAL MATRIX */
int main()
{
int arr[][4] = { {1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13, 14, 15, 16}
};
int i, j, k,middle,size;
printf("\n\n");
size = 4;
for(i=size1, j=0; i > 0; i, j++)
{
for(k=j; k < i; k++) printf("%d ", arr[j][k]);
for(k=j; k < i; k++) printf("%d ", arr[k][i]);
for(k=i; k > j; k) printf("%d ", arr[i][k]);
for(k=i; k > j; k) printf("%d ", arr[k][j]);
}
middle = (size1)/2;
if (size % 2 == 1) printf("%d", arr[middle][middle]);
printf("\n\n");
return 1;
}
This is a simple program to print a matrix helically.
#include
/* HELICAL MATRIX */
int main()
{
int arr[][4] = { {1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13, 14, 15, 16}
};
int i, j, k,middle,size;
printf("\n\n");
size = 4;
for(i=size1, j=0; i > 0; i, j++)
{
for(k=j; k < i; k++) printf("%d ", arr[j][k]);
for(k=j; k < i; k++) printf("%d ", arr[k][i]);
for(k=i; k > j; k) printf("%d ", arr[i][k]);
for(k=i; k > j; k) printf("%d ", arr[k][j]);
}
middle = (size1)/2;
if (size % 2 == 1) printf("%d", arr[middle][middle]);
printf("\n\n");
return 1;
}
What is the 8 queens problem? Write a C program to solve it.
The 8 queens problem is a classic problem using the chess board. This problem is to place 8 queens on the chess board so that they do not attack each other horizontally, vertically or diagonally. It turns out that there are 12 essentially distinct solutions to this problem.
Suppose we have an array t[8] which keeps track of which column is occupied in which row of the chess board. That is, if t[0]==5, then it means that the queen has been placed in the fifth column of the first row. We need to couple the backtracking algorithm with a procedure that checks whether the tuple is completable or not, i.e. to check that the next placed queen 'i' is not menaced by any of the already placed 'j' (j < i):
Two queens are in the same column if t[i]=t[j]
Two queens are in the same major diagonal if (t[i]t[j])=(ij)
two queens are in the same minor diagonal if (t[j]t[i])=(ij)
Here is some working C code to solve this problem using backtracking
#include
static int t[10]={1};
void queens(int i);
int empty(int i);
void print_solution();
int main()
{
queens(1);
print_solution();
return(0);
}
void queens(int i)
{
for(t[i]=1;t[i]<=8;t[i]++)
{
if(empty(i))
{
if(i==8)
{
print_solution();
/* If this exit is commented, it will show ALL possible combinations */
exit(0);
}
else
{
// Recurse!
queens(i+1);
}
}// if
}// for
}
int empty(int i)
{
int j;
j=1;
while(t[i]!=t[j] && abs(t[i]t[j])!=(ij) &&j<8)j++;
return((i==j)?1:0);
}
void print_solution()
{
int i;
for(i=1;i<=8;i++)printf("\nt[%d] = [%d]",i,t[i]);
}
And here is one of the possible solutions
t[1] = [1] // This means the first square of the first row.
t[2] = [5] // This means the fifth square of the second row.
t[3] = [8] ..
t[4] = [6] ..
t[5] = [3] ..
t[6] = [7] ..
t[7] = [2] ..
t[8] = [4] // This means the fourth square of the last row.
Suppose we have an array t[8] which keeps track of which column is occupied in which row of the chess board. That is, if t[0]==5, then it means that the queen has been placed in the fifth column of the first row. We need to couple the backtracking algorithm with a procedure that checks whether the tuple is completable or not, i.e. to check that the next placed queen 'i' is not menaced by any of the already placed 'j' (j < i):
Two queens are in the same column if t[i]=t[j]
Two queens are in the same major diagonal if (t[i]t[j])=(ij)
two queens are in the same minor diagonal if (t[j]t[i])=(ij)
Here is some working C code to solve this problem using backtracking
#include
static int t[10]={1};
void queens(int i);
int empty(int i);
void print_solution();
int main()
{
queens(1);
print_solution();
return(0);
}
void queens(int i)
{
for(t[i]=1;t[i]<=8;t[i]++)
{
if(empty(i))
{
if(i==8)
{
print_solution();
/* If this exit is commented, it will show ALL possible combinations */
exit(0);
}
else
{
// Recurse!
queens(i+1);
}
}// if
}// for
}
int empty(int i)
{
int j;
j=1;
while(t[i]!=t[j] && abs(t[i]t[j])!=(ij) &&j<8)j++;
return((i==j)?1:0);
}
void print_solution()
{
int i;
for(i=1;i<=8;i++)printf("\nt[%d] = [%d]",i,t[i]);
}
And here is one of the possible solutions
t[1] = [1] // This means the first square of the first row.
t[2] = [5] // This means the fifth square of the second row.
t[3] = [8] ..
t[4] = [6] ..
t[5] = [3] ..
t[6] = [7] ..
t[7] = [2] ..
t[8] = [4] // This means the fourth square of the last row.
Write a C program to swap two variables without using a temporary variable.
This questions is asked almost always in every interview.
The best way to swap two variables is to use a temporary variable.
int a,b,t;
t = a;
a = b;
b = t;
There is no way better than this as you will find out soon. There are a few slick expressions that do swap variables without using temporary storage. But they come with their own set of problems.
Method1 (The XOR trick)
a ^= b ^= a ^= b;
Although the code above works fine for most of the cases, it tries to modify variable 'a' two times between sequence points, so the behavior is undefined. What this means is it wont work in all the cases. This will also not work for floatingpoint values. Also, think of a scenario where you have written your code like this
swap(int *a, int *b)
{
*a ^= *b ^= *a ^= *b;
}
Now, if suppose, by mistake, your code passes the pointer to the same variable to this function. Guess what happens? Since Xor'ing an element with itself sets the variable to zero, this routine will end up setting the variable to zero (ideally it should have swapped the variable with itself). This scenario is quite possible in sorting algorithms which sometimes try to swap a variable with itself (maybe due to some small, but not so fatal coding error). One solution to this problem is to check if the numbers to be swapped are already equal to each other.
swap(int *a, int *b)
{
if(*a!=*b)
{
*a ^= *b ^= *a ^= *b;
}
}
Method2
This method is also quite popular
a=a+b;
b=ab;
a=ab;
But, note that here also, if a and b are big and their addition is bigger than the size of an int, even this might end up giving you wrong results.
Method3
One can also swap two variables using a macro. However, it would be required to pass the type of the variable to the macro. Also, there is an interesting problem using macros. Suppose you have a swap macro which looks something like this
#define swap(type,a,b) type temp;temp=a;a=b;b=temp;
Now, think what happens if you pass in something like this
swap(int,temp,a) //You have a variable called "temp" (which is quite possible).
This is how it gets replaced by the macro
int temp;
temp=temp;
temp=b;
b=temp;
Which means it sets the value of "b" to both the variables!. It never swapped them! Scary, isn't it?
So the moral of the story is, dont try to be smart when writing code to swap variables. Use a temporary variable. Its not only fool proof, but also easier to understand and maintain.
The best way to swap two variables is to use a temporary variable.
int a,b,t;
t = a;
a = b;
b = t;
There is no way better than this as you will find out soon. There are a few slick expressions that do swap variables without using temporary storage. But they come with their own set of problems.
Method1 (The XOR trick)
a ^= b ^= a ^= b;
Although the code above works fine for most of the cases, it tries to modify variable 'a' two times between sequence points, so the behavior is undefined. What this means is it wont work in all the cases. This will also not work for floatingpoint values. Also, think of a scenario where you have written your code like this
swap(int *a, int *b)
{
*a ^= *b ^= *a ^= *b;
}
Now, if suppose, by mistake, your code passes the pointer to the same variable to this function. Guess what happens? Since Xor'ing an element with itself sets the variable to zero, this routine will end up setting the variable to zero (ideally it should have swapped the variable with itself). This scenario is quite possible in sorting algorithms which sometimes try to swap a variable with itself (maybe due to some small, but not so fatal coding error). One solution to this problem is to check if the numbers to be swapped are already equal to each other.
swap(int *a, int *b)
{
if(*a!=*b)
{
*a ^= *b ^= *a ^= *b;
}
}
Method2
This method is also quite popular
a=a+b;
b=ab;
a=ab;
But, note that here also, if a and b are big and their addition is bigger than the size of an int, even this might end up giving you wrong results.
Method3
One can also swap two variables using a macro. However, it would be required to pass the type of the variable to the macro. Also, there is an interesting problem using macros. Suppose you have a swap macro which looks something like this
#define swap(type,a,b) type temp;temp=a;a=b;b=temp;
Now, think what happens if you pass in something like this
swap(int,temp,a) //You have a variable called "temp" (which is quite possible).
This is how it gets replaced by the macro
int temp;
temp=temp;
temp=b;
b=temp;
Which means it sets the value of "b" to both the variables!. It never swapped them! Scary, isn't it?
So the moral of the story is, dont try to be smart when writing code to swap variables. Use a temporary variable. Its not only fool proof, but also easier to understand and maintain.
Write your own strcat() function.
Here is a C function which implements the strcat() function...
/* Function to concatenate string t to end of s; return s */
char *myStrcat(char *s, const char *t)
{
char *p = s;
if (s == NULL  t == NULL)
return s; /* we need not have to do anything */
while (*s)
s++;
while (*s++ = *t++)
;
return p;
}
/* Function to concatenate string t to end of s; return s */
char *myStrcat(char *s, const char *t)
{
char *p = s;
if (s == NULL  t == NULL)
return s; /* we need not have to do anything */
while (*s)
s++;
while (*s++ = *t++)
;
return p;
}
Write a C program to implement the strlen() function.
The prototype of the strlen() function is...
size_t strlen(const char *string);
Here is some C code which implements the strlen() function....
int my_strlen(char *string)
{
int length;
for (length = 0; *string != '\0', string++)
{
length++;
}
return(length);
}
Also, see another example
int my_strlen(char *s)
{
char *p=s;
while(*p!='\0')
p++;
return(ps);
}
size_t strlen(const char *string);
Here is some C code which implements the strlen() function....
int my_strlen(char *string)
{
int length;
for (length = 0; *string != '\0', string++)
{
length++;
}
return(length);
}
Also, see another example
int my_strlen(char *s)
{
char *p=s;
while(*p!='\0')
p++;
return(ps);
}
Write a C program to implement your own strdup() function.
Here is a C program to implement the strdup() function.
char *mystrdup(char *s)
{
char *result = (char*)malloc(strlen(s) + 1);
if (result == (char*)0){return (char*)0;}
strcpy(result, s);
return result;
}
char *mystrdup(char *s)
{
char *result = (char*)malloc(strlen(s) + 1);
if (result == (char*)0){return (char*)0;}
strcpy(result, s);
return result;
}
Write C programs to implement the toupper() and the isupper() functions.
toUpper()
int toUpper(int ch)
{
if(ch>='a' && c<='z')
return('A' + ch  'a');
else
return(ch);
}
isUpper()
int isUpper(int ch)
{
if(ch>='A' && ch <='Z')
return(1); //Yes, its upper!
else
return(0); // No, its lower!
}
Its important to know that the upper and lower case alphabets have corresponding integer values.
AZ  6590
az  97122
Another way to do this conversion is to maintain a correspondance between the upper and lower case alphabets. The program below does that. This frees us from the fact that these alphabets have a corresponding integer values. I dont know what one should do for nonenglish alphabets. Do other languages have upper and lower case letters in the first place :) !
#include
#define UPPER "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#define LOWER "abcdefghijklmnopqrstuvwxyz"
int toUpper(int c)
{
const char *upper;
const char *const lower = LOWER;
// Get the position of the lower case alphabet in the LOWER string using the strchr() function ..
upper = ( ((CHAR_MAX >= c)&&(c > '\0')) ? strchr(lower, c) : NULL);
// Now return the corresponding alphabet at that position in the UPPER string ..
return((upper != NULL)?UPPER[upper  lower] : c);
}
Note that these routines dont have much error handling incorporated in them. Its really easy to add error handling to these routines or just leave it out (as I like it). This site consciously leaves out error handling for most of the programs to prevent unwanted clutter and present the core logic first.
int toUpper(int ch)
{
if(ch>='a' && c<='z')
return('A' + ch  'a');
else
return(ch);
}
isUpper()
int isUpper(int ch)
{
if(ch>='A' && ch <='Z')
return(1); //Yes, its upper!
else
return(0); // No, its lower!
}
Its important to know that the upper and lower case alphabets have corresponding integer values.
AZ  6590
az  97122
Another way to do this conversion is to maintain a correspondance between the upper and lower case alphabets. The program below does that. This frees us from the fact that these alphabets have a corresponding integer values. I dont know what one should do for nonenglish alphabets. Do other languages have upper and lower case letters in the first place :) !
#include
#define UPPER "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#define LOWER "abcdefghijklmnopqrstuvwxyz"
int toUpper(int c)
{
const char *upper;
const char *const lower = LOWER;
// Get the position of the lower case alphabet in the LOWER string using the strchr() function ..
upper = ( ((CHAR_MAX >= c)&&(c > '\0')) ? strchr(lower, c) : NULL);
// Now return the corresponding alphabet at that position in the UPPER string ..
return((upper != NULL)?UPPER[upper  lower] : c);
}
Note that these routines dont have much error handling incorporated in them. Its really easy to add error handling to these routines or just leave it out (as I like it). This site consciously leaves out error handling for most of the programs to prevent unwanted clutter and present the core logic first.
Write your own copy() function.
Here is some C code that simulates a file copy action.
#include /* standard I/O routines. */
#define MAX_LINE_LEN 1000 /* maximum line length supported. */
void main(int argc, char* argv[])
{
char* file_path_from;
char* file_path_to;
FILE* f_from;
FILE* f_to;
char buf[MAX_LINE_LEN+1];
file_path_from = "";
file_path_to = "";
f_from = fopen(file_path_from, "r");
if (!f_from) {exit(1);}
f_to = fopen(file_path_to, "w+");
if (!f_to) {exit(1);}
/* Copy source to target, line by line. */
while (fgets(buf, MAX_LINE_LEN+1, f_from))
{
if (fputs(buf, f_to) == EOF){exit(1);}
}
if (!feof(f_from)){exit(1);}
if (fclose(f_from) == EOF) {exit(1);}
if (fclose(f_to) == EOF) {exit(1);}
return(0);
}
#include
#define MAX_LINE_LEN 1000 /* maximum line length supported. */
void main(int argc, char* argv[])
{
char* file_path_from;
char* file_path_to;
FILE* f_from;
FILE* f_to;
char buf[MAX_LINE_LEN+1];
file_path_from = "
file_path_to = "
f_from = fopen(file_path_from, "r");
if (!f_from) {exit(1);}
f_to = fopen(file_path_to, "w+");
if (!f_to) {exit(1);}
/* Copy source to target, line by line. */
while (fgets(buf, MAX_LINE_LEN+1, f_from))
{
if (fputs(buf, f_to) == EOF){exit(1);}
}
if (!feof(f_from)){exit(1);}
if (fclose(f_from) == EOF) {exit(1);}
if (fclose(f_to) == EOF) {exit(1);}
return(0);
}
Implement the substr() function in C.
Here is a C program which implements the substr() function in C.
int main()
{
char str1[] = "India";
char str2[25];
substr(str2, str1, 1, 3);
printf("\nstr2 : [%s]", str2);
return(0);
}
substr(char *dest, char *src, int position, int length)
{
dest[0]='\0';
strncat(dest, (src + position), length);
}
Here is another C program to do the same...
#include
#include
void mySubstr(char *dest, char *src, int position, int length);
int main()
{
char subStr[100];
char str[]="My Name Is Sweet";
mySubstr(subStr, str, 1, 5);
printf("\nstr = [%s]"
"\nsubStr = [%s]\n\n",
str, subStr);
getch();
return(0);
}
void mySubstr(char *dest, char *src, int position, int length)
{
while(length > 0)
{
*dest = *(src+position);
dest++;
src++;
length;
}
}
int main()
{
char str1[] = "India";
char str2[25];
substr(str2, str1, 1, 3);
printf("\nstr2 : [%s]", str2);
return(0);
}
substr(char *dest, char *src, int position, int length)
{
dest[0]='\0';
strncat(dest, (src + position), length);
}
Here is another C program to do the same...
#include
#include
void mySubstr(char *dest, char *src, int position, int length);
int main()
{
char subStr[100];
char str[]="My Name Is Sweet";
mySubstr(subStr, str, 1, 5);
printf("\nstr = [%s]"
"\nsubStr = [%s]\n\n",
str, subStr);
getch();
return(0);
}
void mySubstr(char *dest, char *src, int position, int length)
{
while(length > 0)
{
*dest = *(src+position);
dest++;
src++;
length;
}
}
Implement the strcmp(str1, str2) function.
There are many ways one can implement the strcmp() function. Note that strcmp(str1,str2) returns a ve number if str1 is alphabetically above str2, 0 if both are equal and +ve if str2 is alphabetically above str1.
Here are some C programs which implement the strcmp() function. This is also one of the most frequently asked interview questions. The prototype of strcmp() is
int strcmp( const char *string1, const char *string2 );
Here is some C code..
#include
int mystrcmp(const char *s1, const char *s2);
int main()
{
printf("\nstrcmp() = [%d]\n", mystrcmp("A","A"));
printf("\nstrcmp() = [%d]\n", mystrcmp("A","B"));
printf("\nstrcmp() = [%d]\n", mystrcmp("B","A"));
return(0);
}
int mystrcmp(const char *s1, const char *s2)
{
while (*s1==*s2)
{
if(*s1=='\0')
return(0);
s1++;
s2++;
}
return(*s1*s2);
}
And here is the output...
strcmp() = [0]
strcmp() = [1]
strcmp() = [1]
Here are some C programs which implement the strcmp() function. This is also one of the most frequently asked interview questions. The prototype of strcmp() is
int strcmp( const char *string1, const char *string2 );
Here is some C code..
#include
int mystrcmp(const char *s1, const char *s2);
int main()
{
printf("\nstrcmp() = [%d]\n", mystrcmp("A","A"));
printf("\nstrcmp() = [%d]\n", mystrcmp("A","B"));
printf("\nstrcmp() = [%d]\n", mystrcmp("B","A"));
return(0);
}
int mystrcmp(const char *s1, const char *s2)
{
while (*s1==*s2)
{
if(*s1=='\0')
return(0);
s1++;
s2++;
}
return(*s1*s2);
}
And here is the output...
strcmp() = [0]
strcmp() = [1]
strcmp() = [1]
Implement the strcpy() function.
Here are some C programs which implement the strcpy() function. This is one of the most frequently asked C interview questions.
Method1
char *mystrcpy(char *dst, const char *src)
{
char *ptr;
ptr = dst;
while(*dst++=*src++);
return(ptr);
}
The strcpy function copies src, including the terminating null character, to the location specified by dst. No overflow checking is performed when strings are copied or appended. The behavior of strcpy is undefined if the source and destination strings overlap. It returns the destination string. No return value is reserved to indicate an error.
Note that the prototype of strcpy as per the C standards is
char *strcpy(char *dst, const char *src);
Notice the const for the source, which signifies that the function must not change the source string in anyway!.
Method2
char *my_strcpy(char dest[], const char source[])
{
int i = 0;
while (source[i] != '\0')
{
dest[i] = source[i];
i++;
}
dest[i] = '\0';
return(dest);
}
Simple, isn't it?
Method1
char *mystrcpy(char *dst, const char *src)
{
char *ptr;
ptr = dst;
while(*dst++=*src++);
return(ptr);
}
The strcpy function copies src, including the terminating null character, to the location specified by dst. No overflow checking is performed when strings are copied or appended. The behavior of strcpy is undefined if the source and destination strings overlap. It returns the destination string. No return value is reserved to indicate an error.
Note that the prototype of strcpy as per the C standards is
char *strcpy(char *dst, const char *src);
Notice the const for the source, which signifies that the function must not change the source string in anyway!.
Method2
char *my_strcpy(char dest[], const char source[])
{
int i = 0;
while (source[i] != '\0')
{
dest[i] = source[i];
i++;
}
dest[i] = '\0';
return(dest);
}
Simple, isn't it?
Write your own printf() function in C.
This is again one of the most frequently asked interview questions. Here is a C program which implements a basic version of printf(). This is a really, really simplified version of printf(). Note carefully how floating point and other compilcated support has been left out. Also, note how we use low level puts() and putchar(). Dont make a fool of yourself by using printf() within the implementation of printf()!
#include
#include
main()
{
void myprintf(char *,...);
char * convert(unsigned int, int);
int i=65;
char str[]="This is my string";
myprintf("\nMessage = %s%d%x",str,i,i);
}
void myprintf(char * frmt,...)
{
char *p;
int i;
unsigned u;
char *s;
va_list argp;
va_start(argp, fmt);
p=fmt;
for(p=fmt; *p!='\0';p++)
{
if(*p=='%')
{
putchar(*p);continue;
}
p++;
switch(*p)
{
case 'c' : i=va_arg(argp,int);putchar(i);break;
case 'd' : i=va_arg(argp,int);
if(i<0){i=i;putchar('');}puts(convert(i,10));break;
case 'o': i=va_arg(argp,unsigned int); puts(convert(i,8));break;
case 's': s=va_arg(argp,char *); puts(s); break;
case 'u': u=va_arg(argp,argp, unsigned int); puts(convert(u,10));break;
case 'x': u=va_arg(argp,argp, unsigned int); puts(convert(u,16));break;
case '%': putchar('%');break;
}
}
va_end(argp);
}
char *convert(unsigned int, int)
{
static char buf[33];
char *ptr;
ptr=&buf[sizeof(buff)1];
*ptr='\0';
do
{
*ptr="0123456789abcdef"[num%base];
num/=base;
}while(num!=0);
return(ptr);
}
#include
#include
main()
{
void myprintf(char *,...);
char * convert(unsigned int, int);
int i=65;
char str[]="This is my string";
myprintf("\nMessage = %s%d%x",str,i,i);
}
void myprintf(char * frmt,...)
{
char *p;
int i;
unsigned u;
char *s;
va_list argp;
va_start(argp, fmt);
p=fmt;
for(p=fmt; *p!='\0';p++)
{
if(*p=='%')
{
putchar(*p);continue;
}
p++;
switch(*p)
{
case 'c' : i=va_arg(argp,int);putchar(i);break;
case 'd' : i=va_arg(argp,int);
if(i<0){i=i;putchar('');}puts(convert(i,10));break;
case 'o': i=va_arg(argp,unsigned int); puts(convert(i,8));break;
case 's': s=va_arg(argp,char *); puts(s); break;
case 'u': u=va_arg(argp,argp, unsigned int); puts(convert(u,10));break;
case 'x': u=va_arg(argp,argp, unsigned int); puts(convert(u,16));break;
case '%': putchar('%');break;
}
}
va_end(argp);
}
char *convert(unsigned int, int)
{
static char buf[33];
char *ptr;
ptr=&buf[sizeof(buff)1];
*ptr='\0';
do
{
*ptr="0123456789abcdef"[num%base];
num/=base;
}while(num!=0);
return(ptr);
}
Write C code to implement the strstr() (search for a substring) function.
This is also one of the most frequently asked interview questions. Its asked almost 99% of the times. Here are a few C programs to implement your own strstr() function.
There are a number of ways to find a string inside another string. Its important to be aware of these algorithms than to memorize them. Some of the fastest algorithms are quite tough to understand!.
Method1
The first method is the classic Brute force method. The Brute Force algorithm checks, at all positions in the text between 0 and (nm), if an occurrence of the pattern starts at that position or not. Then, after each successfull or unsuccessful attempt, it shifts the pattern exactly one position to the right. The time complexity of this searching phase is O(mn). The expected number of text character comparisons is 2n.
Here 'n' is the size of the string in which the substring of size 'm' is being searched for.
Here is some code (which works!)
#include
void BruteForce(char *x /* pattern */,
int m /* length of the pattern */,
char *y /* actual string being searched */,
int n /* length of this string */)
{
int i, j;
printf("\nstring : [%s]"
"\nlength : [%d]"
"\npattern : [%s]"
"\nlength : [%d]\n\n", y,n,x,m);
/* Searching */
for (j = 0; j <= (n  m); ++j)
{
for (i = 0; i < m && x[i] == y[i + j]; ++i);
if (i >= m) {printf("\nMatch found at\n\n>[%d]\n>[%s]\n",j,y+j);}
}
}
int main()
{
char *string = "hereroheroero";
char *pattern = "hero";
BF(pattern,strlen(pattern),string,strlen(string));
printf("\n\n");
return(0);
}
This is how the comparison happens visually
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
 > Match!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
Method2
The second method is called the RabinKarp method.
Instead of checking at each position of the text if the pattern occurs or not, it is better to check first if the contents of the current string "window" looks like the pattern or not. In order to check the resemblance between these two patterns, a hashing function is used. Hashing a string involves computing a numerical value from the value of its characters using a hash function.
The RabinKarp method uses the rule that if two strings are equal, their hash values must also be equal. Note that the converse of this statement is not always true, but a good hash function tries to reduce the number of such hash collisions. RabinKarp computes hash value of the pattern, and then goes through the string computing hash values of all of its substrings and checking if the pattern's hash value is equal to the substring hash value, and advancing by 1 character every time. If the two hash values are the same, then the algorithm verifies if the two string really are equal, rather than this being a fluke of the hashing scheme. It uses regular string comparison for this final check. RabinKarp is an algorithm of choice for multiple pattern search. If we want to find any of a large number, say k, fixed length patterns in a text, a variant RabinKarp that uses a hash table to check whether the hash of a given string belongs to a set of hash values of patterns we are looking for. Other algorithms can search for a single pattern in time order O(n), hence they will search for k patterns in time order O(n*k). The variant RabinKarp will still work in time order O(n) in the best and average case because a hash table allows to check whether or not substring hash equals any of the pattern hashes in time order of O(1).
Here is some code (not working though!)
#include
hashing_function()
{
// A hashing function to compute the hash values of the strings.
....
}
void KarpRabinR(char *x, int m, char *y, int n)
{
int hx, hy, i, j;
printf("\nstring : [%s]"
"\nlength : [%d]"
"\npattern : [%s]"
"\nlength : [%d]\n\n", y,n,x,m);
/* Preprocessing phase */
Do preprocessing here..
/* Searching */
j = 0;
while (j <= nm)
{
if (hx == hy && memcmp(x, y + j, m) == 0)
{
// Hashes match and so do the actual strings!
printf("\nMatch found at : [%d]\n",j);
}
hy = hashing_function(y[j], y[j + m], hy);
++j;
}
}
int main()
{
char *string="hereroheroero";
char *pattern="hero";
KarpRabin(pattern,strlen(pattern),string,strlen(string));
printf("\n\n");
return(0);
}
This is how the comparison happens visually
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
 > Hash values match, so do the strings!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
Method3
The KnuthMorrisPratt or the MorrisPratt algorithms are extensions of the basic Brute Force algorithm. They use precomputed data to skip forward not by 1 character, but by as many as possible for the search to succeed.
Here is some code
void preComputeData(char *x, int m, int Next[])
{
int i, j;
i = 0;
j = Next[0] = 1;
while (i < m)
{
while (j > 1 && x[i] != x[j])
j = Next[j];
Next[++i] = ++j;
}
}
void MorrisPrat(char *x, int m, char *y, int n)
{
int i, j, Next[1000];
/* Preprocessing */
preComputeData(x, m, Next);
/* Searching */
i = j = 0;
while (j < n)
{
while (i > 1 && x[i] != y[j])
i = Next[i];
i++;
j++;
if (i >= m)
{
printf("\nMatch found at : [%d]\n",j  i);
i = Next[i];
}
}
}
int main()
{
char *string="hereroheroero";
char *pattern="hero";
MorrisPrat(pattern,strlen(pattern),string,strlen(string));
printf("\n\n");
return(0);
}
This is how the comparison happens visually
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
 > Match found!
hero
hereroheroero
!
hero
Method4
The Boyer Moore algorithm is the fastest string searching algorithm. Most editors use this algorithm.
It compares the pattern with the actual string from right to left. Most other algorithms compare from left to right. If the character that is compared with the rightmost pattern symbol does not occur in the pattern at all, then the pattern can be shifted by m positions behind this text symbol.
The following example illustrates this situation.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b b a d a b a c b a
 
b a b a c 
< 

b a b a c
The comparison of "d" with "c" at position 4 does not match. "d" does not occur in the pattern. Therefore, the pattern cannot match at any of the positions 0,1,2,3,4, since all corresponding windows contain a "d". The pattern can be shifted to position 5. The best case for the BoyerMoore algorithm happens if, at each search attempt the first compared character does not occur in the pattern. Then the algorithm requires only O(n/m) comparisons .
Bad character heuristics
This method is called bad character heuristics. It can also be applied if the bad character (the character that causes a mismatch), occurs somewhere else in the pattern. Then the pattern can be shifted so that it is aligned to this text symbol. The next example illustrates this situation.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b b a b a b a c b a

b a b a c
<

b a b a c
Comparison between "b" and "c" causes a mismatch. The character "b" occurs in the pattern at positions 0 and 2. The pattern can be shifted so that the rightmost "b" in the pattern is aligned to "b".
Good suffix heuristics
Sometimes the bad character heuristics fails. In the following situation the comparison between "a" and "b" causes a mismatch. An alignment of the rightmost occurence of the pattern symbol a with the text symbol a would produce a negative shift. Instead, a shift by 1 would be possible. However, in this case it is better to derive the maximum possible shift distance from the structure of the pattern. This method is called good suffix heuristics.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b a a b a b a c b a
  
c a b a b
<
  
c a b a b
The suffix "ab" has matched. The pattern can be shifted until the next occurence of ab in the pattern is aligned to the text symbols ab, i.e. to position 2.
In the following situation the suffix "ab" has matched. There is no other occurence of "ab" in the pattern.Therefore, the pattern can be shifted behind "ab", i.e. to position 5.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b c a b a b a c b a
  
c b a a b
c b a a b
In the following situation the suffix "bab" has matched. There is no other occurence of "bab" in the pattern. But in this case the pattern cannot be shifted to position 5 as before, but only to position 3, since a prefix of the pattern "ab" matches the end of "bab". We refer to this situation as case 2 of the good suffix heuristics.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a a b a b a b a c b a
   
a b b a b
a b b a b
The pattern is shifted by the longest of the two distances that are given by the bad character and the good suffix heuristics.
The BoyerMoore algorithm uses two different heuristics for determining the maximum possible shift distance in case of a mismatch: the "bad character" and the "good suffix" heuristics. Both heuristics can lead to a shift distance of m. For the bad character heuristics this is the case, if the first comparison causes a mismatch and the corresponding text symbol does not occur in the pattern at all. For the good suffix heuristics this is the case, if only the first comparison was a match, but that symbol does not occur elsewhere in the pattern.
There are a number of ways to find a string inside another string. Its important to be aware of these algorithms than to memorize them. Some of the fastest algorithms are quite tough to understand!.
Method1
The first method is the classic Brute force method. The Brute Force algorithm checks, at all positions in the text between 0 and (nm), if an occurrence of the pattern starts at that position or not. Then, after each successfull or unsuccessful attempt, it shifts the pattern exactly one position to the right. The time complexity of this searching phase is O(mn). The expected number of text character comparisons is 2n.
Here 'n' is the size of the string in which the substring of size 'm' is being searched for.
Here is some code (which works!)
#include
void BruteForce(char *x /* pattern */,
int m /* length of the pattern */,
char *y /* actual string being searched */,
int n /* length of this string */)
{
int i, j;
printf("\nstring : [%s]"
"\nlength : [%d]"
"\npattern : [%s]"
"\nlength : [%d]\n\n", y,n,x,m);
/* Searching */
for (j = 0; j <= (n  m); ++j)
{
for (i = 0; i < m && x[i] == y[i + j]; ++i);
if (i >= m) {printf("\nMatch found at\n\n>[%d]\n>[%s]\n",j,y+j);}
}
}
int main()
{
char *string = "hereroheroero";
char *pattern = "hero";
BF(pattern,strlen(pattern),string,strlen(string));
printf("\n\n");
return(0);
}
This is how the comparison happens visually
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
 > Match!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
Method2
The second method is called the RabinKarp method.
Instead of checking at each position of the text if the pattern occurs or not, it is better to check first if the contents of the current string "window" looks like the pattern or not. In order to check the resemblance between these two patterns, a hashing function is used. Hashing a string involves computing a numerical value from the value of its characters using a hash function.
The RabinKarp method uses the rule that if two strings are equal, their hash values must also be equal. Note that the converse of this statement is not always true, but a good hash function tries to reduce the number of such hash collisions. RabinKarp computes hash value of the pattern, and then goes through the string computing hash values of all of its substrings and checking if the pattern's hash value is equal to the substring hash value, and advancing by 1 character every time. If the two hash values are the same, then the algorithm verifies if the two string really are equal, rather than this being a fluke of the hashing scheme. It uses regular string comparison for this final check. RabinKarp is an algorithm of choice for multiple pattern search. If we want to find any of a large number, say k, fixed length patterns in a text, a variant RabinKarp that uses a hash table to check whether the hash of a given string belongs to a set of hash values of patterns we are looking for. Other algorithms can search for a single pattern in time order O(n), hence they will search for k patterns in time order O(n*k). The variant RabinKarp will still work in time order O(n) in the best and average case because a hash table allows to check whether or not substring hash equals any of the pattern hashes in time order of O(1).
Here is some code (not working though!)
#include
hashing_function()
{
// A hashing function to compute the hash values of the strings.
....
}
void KarpRabinR(char *x, int m, char *y, int n)
{
int hx, hy, i, j;
printf("\nstring : [%s]"
"\nlength : [%d]"
"\npattern : [%s]"
"\nlength : [%d]\n\n", y,n,x,m);
/* Preprocessing phase */
Do preprocessing here..
/* Searching */
j = 0;
while (j <= nm)
{
if (hx == hy && memcmp(x, y + j, m) == 0)
{
// Hashes match and so do the actual strings!
printf("\nMatch found at : [%d]\n",j);
}
hy = hashing_function(y[j], y[j + m], hy);
++j;
}
}
int main()
{
char *string="hereroheroero";
char *pattern="hero";
KarpRabin(pattern,strlen(pattern),string,strlen(string));
printf("\n\n");
return(0);
}
This is how the comparison happens visually
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
 > Hash values match, so do the strings!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
Method3
The KnuthMorrisPratt or the MorrisPratt algorithms are extensions of the basic Brute Force algorithm. They use precomputed data to skip forward not by 1 character, but by as many as possible for the search to succeed.
Here is some code
void preComputeData(char *x, int m, int Next[])
{
int i, j;
i = 0;
j = Next[0] = 1;
while (i < m)
{
while (j > 1 && x[i] != x[j])
j = Next[j];
Next[++i] = ++j;
}
}
void MorrisPrat(char *x, int m, char *y, int n)
{
int i, j, Next[1000];
/* Preprocessing */
preComputeData(x, m, Next);
/* Searching */
i = j = 0;
while (j < n)
{
while (i > 1 && x[i] != y[j])
i = Next[i];
i++;
j++;
if (i >= m)
{
printf("\nMatch found at : [%d]\n",j  i);
i = Next[i];
}
}
}
int main()
{
char *string="hereroheroero";
char *pattern="hero";
MorrisPrat(pattern,strlen(pattern),string,strlen(string));
printf("\n\n");
return(0);
}
This is how the comparison happens visually
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
!
hero
hereroheroero
 > Match found!
hero
hereroheroero
!
hero
Method4
The Boyer Moore algorithm is the fastest string searching algorithm. Most editors use this algorithm.
It compares the pattern with the actual string from right to left. Most other algorithms compare from left to right. If the character that is compared with the rightmost pattern symbol does not occur in the pattern at all, then the pattern can be shifted by m positions behind this text symbol.
The following example illustrates this situation.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b b a d a b a c b a
 
b a b a c 
< 

b a b a c
The comparison of "d" with "c" at position 4 does not match. "d" does not occur in the pattern. Therefore, the pattern cannot match at any of the positions 0,1,2,3,4, since all corresponding windows contain a "d". The pattern can be shifted to position 5. The best case for the BoyerMoore algorithm happens if, at each search attempt the first compared character does not occur in the pattern. Then the algorithm requires only O(n/m) comparisons .
Bad character heuristics
This method is called bad character heuristics. It can also be applied if the bad character (the character that causes a mismatch), occurs somewhere else in the pattern. Then the pattern can be shifted so that it is aligned to this text symbol. The next example illustrates this situation.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b b a b a b a c b a

b a b a c
<

b a b a c
Comparison between "b" and "c" causes a mismatch. The character "b" occurs in the pattern at positions 0 and 2. The pattern can be shifted so that the rightmost "b" in the pattern is aligned to "b".
Good suffix heuristics
Sometimes the bad character heuristics fails. In the following situation the comparison between "a" and "b" causes a mismatch. An alignment of the rightmost occurence of the pattern symbol a with the text symbol a would produce a negative shift. Instead, a shift by 1 would be possible. However, in this case it is better to derive the maximum possible shift distance from the structure of the pattern. This method is called good suffix heuristics.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b a a b a b a c b a
  
c a b a b
<
  
c a b a b
The suffix "ab" has matched. The pattern can be shifted until the next occurence of ab in the pattern is aligned to the text symbols ab, i.e. to position 2.
In the following situation the suffix "ab" has matched. There is no other occurence of "ab" in the pattern.Therefore, the pattern can be shifted behind "ab", i.e. to position 5.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a b c a b a b a c b a
  
c b a a b
c b a a b
In the following situation the suffix "bab" has matched. There is no other occurence of "bab" in the pattern. But in this case the pattern cannot be shifted to position 5 as before, but only to position 3, since a prefix of the pattern "ab" matches the end of "bab". We refer to this situation as case 2 of the good suffix heuristics.
Example:
0 1 2 3 4 5 6 7 8 9 ...
a a b a b a b a c b a
   
a b b a b
a b b a b
The pattern is shifted by the longest of the two distances that are given by the bad character and the good suffix heuristics.
The BoyerMoore algorithm uses two different heuristics for determining the maximum possible shift distance in case of a mismatch: the "bad character" and the "good suffix" heuristics. Both heuristics can lead to a shift distance of m. For the bad character heuristics this is the case, if the first comparison causes a mismatch and the corresponding text symbol does not occur in the pattern at all. For the good suffix heuristics this is the case, if only the first comparison was a match, but that symbol does not occur elsewhere in the pattern.
Implement the memmove() function. What is the difference between the memmove() and memcpy() function?
One more most frequently asked interview question!.
memmove() offers guaranteed behavior if the source and destination arguments overlap. memcpy() makes no such guarantee, and may therefore be more efficient to implement. It's always safer to use memmove().
Note that the prototype of memmove() is ...
void *memmove(void *dest, const void *src, size_t count);
Here is an implementation..
#include
#include
void *mymemmove(void *dest, const void *src, size_t count);
int main(int argc, char* argv[])
{
char *p1, *p2;
char *p3, *p4;
int size;
printf("\n\n");
/* 
*
* CASE 1 : From (SRC) < To (DEST)
*
* ++++
*    
* ++++
* ^ ^
*  
* From To
*
*  */
p1 = (char *) malloc(12);
memset(p1,12,'\0');
size=10;
strcpy(p1,"ABCDEFGHI");
p2 = p1 + 2;
printf("\n\n");
printf("\nFrom (before) = [%s]",p1);
printf("\nTo (before) = [%s]",p2);
mymemmove(p2,p1,size);
printf("\n\nFrom (after) = [%s]",p1);
printf("\nTo (after) = [%s]",p2);
printf("\n\n");
/* 
*
* CASE 2 : From (SRC) > To (DEST)
*
* ++++
*    
* ++++
* ^ ^
*  
* To From
*
*  */
p3 = (char *) malloc(12);
memset(p3,12,'\0');
p4 = p3 + 2;
strcpy(p4, "ABCDEFGHI");
printf("\nFrom (before) = [%s]",p4);
printf("\nTo (before) = [%s]",p3);
mymemmove(p3, p4, size);
printf("\n\nFrom (after) = [%s]",p4);
printf("\nTo (after) = [%s]",p3);
printf("\n\n");
/* 
*
* CASE 3 : No overlap
*
*  */
p1 = (char *) malloc(30);
memset(p1,30,'\0');
size=10;
strcpy(p1,"ABCDEFGHI");
p2 = p1 + 15;
printf("\n\n");
printf("\nFrom (before) = [%s]",p1);
printf("\nTo (before) = [%s]",p2);
mymemmove(p2,p1,size);
printf("\n\nFrom (after) = [%s]",p1);
printf("\nTo (after) = [%s]",p2);
printf("\n\n");
printf("\n\n");
return 0;
}
void *mymemmove(void *to, const void *from, size_t size)
{
unsigned char *p1;
const unsigned char *p2;
p1 = (unsigned char *) to;
p2 = (const unsigned char *) from;
p2 = p2 + size;
// Check if there is an overlap or not.
while (p2 != from && p2 != to);
if (p2 != from)
{
// Overlap detected!
p2 = (const unsigned char *) from;
p2 = p2 + size;
p1 = p1 + size;
while (size != 0)
{
*p1 = *p2;
}
}
else
{
// No overlap OR they overlap as CASE 2 above.
// memcopy() would have done this directly.
while (size != 0)
{
*p1++ = *p2++;
}
}
return(to);
}
And here is the output

From (before) = [ABCDEFGHI]
To (before) = [CDEFGHI]
From (after) = [ABABCDEFGHI]
To (after) = [ABCDEFGHI]

From (before) = [ABCDEFGHI]
To (before) = [α╙ABCDEFGHI]
From (after) = [CDEFGHI]
To (after) = [ABCDEFGHI]

From (before) = [ABCDEFGHI]
To (before) = [FEδ‼&:F]
From (after) = [ABCDEFGHI]
To (after) = [ABCDEFGHI]

So then, whats the difference between the implementation of memmove() and memcpy(). Its just that memcpy() will not care if the memories overlap and will either copy from left to right or right to left without checking which method to used depending on the type of the overlap. Also note that the C code proves that the results are the same irrespective of the Endianness of the machine.
memmove() offers guaranteed behavior if the source and destination arguments overlap. memcpy() makes no such guarantee, and may therefore be more efficient to implement. It's always safer to use memmove().
Note that the prototype of memmove() is ...
void *memmove(void *dest, const void *src, size_t count);
Here is an implementation..
#include
#include
void *mymemmove(void *dest, const void *src, size_t count);
int main(int argc, char* argv[])
{
char *p1, *p2;
char *p3, *p4;
int size;
printf("\n\n");
/* 
*
* CASE 1 : From (SRC) < To (DEST)
*
* ++++
*    
* ++++
* ^ ^
*  
* From To
*
*  */
p1 = (char *) malloc(12);
memset(p1,12,'\0');
size=10;
strcpy(p1,"ABCDEFGHI");
p2 = p1 + 2;
printf("\n\n");
printf("\nFrom (before) = [%s]",p1);
printf("\nTo (before) = [%s]",p2);
mymemmove(p2,p1,size);
printf("\n\nFrom (after) = [%s]",p1);
printf("\nTo (after) = [%s]",p2);
printf("\n\n");
/* 
*
* CASE 2 : From (SRC) > To (DEST)
*
* ++++
*    
* ++++
* ^ ^
*  
* To From
*
*  */
p3 = (char *) malloc(12);
memset(p3,12,'\0');
p4 = p3 + 2;
strcpy(p4, "ABCDEFGHI");
printf("\nFrom (before) = [%s]",p4);
printf("\nTo (before) = [%s]",p3);
mymemmove(p3, p4, size);
printf("\n\nFrom (after) = [%s]",p4);
printf("\nTo (after) = [%s]",p3);
printf("\n\n");
/* 
*
* CASE 3 : No overlap
*
*  */
p1 = (char *) malloc(30);
memset(p1,30,'\0');
size=10;
strcpy(p1,"ABCDEFGHI");
p2 = p1 + 15;
printf("\n\n");
printf("\nFrom (before) = [%s]",p1);
printf("\nTo (before) = [%s]",p2);
mymemmove(p2,p1,size);
printf("\n\nFrom (after) = [%s]",p1);
printf("\nTo (after) = [%s]",p2);
printf("\n\n");
printf("\n\n");
return 0;
}
void *mymemmove(void *to, const void *from, size_t size)
{
unsigned char *p1;
const unsigned char *p2;
p1 = (unsigned char *) to;
p2 = (const unsigned char *) from;
p2 = p2 + size;
// Check if there is an overlap or not.
while (p2 != from && p2 != to);
if (p2 != from)
{
// Overlap detected!
p2 = (const unsigned char *) from;
p2 = p2 + size;
p1 = p1 + size;
while (size != 0)
{
*p1 = *p2;
}
}
else
{
// No overlap OR they overlap as CASE 2 above.
// memcopy() would have done this directly.
while (size != 0)
{
*p1++ = *p2++;
}
}
return(to);
}
And here is the output

From (before) = [ABCDEFGHI]
To (before) = [CDEFGHI]
From (after) = [ABABCDEFGHI]
To (after) = [ABCDEFGHI]

From (before) = [ABCDEFGHI]
To (before) = [α╙ABCDEFGHI]
From (after) = [CDEFGHI]
To (after) = [ABCDEFGHI]

From (before) = [ABCDEFGHI]
To (before) = [FEδ‼&:F]
From (after) = [ABCDEFGHI]
To (after) = [ABCDEFGHI]

So then, whats the difference between the implementation of memmove() and memcpy(). Its just that memcpy() will not care if the memories overlap and will either copy from left to right or right to left without checking which method to used depending on the type of the overlap. Also note that the C code proves that the results are the same irrespective of the Endianness of the machine.
Subscribe to:
Posts (Atom)