Archive | C – Fresher questions

c training- program for 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?);
}

Posted in C - Fresher questions3 Comments

c training- program for 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(n-1, from, temp, to);
printf("\nMove disk %d from %c to %c\n", n, from, to);
tower_of_hanio(n-1, temp, to, from);
}
}

Posted in C - Fresher questions0 Comments

c training- How to find endianness ?

First of all, Do you know what Little-Endian and Big-Endian 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, 32-bit 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 high-order 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("\nLittle-Endian\n");
}
else
{
printf("Big-Endian\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));
}

Posted in C - Fresher questions0 Comments

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

Posted in C - Fresher questions0 Comments

c training- program for generating fibonacci numbers? How to find out if a given number is a fibonacci number or not?

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.

Posted in C - Fresher questions0 Comments

c training- program for calculating 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..R-1] 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 divide-and-conquer

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.

Posted in C - Fresher questions1 Comment

c training- program for 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;
}

Posted in C - Fresher questions3 Comments

c training- program for calculating 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.

Posted in C - Fresher questions0 Comments

c training- program for calculating factorial of a number.

Here is a recursive C program

fact(int n)
{
int fact;
if(n==1)
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 ofcourse add as much error handling and comply to the standards of your compiler when you actually write the code to implement these algorithms.

Posted in C - Fresher questions0 Comments

c training- program for generating 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[m-1]); */
temp=list[i];
list[i]=list[m-1];
list[m-1]=temp;

permute(list,k,m-1);

/* swap(a[m-1],a[i]); */

temp=list[m-1];
list[m-1]=list[i];
list[i]=temp;
}
}
}

Posted in C - Fresher questions0 Comments