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

Writing Your First Hello World Console Application in C#


In the following text, we will build our first C# application with, and then without, Visual Studio.Net. We will see how to write, compile, and execute the C# application. Later in the chapter, we will explain the different concepts in the program.



Open Notepad, or any other text editor, and write the following code:



using System;
namespace MyHelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine("Hello World,Welcome to http://www.codesforprogrammers.blogspot.com/ ");
}
}
}



Save this with any file name with the extension ".cs". Example: 'MyFirstApplication.cs' To compile this file, go to command prompt and write:



csc MyFirstApplication.cs


This will compile your program and create an .exe file (MyFirstApplication.exe) in the same directory and will report any errors that may occur.
To run your program, type:


MyFirstApplication


This will print Hello World,Welcome to http://www.codesforprogrammers.blogspot.com/ as a result on your console screen. So simple, isn't it? Let's do the same procedure with Visual Studio.Net:



With Visual Studio.Net



Start Microsoft Visual Studio.Net and select File - New - Project; this will show the open file dialog. Select Visual C# Project from Project Type and select Console Application from Template. Write MyHelloWorldApplication in the name text box below and click OK.


Writing Your First Hello World Console Application in C#


Now to compile and execute your application, select Debug - Start Without Debugging or press Ctrl+F5. This will open a new Console Window with Hello World written in it. Once you press any key, the window will close,terminating the program.

Namespaces in C#


A Namespace is simply a logical collection of related classes in C#. We bundle our related classes (like those related with database activity) in some named collection calling it a namespace (e.g., DataActivity). As C# does not allow two classes with the same name to be used in a program, the sole purpose of using namespaces is to prevent name conflicts. This may happen when you have a large number of classes, as is the case in the Framework Class Library (FCL). It is very much possible that our Connection Class in DataActivity conflicts with the Connection Class of InternetActivity. To avoid this, these classes are made part of their respective namespace. So the fully qualified name of these classes will be DataActivity.Connection and InternetActivity.Connection, hence resolving any ambiguity for the compiler.



So, in the second line of our program we are declaring that the following classes (within { } block) are part of
MyHelloWorldApplication namespace.





namespace MyHelloWorldApplication
{
...
}




  • The C# namespaces have NO physical mapping as is the case in Java. Classes with same namespace can be in different folders.

  • The namespace may contain classes, events, exceptions, delegates and even other namespaces called Internal namespace.


These internal namespaces can be defined like this:





namespace Parent
{
namespace Child
{
...
}
}

Bubble Sort Algorithm

Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing two items at a time and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort.Bubble sort has worst-case and average complexity both О(n²), where n is the number of items being sorted. There exist many sorting algorithms with the substantially better worst-case or average complexity of O(n log n). Even other О(n²) sorting algorithms, such as insertion sort,tend to have better performance than bubble sort. Therefore bubble sort is not a practical sorting algorithm when n is large.The positions of the elements in bubble sort will play a large part in determining its performance. Large elements at the beginning of the list do not pose a problem, as they are quickly swapped. Small elements towards the end, however, move to the beginning extremely slowly. This has led to these types of elements being named rabbits and turtles, respectively

Example

Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest number using bubble sort algorithm. In each step, elements written in bold are being compared.

First Pass:
( 5 1 4 2 8 ) --- ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps them.
( 1 5 4 2 8 ) --- ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) --- ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) --- ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

Second Pass:
( 1 4 2 5 8 ) --- ( 1 4 2 5 8 )
( 1 4 2 5 8 ) --- ( 1 2 4 5 8 )
( 1 2 4 5 8 ) --- ( 1 2 4 5 8 )
( 1 2 4 5 8 ) --- ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. Algorithm needs one whole pass without any swap to know it is sorted.

Third Pass:
( 1 2 4 5 8 ) --- ( 1 2 4 5 8 )
( 1 2 4 5 8 ) --- ( 1 2 4 5 8 )
( 1 2 4 5 8 ) --- ( 1 2 4 5 8 )
( 1 2 4 5 8 ) --- ( 1 2 4 5 8 )
Finally, the array is sorted, and the algorithm can terminate.

