Another One For Interview … This Time Recursion

Recursion has been famous technique of eliminating loop and breaking the execution of code into regular call of methods.
Some times your interview is going good and there comes recursion which just shocks you….
It is simple but it’s simplicity makes you in trouble especially during strict time bound interview.
Basically recursion is a technique of calling a method from it’s own method.
It is similar to divide and break the complex logic into simple executable code.
Key to remember before starting to code any recursion solution is this equation

F(n)=F(x) + – F(n)

.
Where F(n) calls it self multiple times using the old value.

Let say we have to multiply two positive unknown values without using the multiplication sign.
So the function would
F(0) =b+F(1) —– F(1)=b+F(0) …. and so on ….

So lets write the code.

using System;

public class Test
{
public static void Main()
{
int d= multiply (10,2);
Console.WriteLine(d);
}
public static int multiply(int a,int b)
{
if(b==0)
{
return 0;
}
else
{
return a+multiply(a,b-1);
}
}
}

 

Here you can see the function is calling itself and reusing the old returned value until and unless value becomes 0. We can do factorial and division using the same technique with little bit enhancement.

 

Advertisements

Interview-Example of Model View Controller In Real World

This is another simple question which was asked to me in an interview.
As all interviewer requires real world example of every concept so the MVC (Model View Controller) application can be seen in a Calculator.

The buttons is the Controller.-> when you press the add button request is send to model.
The back end hidden knowledge is Model-> When you press the add button some business logic runs let say two number are added in the calculator then the answer is send to view.

The Display is View->The View is responsible to display the result.

mvcdiagram

Interview-How To Store Directory Structure In Database

This was asked in an interview question that what will be the data structure schema of database if you  are given to save folder and they have files stored in it and also they contain sub folders in it.

So the best schema for this type of problem is that we will only require one table.
Yes one Table will do the job and more interestingly only 3 fields are enough to save  this information.

Field Name      –   Key                    – Data Type – Nullable

1). Dir                 – Primary Key   -int                   – Not Null
2). Dir_Parent –  Foreign Key   -int                   – Null Allowed
3). Description – Null                 -Varchar          – Not Null

dirdbschema

Here on top is the description of how data will be save in database using one table and .