Showing posts with label c. Show all posts
Showing posts with label c. Show all posts

2014-09-19

Write C code to implement the Binary Search algorithm

Code - C function

int binarySearch(int arr[],int size, int item)
{
 int left, right, middle;
 left = 0;
 right = size-1;
    while(left<=right)
    {
        middle = ((left + right)/2);
        if(item == arr[middle])
        {
        94
        return(middle);
        }
        if(item > arr[middle])
        {
        left = middle+1;
        }
        else
        {
        right = middle-1;
    }
}
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 convert a decimal number into a binary number

99% of the people who attend interviews can't answer this question, believe me!. Here is a C program which does this....

Programming Code

#include<stdio.h>
generatebits(int num)
{
int temp;
if(num)
{
temp = num % 2;
bit(num >>= 1);
printf("%d",temp);
}
}
int main()
{
int num;
while(1)
{
scanf("Enter a number : %d",&num);
printf("\n\n");
generatebits(num);
}
getch();
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];
}
}

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]);

}
}

Solve the Rat In A Maze problem using backtracking

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
o Moving right means adding {0,1} to the current coordinates.
o Moving left means adding {0,-1} to the current coordinates.
o Moving up means adding {-1,0} to the current coordinates.
o 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 one-by-one, 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(n-1) + F(n-2)

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[i-1] + f[i-2];
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(n-1) + fib(n-2)
}
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(n-1) ]
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 n-th 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 n-th Fibonacci number. Here is the pseudocode for this
int Matrix[2][2] = {{1,0}{0,1}}
int fib(int n)
{
matrixpower(n-1);
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<stdio.h>
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(n-1);
// 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 - ((1-sqrt(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.

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)re
turn(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, y-1) ;
}

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 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 nonr-ecursive (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 <stdio.h>
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)-pos-1]
ch = str[pos];
str[pos]=str[strlen(str)-pos-1];
str[strlen(str)-pos-1]=ch;
// Now recurse!
reverse(pos+1);
}
}


Method2
#include <stdio.h>
#include <malloc.h>
#include <string.h>
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(N-i-1);
String reverse = new String(a);
return reverse;
}

C program for calculating the factorial of a number

Here is a recursive C program
fact(int n)
{
int fact;
if(n==1)
62
return(1);
else
fact = n * fact(n-1);
return(fact);
}
Please note that there is no error handling added to this function (to check if n is negative or 0. Or if n is too large for the system to handle). This is true for most of the answers in this website. Too much error handling and standard compliance results in a lot of clutter making it difficult to concentrate on the crux of the solution. You must of course add as much error handling and comply to the standards of your compiler when you actually write the code to implement these algorithms.

C program to swap two variables without using a temporary variable

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 floating-point 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=a-b;
a=a-b;
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 po
ssible).
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.

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);
}

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<stdio.h>
#include<stdarg.h>
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));b
reak;
case 's': s=va_arg(argp,char *); puts(s); break;
case 'u': u=va_arg(argp,argp, unsigned int); puts(convert(u
,10));break;
47
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);
}

Tools & Plugins