Source Code

// array of integers to hold values
private int[] a = new int[100];

// number of elements in array
private int x;

// Bubble Sort Algorithm
public void sortArray()
{
int i;
int j;
int temp;

for( i = (x - 1); i >= 0; i-- )
{
for( j = 1; j <= i; j++ ) { if( a[j-1] > a[j] )
{
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
}

Selection Sort Algorithm

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations.
he algorithm works as follows:

  • Find the minimum value in the list
  • Swap it with the value in the first position
  • Repeat the steps above for the remainder of the list (starting at the second position and advancing each time)

Effectively, we divide the list into two parts: the sublist of items already sorted, which we build up from left to right and is found at the beginning, and the sublist of items remaining to be sorted, occupying the remainder of the array.

Here is an example of this sort algorithm sorting five elements:

64 25 12 22 11

11 25 12 22 64

11 12 25 22 64

11 12 22 25 64

11 12 22 25 64
(nothing appears changed on this last line because the last)

Selection sort can also be used on list structures that make add and remove efficient, such as a Linked list In this case it's more common to remove the minimum element from the remainder of the list, and then insert it at the end of the values sorted so far. For example:

64 25 12 22 11

11 64 25 12 22

11 12 64 25 22

11 12 22 64 25

11 12 22 25 64
Source code
using System;
class selectionSort
{
public static void Main()
{
int[] a= new int[100];
int min,pass,i;
Console.WriteLine("Number of elements in the array ?");
string s=Console.ReadLine();
int x=Int32.Parse(s);
Console.WriteLine("-----------------------");
Console.WriteLine(" array elements ");
Console.WriteLine("-----------------------");
for(int j=0;j<x;j++)
{
string s1=Console.ReadLine();
a[j]=Int32.Parse(s1);
}
for(pass=0;pass<x-1;pass++)
{
min=pass;
for(i=pass+1;i<x;i++)
{
if(a[min]>a[i])
min=i;
}
if( min!=pass)
{
int k=a[pass];
a[pass]=a[min];
a[min]=k;
}
}
Console.WriteLine("--------------------------------------------");
Console.WriteLine("Sorted elements of an array are(selection sort)");
for (int j=0;j<x;j++)
Console.WriteLine(a[j]);
}
}

Binary Search Algorithm

binary search algorithm (or binary chop) is a technique for locating a particular value in a sorted list. The method makes progressively better guesses, and closes in on the location of the sought value by selecting the middle element in the span (which, because the list is in sorted order, is the median value), comparing its value to the target value, and determining if it is greater than, less than, or equal to the target value. A guessed index whose value turns out to be too high becomes the new upper bound of the span, and if its value is too low that index becomes the new lower bound. Only the sign of the difference is inspected: there is no attempt at an interpolation search based on the size of the difference.Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.First, the search item is compared with the middle element of the list. If the search item is less than the middle item of the list, we restrict the search to the upper half of the list; otherwise, we search the lower half of the list.Algorithm.First, the middle element of the sequence is compared to the value we are searching for. If this element matches the value we are searching for, we are done. If, however, the middle element is ``less than'' the value we are chosen for (as specified by the relation used to specify a total order over the set of elements), then we know that, if the value exists in the sequence, it must exist somewhere after the middle element. Therefore we can eliminate the first half of the sequence from our search and simply repeat the search in the exact same manner on the remaining half of the sequence. If, however, the value we are searching for comes before the middle element, then we repeat the search on the first half of the sequence.

Loop for Binary Search

#include 

int binarySearch(int sortedArray[], int first, int last, int key) {
// function:
// Searches sortedArray[first]..sortedArray[last] for key.
// returns: index of the matching element if it finds key,
// otherwise -(index where it could be inserted)-1.
// parameters:
// sortedArray in array of sorted (ascending) values.
// first, last in lower and upper subscript bounds
// key in value to search for.
// returns:
// index of key, or -insertion_position -1 if key is not
// in the array. This value can easily be
// transformed into the position to insert it.

while (first <= last)
{
int mid = (first + last) / 2; // compute mid point.
if (key > sortedArray[mid])
first = mid + 1; // repeat search in top half.
else if (key < sortedArray[mid])
last = mid - 1; // repeat search in bottom half.
else
return mid; // found it. return position /////
}
return -(first + 1); // failed to find key
}

Source code
using System;
class binSearch
{
public static void Main()
{
int[] a= new int[100];
Console.WriteLine("Number of elements in the array ?");
string s=Console.ReadLine();
int x=Int32.Parse(s);
Console.WriteLine("-----------------------");
Console.WriteLine(" Enter array elements ");
Console.WriteLine("-----------------------");
for(int i=0;i<x;i++)
{
string s1=Console.ReadLine();
a[i]=Int32.Parse(s1);
}
Console.WriteLine("--------------------");
Console.WriteLine("Enter Search element");
Console.WriteLine("--------------------");
string s3=Console.ReadLine();
int x2=Int32.Parse(s3);
int low=0;
int high=x-1;
while(low<=high)
{
int mid=(low+high)/2;
if(x2<a[mid])
high=mid-1;
else if(x2>a[mid])
low=mid+1;
else if(x2==a[mid])
{
Console.WriteLine("-----------------");
Console.WriteLine("Search successful");
Console.WriteLine("-----------------");
Console.WriteLine("Element {0} found at location {1}\n",x2,mid+1);
return;
}
}
Console.WriteLine("Search unsuccessful");
}
}

Linear Search Algorithm

linear search is a search algorithm, also known as sequential search,that is suitable for searching a list of data for a particular value.It operates by checking every element of a list one at a time in sequence until a match is found.The Linear Search, or sequential search, is simply examining each element in a list one by one until the desired element is found. The Linear Search is not very efficient. If the item of data to be found is at the end of the list, then all previous items mustbe read and checked before the item that matches the search criteria is found.This is a very straightforward loop comparing every element in the array with the key. As soon as an equal value is found, it returns. If theloop finishes without finding a match, the search failed and -1 is returned.For small arrays, linear search is a good solution because it's so straightforward. In an array of a million elements linear search on average willtake500,000 comparisons to find the key. For a much faster search, take a look at binary search.

loop for linear search

int linearSearch(int a[], int first, int last, int key) {
// function:
// Searches a[first]..a[last] for key.
// returns: index of the matching element if it finds key,
// otherwise -1.
// parameters:
// a in array of (possibly unsorted) values.
// first, last in lower and upper subscript bounds
// key in value to search for.
// returns:
// index of key, or -1 if key is not in the array.

for (int i=first; i<=last; i++) {
if (key == a[i]) {
return i;
}
}
return -1; // failed to find key
}
Algorithm

For each item in the database if the item matches the wanted info exit with this item.Continue loop wanted item is not in database

Source code
using System;
class linSearch
{
public static void Main()
{
int[] a= new int[100];
Console.WriteLine("Enter number of elements you want to hold in the array ?");
string s=Console.ReadLine();
int x=Int32.Parse(s);
Console.WriteLine("-------------------------");
Console.WriteLine("\n Enter array elements \n");
for(int i=0;i<x;i++)
{
string s1=Console.ReadLine();
a[i]=Int32.Parse(s1);
}
Console.WriteLine("-------------------------");
Console.WriteLine("Enter Search element\n");
string s3=Console.ReadLine();
int x2=Int32.Parse(s3);
for(int i=0;i<x;i++)
{
if(a[i]==x2)
{
Console.WriteLine("-------------------------");
Console.WriteLine("Search successful");
Console.WriteLine("Element {0} found at location {1}\n",x2,i+1);
return;
}
}
Console.WriteLine("Search unsuccessful");
}
}

Template by - Mathew | Mux99