Saturday, September 4, 2010

Sample C# programs

1. A C# program implementing insertion sort.

using System;
class Insert
{
public static void Main()
{
int j,k,i,v;
Console.WriteLine("enter the no. of numbers to be sorted:");
int n=Int32.Parse(Console.ReadLine());
int []num=new int [n];
Console.WriteLine("enter the numbers one after another:");
for(i=0;i<n;i++)
{
num[i]=Int32.Parse(Console.ReadLine()); .
}

for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(num[j]<num[i])
{

v=num[j];

for(k=j-1;k>=i;k--)
{
num[k+1]=num[k];
}
num[i]=v;
}
}
}
Console.WriteLine("the sorted numbers are:");
for(i=0;i<n;i++)
{
Console.WriteLine(num[i]);
}
}
}

2. To sort Strings.

using System;
class StringSrt
{
public static void Main(String []args)// take the input of no of strings to be sorted from command prompt
{
int i,n,c,j;String b;
Console.WriteLine("enter the type of sorting to be done:1.Based on Alphabet, 2.Based on Length;");
c=Int32.Parse(Console.ReadLine());

Console.WriteLine("Enter the no. of Strings to be sorted:");
n=Int32.Parse(Console.ReadLine());

String []S1=new String[n];

Console.WriteLine("Enter the Strings one after the other: ");
for ( i=0 ; i<n ; i++ )
{b = Console.ReadLine();
S1[i] = b;}

Console.WriteLine("After Sorting the Strings on the basis of ");
if(c==1||c==2)
{
for(i=0;i<n;i++)
for(j=i;j<n;j++)
{
int wor=0;
do
{
if(String.Compare(S1[i],S1[j],true)>0)
{
b=S1[i];
S1[i]=S1[j];
S1[j]=b;wor=-1;
}
}while(wor!=-1);
}
if(c==2)
{Console.Write("LENGTH ");
for(i=0;i<n;i++)
for(j=i;j<n;j++)
{
if(S1[i].Length>S1[j].Length)
{
b=S1[i];
S1[i]=S1[j];
S1[j]=b;
}
}
}
else
Console.Write("ALPHABETS ");
}
Console.Write("are :");
for(j=0;j<n;j++)
Console.WriteLine(S1[j]);
}
}

3. To setup a student information system using Structures.


using System;
namespace StudentsInfo
{
    struct A
    {
        public string name;
        public int roll;
        public float marks;
        public A(int rol, string nam, float mak)
        {
            this.name = nam;
            this.roll = rol;
            this.marks = mak;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            int t,c=0,i,j;
            String s;
            A []aa = new A[100];
            do{
                Console.WriteLine("Enter the Operations to be performed:");
                Console.WriteLine("1.Add Info. 2.Display Info. 3.Delete Info.");
                t=Int32.Parse(Console.ReadLine());
                switch (t)
                {
                    case 1:
                        Console.WriteLine("Enter the Student: Name, Roll No., Marks");
                        string name=Console.ReadLine();
                        int roll=Int32.Parse(Console.ReadLine());
                        float marks=(float)Double.Parse(Console.ReadLine());
                        A a=new A(roll,name,marks);
                        aa[c]=a;
                        c++;
                        break;
                    case 2:
                        if (c == 0)
                        {
                            Console.WriteLine("The DB has no elements to be displayed.");
                        }
                        else
                        {
                            Console.WriteLine("Name of the Student\tRoll No.\tMarks");
                            for (i = 0; i < c; i++)
                            {
                                Console.WriteLine(aa[i].name + "   " + aa[i].roll + "   " + aa[i].marks);
                            }
                        }
                        break;
                    case 3:
                        if (c == 0)
                        {
                            Console.WriteLine("The DB has no elements to be deleted.");
                        }
                        else
                        {
                            Console.WriteLine("Enter the roll no. of the student, whose info. has to be deleted:");
                            int r = Int32.Parse(Console.ReadLine());
                            j = -1;
                            for (i = 0; i < c; i++)
                            {
                                if (aa[i].roll == r)
                                {
                                    j = i; break;
                                }
                            }
                            if (j == -1)
                            {
                                Console.WriteLine("Given roll no. is not present in the DB:");
                            }
                            else
                            {
                                while (i != c)
                                {
                                    aa[i] = aa[i + 1];
                                    i++;
                                }
                                c--;
                                Console.WriteLine("One record got deleted");
                            }
                        }
                        break;
                    default:
                        Console.WriteLine("Entered choice is wrong...");
                        break;
                }
                Console.WriteLine("Enter '0' to continue and '1' to terminate...");
                s=Console.ReadLine();
            }while(s!="1");
        }
    }
}


