Thursday, May 30, 2013

What is a Self join in SQL? Explain with examples. (SQL)

Self join is just like any other join, except that two instances of the same table will be joined in the query.
Here is an example: Employees table which contains rows for normal employees as well as managers. So, to find out the managers of all the employees, you need a self join.
CREATE TABLE emp
(
empid int,
mgrid int,
empname char(10)
)

INSERT emp SELECT 1,2,'Vyas'
INSERT emp SELECT 2,3,'Mohan'
INSERT emp SELECT 3,NULL,'Shobha'
INSERT emp SELECT 4,2,'Sridhar'
INSERT emp SELECT 5,2,'Sourabh'

//Query which will return employees who have managers

SELECT t1.empname [Employee], t2.empname [Manager]
FROM emp t1, emp t2
WHERE t1.mgrid = t2.empid

//Query using a LEFT OUTER JOIN that returns the employees without managers (super bosses)

SELECT t1.empname [Employee], COALESCE (t2.empname, 'No Manager') [Manager]
FROM emp t1
LEFT OUTER JOIN emp t2
ON t1.mgrid =t2.empid


 

Monday, May 27, 2013

String Reversal (C#)

class Program()
{
static void Main()
{
string str = "this is a string";
char[] charArr = str.ToCharArray();
StringBuilder build = new StringBuilder();

for (int i = charArr.lenght-1; i >=0; i--)
{
build.Append(charArr[i]);
}
Console.WriteLine(build.ToString());
Console.ReadKey();
}
}

What is the difference between a ref and out keyword? (C#)

The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed. For example:
class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value; Method(out value);
        // value is now 44     }
}

class RefExample
    {
        static void Method(ref int i)
        {
           // The following statement would cause a compiler error if 'i' were boxed as an object.            

 i = i + 44;
        }
        static void Main()
        {
            int val = 1;
            Method(ref val);
            Console.WriteLine(val);
            // Output: 45         }
    }
Although variables passed as an out arguments need not be initialized prior to being passed, the calling method is required to assign a value before the method returns.

The ref and out keywords are treated differently at run-time, but they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument. These two methods, for example, are identical in terms of compilation, so this code will not compile.

class CS0663_Example
{
    // compiler error CS0663: "cannot define overloaded methods that differ only on ref and out"     public void SampleMethod(out int i) {  }
    public void SampleMethod(ref int i) {  }
}

Overloading can be done, however, if one method takes a ref or out argument and the other uses neither, like this:

class RefOutOverloadExample
{
    public void SampleMethod(int i) {  }
    public void SampleMethod(out int i) {  }
}

Find the sum of all natural numbers which are multiples of 3 and 5 below 1000. (C#)

Question


If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

Solution


static void Main()
{
//List all numbers below 100 which are multiples of 3 or 5
List Multiples = new List();
for (int i=0; i<1000 i="" int="">
{
if (i%3 ==0) || (i%5==0)
{
Multiples.Add(i);
}
}
Console.Write (Multiple.Sum());
Console.ReadKey();
 
 

Write a method to print out multiplication tables (C#)

Question


Write a method where when you input a number, it prints out a multiplication table of column header times row headers up to the input number. For example, if input = 2, it would write a table with 1 times 1, 1 times 2, 2 times 1 and 2 times 2.

Solution


class Program
{
static void Main ()
{
int input = 10;
if (input <=0)
{
Console.Write("No table");
}
else
{
int[ , ] table = new int[input,input];
 for(int i =0; I < input; i++)
 {
 for (int j =0; j < input; j++)
 {table[i,j] = (i+1) * (j+1);}
}
}
foreach (var i in table)
{
Console.write(i);
Console.Write(Environment.NewLine);
}
}
Console.Readkey();
}



 
 




 

Saturday, May 25, 2013

Write a method to find all prime numbers between 50 and 100

class Program
{
static void Main()
{
//Call the method to check for prime numbers and only print if the number is prime.
for (int x=50;  x<101 p="" x="">{
bool result = IsPrime(x);
if (result == true)
Console.Writeline("{0} is a prime number", x);
}
Console.ReadKey();
}

public static bool IsPrime(int n)
{
//negative numbers, 0 and 1 are not prime numbers
if ( n<= 1)
return false;

else
{
//you need to divide a number only by 2,3,5,7

int [] primeNumDivisors = new int[]{2,3,5,7};

foreach (int I in primeNumDivisors)
{
// no need to divide the number by itself
if ( n ! =I)
{
if (n% i ==0)
return false;
}
}
return true;
}
}
}
 


 

Tuesday, May 21, 2013

Sort Algorithms (C#)

Quick sort


The quick sort function starts its work by selecting a random value from the unsorted list. This value is called the pivot value. Then we remove the pivot value from the unsorted list.
Now each element x in the unsorted list is compared with this pivot. We have two other lists 'Less' and 'Greater'.
if any element is less than the pivot, it is placed in the 'Less' list and if it is greater than the pivot value, it is placed in the 'Greater' list. Then we call the concat function with three arguments in it.
1.List name 'Less'
2.Variable Pivot
3.List Name 'Greater

Using System;
Using System.Collection.Generic;
Using System.Linq;
Using System.Text;

namespace SortAlgorithms
{
class Quicksort
{
public List QuickSort1(List a)
{
List Less = new List();
List Greater = new List();
if (a.Count<=1)
return a;
Random R = new Random();
int pos = R.Next(0,a.Count);
int pivot = a[pos];
a.RemoveAt(pos);
foreach(int i in a)
{
if  (i < pivot)
{
Less.Add(i);
}
else
{
Greater.Add(i);
}
}
return Concat(QuickSort1(Less), pivot, QuickSort1(Greater);

 

/* The concat function here performs a very important role, the quicksort algorithm uses the recursive approach throgh concat function. 
Here concat function receives the three arguments, two lists and pivot value.  
We have defined a new list of integers here name sorted.  
It concats the less, pivot and greater all together in sorted list and then returns this sorted list to quicksort method.  
The quicksort method receives this sorted list and then returns the sorted list to the function  
which sends the unsorted list to quicksort method.*/
 
public List Concat(List Less, int pivot, List Greater)
{
List Sorted = new List(Less);
Sorted.Add(pivot);
foreach (int g in Greater)
{
Sorted.Add(g);
}
return Soretd;
}
}
}
------------------------------------------------------------------------------------------------------------

Merge Sort


Merge Sort is able to rearrange elements of a list in ascending order. Merge sort works as a divide and conquer algorithm. It recursively divide the list into two halves until one element left, and merge the already sorted halves into a sorted one list.
------------------------------------------------------------------------------------------------------------

Bubble Sort



In bubble sort, each element of the unsorted list is compared to the next element and if the value of first element is greater than the value of the second element, then they are swapped. The same is applied again and again until every element gets compared with the whole list.
The result may have ascending or descending sorted elements.The bubble sort consists on the passes. The number of passes depends on the number of elements in the list. More elements means more passes.
It consists of the two loops - a main loop and a nested loop. The main loop describes the number of passes and the nested loops defined the number of comparisons.
The bubblesort is easy to implement but it is a slow sorting algorithm. It traverses each and every element of the unsorted list in every case. That's why it has the worst case and average case complexity as 0(n2).

using System;
using System.Collection.Generic;
using System.Linq;
using System.Text;

namespace SortAlgorithms
{
class BubbleSort
{
public List BubbleSort1(List Input)
{
int temp;
for (int i =1; i < Input.Count; i++)
{
for (int j=0; j< Input.count - 1; j++)
{
if (Input[j] > Input [j+1])
{
temp =Input[j];
Input[j] = Input [j+1];
Input[j+1] = temp;
}
}
}
return Input;
}
}
}
 
 
 

 

Monday, May 20, 2013

Write a method to find how many times a substring occurs in a string (C#)


//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace Excercises
{
 class Program
{
 static void Main(string[] args)
{
 //Write a method to find how many times a substring occurs in a string
string find = "and";
string input = "ROME — Italy's high court on Tuesday faulted the appeals court that acquitted American student Amanda Knox of murdering her roommate, saying its ruling was full of deficiencies, contradictions and illogical conclusions and ordering the new appeals court to look at all the evidence to determine whether Knox helped kill the teen";
char[] delimiters = { ' ', ',', '.', ';', '-' };
string[] words = input.Split(delimiters);
int count = 0;
foreach (var word in words)
{
 if (word.ToLower() == find.ToLower())
{
count++;
}
}
Console.WriteLine("The word '{0}' was found {1} times", find, count);
Console.ReadKey();
}
}
}