Saturday, 23 February 2019

C# Programs

Reverse a number

 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter a Number");
            int numb = int.Parse(Console.ReadLine());
            int reverse = 0;
            while (numb > 0)
            {
                int rem = numb % 10;
                reverse = (reverse * 10) + rem;
                numb = numb / 10;
              
            }
            Console.WriteLine("Reverse number={0}", reverse);
            Console.ReadLine();
        }

    }

Output
----------

Enter a Number
4567
Reverse number=7654


Palindrome Program

class program
{
    public static void Main()
    {
        int num, temp, remainder, reverse = 0;
        Console.WriteLine("Enter an integer \n");
        num = int.Parse(Console.ReadLine());
        temp = num;
        while (num > 0)
        {
            remainder = num % 10;
            reverse = reverse * 10 + remainder;
            num /= 10;
        }
        Console.WriteLine("Given number is = {0}", temp);
        Console.WriteLine("Its reverse is  = {0}", reverse);
        if (temp == reverse)
            Console.WriteLine("Number is a palindrome \n");
        else
            Console.WriteLine("Number is not a palindrome \n");
        Console.ReadLine();
    }
}

//Output--535 is a prime number(if its reverse also 535 only)

Armstrong Number

An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself.

class Program
    {
        static void Main(string[] args)
        {
            int number, remainder, sum = 0;
            Console.Write("enter the Number");
            number = int.Parse(Console.ReadLine());
            for (int i = number; i > 0; i = i / 10)
            {
                remainder = i % 10;
                sum = sum + remainder*remainder*remainder;

            }
            if (sum == number)
            {
                Console.Write("Entered Number is an Armstrong Number");
            }
            else
                Console.Write("Entered Number is not an Armstrong Number");
            Console.ReadLine();
        }
     }

Output
----------

Enter the Number : 371

Entered Number is an Armstrong Number

Explantion:3Cube+7cube+1cube=371

Sum of given Number

static void Main(string[] args)
        {
            int num, sum = 0, r;
            Console.WriteLine("Enter a Number : ");
            num = int.Parse(Console.ReadLine());
            while (num != 0)
            {
                r = num % 10;
                num = num / 10;
                sum = sum + r;
            }
            Console.WriteLine("Sum of Digits of the Number : "+sum);
            Console.ReadLine();

        }
//Output--Enter a Number : 123
//Sum of Digits of the Number : 6
          

Prime Numbers Between 1 to 10

class Program
{
    static void Main(string[] args)
    {
        bool isPrime = true;
        Console.WriteLine("Prime Numbers : ");
        for (int i = 2; i <= 10; i++)
        {
            for (int j = 2; j <= 10; j++)
            {

                if (i != j && i % j == 0)
                {
                    isPrime = false;
                    break;
                }

            }
            if (isPrime)
            {
                Console.Write("\t" + i);
            }
            isPrime = true;
        }
        Console.ReadKey();
    }

}


//output--2 3 5 7


strong number 
A number is called strong number if sum of the factorial of its digit is equal to number itself.
Ex : 1! + 4! + 5! = 1 + 24 + 120 = 145

Code:
static void Main(string[] args)
{
Int32 num, i, f, r, sum = 0, temp;

Console.WriteLine("enter the number");
num = Convert.ToInt16((Console.ReadLine()));
temp=num;
while (num != 0)
{
   i = 1; f = 1;

   r = num % 10;
     while (i <= r)
     {
        f = f * i;
        i++;
     }

sum = sum + f;
num = num / 10;
}
if (sum == temp)
Console.WriteLine("Strong No", temp);

else
Console.WriteLine("not Strong NO", temp); 

Console.ReadLine();

}

Number sort
int temp = 0;
        int[] arr = new int[] { 20, 65, 98, 71, 64, 11, 2, 80, 5, 6, 100, 50, 13, 9, 80, 454 };
        for (int i = 0; i < arr.Length; i++)
        {
            for (int j = i + 1; j < arr.Length; j++)
            {
                if (arr[i] > arr[j])
                {
                    temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                }
            }
            Console.WriteLine(arr[i]);
        }
