Wednesday 18 July 2012

SAMPLE PROGRAMS IN C#


1.Hello World -- Your First Program
To create and run a console application

·       Start Visual Studio.
·       On the File menu, point to New, and then click Project.
·       In the Templates Categories pane, expand Visual C#, and then click Windows.
·       In the Templates pane, click Console Application.
·       Type a name for your project in the Name field.
·       Click OK.
·       The new project appears in Solution Explorer.
·       If Program.cs is not open in the Code Editor, right-click Program.cs in Solution Explorer and then click View Code.
·       Replace the contents of Program.cs with the following code.

// A Hello World! program in C#.

using System;
namespace HelloWorld
{
class Hello
{
static void Main()
{
Console.WriteLine("Hello World!");

// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}

·       Press F5 to run the project. A Command Prompt window appears that contains the line Hello World!


2. Fibonacci series – A sample program in C#
Sample Code:
using System;
using System.Collections.Generic;
using System.Text;
namespace codeforfibonacciseries
{
    class Program
  {
      static void Main(string[] args)
        {
            int i = 0;
            int j = 1;
            int k = 1;
            int n = 0;
            int m = 0;
            m = Console.Read();
            m++;
            Console.WriteLine("The Fibonacci series values are:");
            Console.Write(" {0}, {1}", i,j);
            for (n = 0; n <= m; n++)
            {
                k = i +j;
                i = j;
                j = k;
                Console.Write (" {0} ", k);
        }
}
}
3. Even or odd – A sample program in C#
Sample Code:
using System;
using System.Collections.Generic;
using System.Text;
namespace codeforevenorodd
{
 class Program
{
 static void Main(string[] args)
 { string g;
 int j = 0;
 int i;
Console.WriteLine(" Enter the value: ");
g = Console.ReadLine();
i = Convert.ToInt32(g);
j = (i % 2);
if(j == 0)
{
Console.WriteLine("The given value is even ");
}
else
{
Console.WriteLine("The given value is odd  ");
}
}
}
}

4. Palindrome – A sample program in C#
Sample Code:
using System;
using System.Collections.Generic;
using System.Text;
namespace codeforpalindrome
{
class Program
{
static void Main(string[] args)
{string s1;
int j = 0;
int i = 0;
Console.WriteLine(" Enter the value ");
s1 = Console.ReadLine();
j = s1.Length;
while (i != (j - 1)){
if (s1[i] == s1[j - 1])
{
i++;
j = j - 1;
}
else
{
Console.WriteLine(" The given value is not a palindrome");
break;
}
}
if (i == (j-1))
{
Console.WriteLine("The given value is a plaindrome")
}
}
}

No comments:

Post a Comment