Thursday, October 27, 2011

C# Sample Programs


Linear Search Program

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");
}
}

Binary Search Program

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");
}
}

Selection Sort Program

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]);
}
}

Bubble Sort Program

using System;
class bubbleSort
{
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(" array elements ");
Console.WriteLine("-----------------------");
for(int j=0;j<x;j++)
{
string s1=Console.ReadLine();
a[j]=Int32.Parse(s1);
}
int limit= x-1;
for(int pass=0;pass<x-1;pass++)
{
for(int j=0;j<limit-pass;j++)
{
if(a[j]>a[j+1])
{
int k=a[j];
a[j]=a[j+1];
a[j+1]=k;
}
Console.WriteLine("------------------------------------------------");
Console.WriteLine("Sorted elements of an array are(buble sort)");
for (int j=0;j<x;j++)
Console.WriteLine(a[j]);
}
}

Finding Largest and Smallest Number

using System;
class Test
{
public static void Main()
{
int n;
float large,small;
int[] a = new int[50];
Console.WriteLine("Enter the size of Array");
string s= Console.ReadLine();
n=Int32.Parse(s);
Console.WriteLine("Enter the array elements");
for(int i=0;i<n;i++)
{
string s1=Console.ReadLine();
a[i]=Int32.Parse(s1);
}
Console.Write("");
large =a[0];
small= a[0];
for(int i=1;i<n;i++)
{
if(a[i]>large)
large=a[i];
else if(a[i]<small)
small=a[i];
}
Console.WriteLine("Largest element in the array is {0}",large);
Console.WriteLine("Smallest element in the array is {0}",small);
}
}

Fibonacci Series

using System;
class FS
{
public static void Main()
{
int n;
Console.WriteLine("Number of terms to be generated ?");
string s=Console.ReadLine();
n=Int32.Parse(s);
Console.WriteLine("*******************************");
Console.WriteLine("Fibonacci seqence upto {0}",n);
Console.WriteLine("*******************************");
test1.generateFib(n);
}
}
class generateFib
{
static int f1=0;
static int f2=1;
public static void fib(int n)
{
int temp;
if(n<2)
{
f1=0;
f2=1;
}
else
{
fib(n-1);
temp=f2;
f2=f1+f2;
f1=temp;
}
Console.WriteLine(f1);
}
}

Palindrome Program

using System;
class palindrome
{
public static void Main()
{
int n,num,digit,sum=0,rev=0;
string s;
Console.WriteLine("*******************");
Console.WriteLine("Please enter a number");
Console.WriteLine("*******************");
s=Console.ReadLine();
num=Int32.Parse(s);
n=num;
do
{
digit=num%10;
sum+=digit;
rev=rev*10+digit;
num/=10;
}while(num!=0);
Console.WriteLine("*******************************");
Console.WriteLine("Sum of the digit of the number = {0}",sum);
Console.WriteLine("************************");
Console.WriteLine("Reverse of the number = {0}",rev);
Console.WriteLine("************************");
if(n==rev)
Console.WriteLine("The number is a palindrome");
else
Console.WriteLine("The number is not a palindrome");
}
}

Generating Pascal Triangle

using System;
class pascalTriangle
{
public static void Main()
{
int binom=1,q=0,r,x;
Console.WriteLine("Enter the number of rows");
string s=Console.ReadLine();
int p =Int32.Parse(s);
Console.WriteLine(p);
Console.WriteLine("The Pascal Triangle");
while(q<p)
{
for(r=40-(3*q);r>0;--r)
Console.Write(" ");
for(x=0;x<=q;++x)
{
if((x==0)||(q==0))
binom=1;
else
binom=(binom*(q-x+1))/x;
Console.Write(binom);
}
Console.Write("\n ");
++q;
}
}
}

The following two source code listings showhow to write a crude but effective console mode application forconverting a number, either from binary to decimal, or from decimal tobinary. Note: you pass in the decimal number or the binary string as aparameter when typing the program's name at a command prompt.

From Decimal to Binary…

using System;

class Program{

static void Main(string[] args){

try{

int i = (int)Convert.ToInt64(args[0]);
Console.WriteLine("\n{0} converted to Binary is {1}\n",i,ToBinary(i));

}catch(Exception e){

Console.WriteLine("\n{0}\n",e.Message);

}

}//end Main

public static string ToBinary(Int64 Decimal)
{
// Declare a few variables we're going to need
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";

while (Decimal > 0)
{
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}

// The algoritm gives us the binary number in reverse order (mirrored)
// We store it in an array so that we can reverse it back to normal
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);

return BinaryResult;
}

}//end class Program

——————————————————————————–

From Binary to Decimal…

using System;

class Program{

static void Main(string[] args){

try{

int i = ToDecimal(args[0]);
Console.WriteLine("\n{0} converted to Decimal is {1}",args[0],i);

}catch(Exception e){

Console.WriteLine("\n{0}\n",e.Message);

}

}//end Main

public static int ToDecimal(string bin)
{
long l = Convert.ToInt64(bin,2);
int i = (int)l;
return i;
}

}//end class Program



//Binary equivalent of a binary number
#include<stdio.h>
#include<conio.h>
int binary (int);
void main()
{
int num;
clrscr();
printf("\nEnter The Number: ");
scanf("%d",&num);
binary(num);
printf("\n\n\n\n\nPress any key to exit.....");
getch();
}
//function to convert deciaml to binary
int binary (int n)
{
int r;
r=n%2;
n=n/2;
if (n==0)
{
printf("\nThe binary equivalent is %d",r);
return(r);
}
else
binary(n);
printf("%d",r);
}


We can achieve the string reversal in a easy way.

Let us Consider a one dimensional character array, input string and an output string variable.

Char[] arrStr;

string strInput = "Naveen";

string strOutput= string.Empty;


Am passing the string "Naveen" to the array in the following manner.

arrStr = strInput.ToCharArray();


then we have to put a reverse for loop like below

for(int idx=arrStr.Length-1;idx>=0; idx--)

{

   strOutput  += arrStr.Getvalue(idx);

}



The output will be "neevaN"


Reversing strings
First, there are many solutions, but this one can be done with three lines of code. The method shown in this article is based on the author's work with ToCharArray, and the method is static because it does not need to save state. This article is based on .NET 3.5 SP1.

=== Example program that reverses strings (C#) ===

using System;

static class StringHelper
{
    /// <summary>
    /// Receives string and returns the string with its letters reversed.
    /// </summary>
    public static string ReverseString(string s)
    {
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);
        return new string(arr);
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(StringHelper.ReverseString("framework"));
        Console.WriteLine(StringHelper.ReverseString("samuel"));
        Console.WriteLine(StringHelper.ReverseString("example string"));
    }
}

=== Output of the program ===

krowemarf
leumas
gnirts elpmaxe

0 comments:

Post a Comment

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Best Wallpapers collections