4. To Implement External Delegate Features to find Fibonacci series and Factorial of a number.


using System;
namespace Delegates
{
    public delegate void Bonacci();
    class A
    {
        public int x,y;
        public A()
        {
            x = 0;
            y = 1;
            Console.WriteLine(x);
        }
        public void fibo()
        {
            int z;
            z=x;
            x = y;
            y = z + y;
            Console.WriteLine(x);
        }
    }
    public delegate void factor();
    class B
    {
        int x,z;
        public int y;
        public B(int a)
        {
            x = a;
            z = a;
            y = 1;
        }
        public void fac()
        {
            y = y * x;
            x--;
        }
        public void disp()
        {
            Console.WriteLine("The factorial of " + z + " is " + y);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the choice:");
            Console.WriteLine("1. To get the fibonacci series.");
            Console.WriteLine("2. To find the factorial of any number.");
            int i = Int32.Parse(Console.ReadLine());
            switch (i)
            {
                case 1:
                    Console.WriteLine("Enter the no. of elements required in the series:");
                    int r = Int32.Parse(Console.ReadLine());
                    Console.WriteLine("The series goes as follows:");
                    A a = new A();
                    Bonacci b = new Bonacci(a.fibo);
                    for (i = 0; i < r - 2; i++)
                    {
                        b += a.fibo;
                    }
                    b();
                        break;
                case 2:
                        Console.WriteLine("Enter the number whose factorial is to be found:");
                        int f = Int32.Parse(Console.ReadLine());
                        B bb = new B(f);
                        factor fc=new factor(bb.fac);
                        for (i = 0; i < f-1; i++)
                            fc += bb.fac;
                        fc += bb.disp;
                        fc();
                            break;
                default:
                    break;
            }
        }
    }
}

5. To implement Custom Namespaces in a program.

Step 1: Save the following program as FakeProgram.cs


using FakeSystem;
using SystemFake;
class FakeProgram
{
public static void Main()
{
FakeConsole.FakeWriteLine("This is a Fake C# Program: ");
FakeConsole.FakeWriteLine(" ");
FakeConsole.FakeWriteLine("Enter any String : ");
FakeString s=new FakeString(FakeConsole.FakeReadLine());
FakeConsole.FakeWriteLine(" ");
FakeConsole.FakeWriteLine("1. The Upper case form of the Input String :");
FakeConsole.FakeWriteLine(s.FakeToUpper());
FakeConsole.FakeWriteLine("");
FakeConsole.FakeWriteLine("2. The Lower Case form of the Input String :");
FakeConsole.FakeWriteLine(s.FakeToLower());
FakeConsole.FakeWriteLine("");
FakeConsole.FakeWriteLine("3. The Length of the String");
FakeConsole.FakeWriteLine(s.FakeLength());
}
}


Step2: Save the following program as SystemFake.cs

using System;
namespace SystemFake
{
public class FakeString
{
public string s;
public int i;
public FakeString(string r)
{
s=r;i=10;
}
public string FakeToUpper()
{
string s1=s.ToUpper();
return s1;
}
public string FakeToLower()
{
string s2=s.ToLower();
return s2;
}
public int FakeLength()
{
int n=s.Length;
return n;
}
}
}


Step 3: Save the following program as FakeSystem.cs