string reverse
static void Main(string[] args)
    {
        string Str, reversestring = "";
        int Length;
        Console.Write("Enter A String : ");
        Str = Console.ReadLine();
        Length = Str.Length - 1;
        while (Length >= 0)
        {
            reversestring = reversestring + Str[Length];
            Length--;
        }
        Console.WriteLine("Reverse  String  Is  {0}", reversestring);
        Console.ReadLine();
    }

collasition?

swap even and odd characters in a string

static void Main(string[] args)
        {
            string input = "Gupta"; //Sample String
            // O/P--uGtpa
            StringBuilder output = new StringBuilder();

            char[] characters = input.ToCharArray();

            for (int i = 0; i < characters.Length; i++)
            {
                if (i % 2 == 0)
                {
                    if ((i + 1) < characters.Length)
                    {
                        output.Append(characters[i + 1]);
                    }
                    output.Append(characters[i]);
                }
            }

            Console.WriteLine(output);
            Console.ReadLine();
        }

 

 remove duplicate characters from string.


 void removeDuplicate()
    {
      string value1 = RemoveDuplicateChars("Devarajan");
    }

     static string RemoveDuplicateChars(string key)
    {

        string table = "";
        string result = "";          
        foreach (char value in key)
        {
            if (table.IndexOf(value) == -1)
            {
                table += value;
                result += value;
            }
        }
        return result;
    }
Number of occurrences in a given string
 static void Main(string[] args)
        {
            string input = "ABCA";
            while (input.Length > 0)
            {
                Console.Write(input[0] + " : ");
                int count = 0;
                for (int j = 0; j < input.Length; j++)
                {
                    if (input[0] == input[j])
                    {
                        count++;
                    }
                }
                Console.WriteLine(count);
                input = input.Replace(input[0].ToString(), string.Empty);
            }
            Console.ReadLine();
        }
        //O/P
        //A-2
        //B-1
        //C-1


Monday, 4 February 2019

IQ

1) Why we use Generics ?

Benefits

The following are the benefits of generics:

  • There is no need for casting for accessing the elements of the data.
  • Code is not duplicated for multiple types of data.
  • Generics can hold the data with the same type and we can decide what type of data that the collection holds.
  • You can create your own generic interface, classes, method, events and delegate.
Why to use Generics

There are mainly two reasons to use generics as in the following:

  1. Performance: Collections that store the objects uses boxing and unboxing on data types. A collection can reduce the performance.
    By using generics it helps to improve the performance and type safety.
  2. Type Safety: there is no strong type information at compile time as to what it is stored in the collection.

When to use Generics

  • When you use various #ff0000 data types, you need to create a generic type.
  • It is easier to write code once and reuse it for multiple types.
  •  If you are working on a value type then for that boxing and unboxing operation will occur, Generics will eliminate the boxing and unboxing operations.


2) why is used static constructor ?
3) Can we create instance for static constructor and why?
4) Can we pass parameters to static constructor and why?
5) What is managed and unmanaged code where its executed?
6) Give me examples for managed and unmanaged code?
7) How the memory allocation and deallocation will be happed for manged and unmanaged code?
8) What is anonymous function and why its used?
9) what is lambda expression?
10) Difference between lambda and LINQ?
11) C# Method to return a boolean from a lambda expression?
12) How Dispose method works in c#?
13) How garbage collector deallocate the memory?
14) Bundling and minification how its works in mvc?
15)String reverse program
16) Default access modifier for static constructor?