using System;
namespace FakeSystem
{
public class FakeConsole
{
public static void FakeWriteLine(String s)
{
Console.WriteLine(s);
}
public static void FakeWriteLine(int s)
{
Console.WriteLine(s);
}
public static void FakeWriteLine(float s)
{
Console.WriteLine(s);
}
public static string FakeReadLine()
{
string s=Console.ReadLine();
return s;
}

}
}

Step 4: In the command prompt type the following command to create .dll files of the aboves codes:

csc /t:library FakeSystem.cs
csc /t:library SystemFake.cs

Step 5: In Following step you will combine the two .dll files into one file:

csc /t:library /out:combine.dll FakeSystem.dll SystemFake.dll

Step 6: To compile the main program FakeProgram.cs by linking with combine.dll

csc /r:combine.dll FakeProgram.cs

Step 7: Run the file FakeProgram.cs and get the result.

6. Custom Exception Handling.

using System;
namespace CustomExceptionHandling
{
    class UnknowInput:Exception
    {
        string strg;
        public UnknowInput(string msg):base(msg)
        {
            strg = msg;
        }
    }
    class Testthis
    {
        Testthis()
        {
        }
        private static char symbol='@';
        public static void TestEnteredMail(string messageinput)
        {
            if(messageinput.IndexOf(symbol)==-1)
            {
                    Console.WriteLine("The string entered is not a valid email address string");
                    throw(new UnknowInput(messageinput));
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter any email Id to check whether it is valid or not.");
            try
            {
                Testthis.TestEnteredMail(Console.ReadLine());
                Console.WriteLine("The given email id is valid");
            }
            catch (UnknowInput)
            {
                Console.WriteLine("The email id is not valid.");
            }
            finally
            {
                Console.WriteLine("Exception is Handled Successfully");
            }
        }
    }
}

7. To perform Matrix Manipulation using switch-case.

using System;
class Matrix
{
public static void Main()
{
int inst;
do{
int i,j,k,l,sum;
Console.WriteLine("Enter the dimension of the two matrix");
Console.WriteLine("M1xN1:");
int m1=Int32.Parse(Console.ReadLine());
int n1=Int32.Parse(Console.ReadLine());
int [,]a1=new int[m1,n1];
for(i=0;i<m1;i++)
for(j=0;j<n1;j++)
a1[i,j]=Int32.Parse(Console.ReadLine());
Console.WriteLine("M2xN2:");
int m2=Int32.Parse(Console.ReadLine());
int n2=Int32.Parse(Console.ReadLine());
int [,]a2=new int[m2,n2];
for(i=0;i<m2;i++)
for(j=0;j<n2;j++)
a2[i,j]=Int32.Parse(Console.ReadLine());
Console.WriteLine("Enter the operation that you want to perform over the assigned matrix");
Console.WriteLine("1. Addition.");
Console.WriteLine("2. Multiplication.");
int n=Int32.Parse(Console.ReadLine());
switch(n){
case 1:
if(m1==m2 && n1==n2)
{
Console.WriteLine("The matrix Addition of (M1xN)1+ (M2+N2) are:");
for(i=0;i<m2;i++){
for(j=0;j<n2;j++)
{
Console.Write((a1[i,j]+a2[i,j])+" ");
}Console.WriteLine("");}
}else
{Console.WriteLine("Error in the  Matrix dimensions to perform addtion. Check the Dimension are same.");
}
break;
case 2:
if(n1==m2)
{ 
Console.WriteLine("The matrix Multiplication of (M1xN)1+ (M2+N2) are:");
for(i=0;i<m1;i++){ 
for(j=0;j<n2;j++)
{l=0;sum=0;
for(k=0;k<n1;k++)
{
sum=sum+(a1[i,k]*a2[l,j]);l++;if(l==n1)break;
}Console.Write(sum+" ");
}Console.WriteLine("");}
}
else Console.WriteLine("Error in the Matrix dimensions to perform Multiplication. Check the Dimension are same.");
break;
default:
Console.WriteLine("You  entered a wrong choice...{:-(");
break;
}
Console.WriteLine( "Enter '0' to try again or press '1' to terminate the process.");
inst=Int32.Parse(Console.ReadLine());
}while(inst==0);
}
}











No comments:

Post a Comment