SQL Server database design and performance

  1. Choose Appropriate Data Type

    Choose appropriate SQL Data Type to store your data since it also helps in to improve the query performance. Example: To store strings use varchar in place of text data type since varchar performs better than text. Use text data type, whenever you required storing of large text data (more than 8000 characters). Up to 8000 characters data you can store in varchar.
  2. Avoid nchar and nvarchar

    Practice to avoid nchar and nvarchar data type since both the data types takes just double memory as char and varchar. Use nchar and nvarchar when you required to store Unicode (16-bit characters) data like as Hindi, Chinese characters etc.
  3. Avoid NULL in fixed-length field

    Practice to avoid the insertion of NULL values in the fixed-length (char) field. Since, NULL takes the same space as desired input value for that field. In case of requirement of NULL, use variable-length (varchar) field that takes less space for NULL.
  4. Avoid * in SELECT statement

    Practice to avoid * in Select statement since SQL Server converts the * to columns name before query execution. One more thing, instead of querying all columns by using * in select statement, give the name of columns which you required.
    1. -- Avoid
    2. SELECT * FROM tblName
    3. --Best practice
    4. SELECT col1,col2,col3 FROM tblName
  5. Use EXISTS instead of IN

    Practice to use EXISTS to check existence instead of IN since EXISTS is faster than IN.
    1. -- Avoid
    2. SELECT Name,Price FROM tblProduct
    3. where ProductID IN (Select distinct ProductID from tblOrder)
    4. --Best practice
    5. SELECT Name,Price FROM tblProduct
    6. where ProductID EXISTS (Select distinct ProductID from tblOrder)
  6. Avoid Having Clause

    Practice to avoid Having Clause since it acts as filter over selected rows. Having clause is required if you further wish to filter the result of an aggregations. Don't use HAVING clause for any other purpose.
  7. Create Clustered and Non-Clustered Indexes

    Practice to create clustered and non clustered index since indexes helps in to access data fastly. But be careful, more indexes on a tables will slow the INSERT,UPDATE,DELETE operations. Hence try to keep small no of indexes on a table.
  8. Keep clustered index small

    Practice to keep clustered index as much as possible since the fields used in clustered index may also used in nonclustered index and data in the database is also stored in the order of clustered index. Hence a large clustered index on a table with a large number of rows increase the size significantly. Please refer the article Effective Clustered Indexes
  9. Avoid Cursors

    Practice to avoid cursor since cursor are very slow in performance. Always try to use SQL Server cursor alternative. Please refer the article Cursor Alternative.
  10. Use Table variable inplace of Temp table

    Practice to use Table varible in place of Temp table since Temp table resides in the TempDb database. Hence use of Temp tables required interaction with TempDb database that is a little bit time taking task.
  11. Use UNION ALL inplace of UNION

    Practice to use UNION ALL in place of UNION since it is faster than UNION as it doesn't sort the result set for distinguished values.
  12. Use Schema name before SQL objects name

    Practice to use schema name before SQL object name followed by "." since it helps the SQL Server for finding that object in a specific schema. As a result performance is best.
    1. --Here dbo is schema name
    2. SELECT col1,col2 from dbo.tblName
    3. -- Avoid
    4. SELECT col1,col2 from tblName
  13. Keep Transaction small

    Practice to keep transaction as small as possible since transaction lock the processing tables data during its life. Some times long transaction may results into deadlocks. Please refer the article SQL Server Transactions Management
  14. SET NOCOUNT ON

    Practice to set NOCOUNT ON since SQL Server returns number of rows effected by SELECT,INSERT,UPDATE and DELETE statement. We can stop this by setting NOCOUNT ON like as:
    1. CREATE PROCEDURE dbo.MyTestProc
    2. AS
    3. SET NOCOUNT ON
    4. BEGIN
    5. .
    6. .
    7. END
  15. Use TRY-Catch

    Practice to use TRY-CATCH for handling errors in T-SQL statements. Sometimes an error in a running transaction may cause deadlock if you have no handle error by using TRY-CATCH. Please refer the article Exception Handling by TRY…CATCH
  16. Use Stored Procedure for frequently used data and more complex queries

    Practice to create stored procedure for quaery that is required to access data frequently. We also created stored procedure for resolving more complex task.
  17. Avoid prefix "sp_" with user defined stored procedure name

    Practice to avoid prefix "sp_" with user defined stored procedure name since system defined stored procedure name starts with prefix "sp_". Hence SQL server first search the user defined procedure in the master database and after that in the current session database. This is time consuming and may give unexcepted result if system defined stored procedure have the same name as your defined procedure.