If you have just started learning to program in C# or you are a beginner student who is willing to learn C#, here are a few basic C# sample programs with output and explanation which will help beginners and students to learn C# more easily.

  1. Hello World program in C#
  2. Check if the number is prime in C#
  3. Check if string is palindrome in C#
  4. Check if int is palindrome or not in C#
  5. Printing right angle triangle pattern using * in C#
  6. Swap two number using third variables
  7. Printing Fibonacci series in C#
  8. C# program to search an element in an array
  9. Get Character to ASCII Value

Hello world program in c#

Let's start with the basic C# program which is printing "hello world" in console application in C#. You can consider working on Visual Studio IDE, but i will be using online IDE (dotnetfiddle), so you can play with the code, if needed.

In Visual Studio, if you have downloaded Visual Studio Community version, you can open "File"-> "New"-> "Project", then Select "Console Application" ( Search "Console" in top-right, if you cannot find it), name it "Hello World" and click "OK"

Here is the simple C# code to print Hello World

using System;
					
public class Program
{
	public static void Main()
	{
		Console.WriteLine("Hello World");
	}
}

Output:

Hello World

https://dotnetfiddle.net/syjUYa

Explanation:

In the above code, we have imported a namespace "System", using is a keyword, highlighted with blue by the editor, by 'using' keyword, we import Class or namespace.

If you have created program in Visual Studio you will see one extra line "namespace ConsoleApp1", basically this is the namespace of this Class "Program"

Now, next line of code is "public class program", as C# is an Object Oriented language, every line of code that actually does something, is wrapped inside a class. In this case, the class is simply called Program.

public = access modifier in C#, means this class can be accessed publicly from anywhere in the application.

class = keyword

program = name of the console application, which can be anything.

Now, let's understand next line of code "public static void Main(string[] args)", i will explain keywords and it's meaning one by one.

public = again, access modifier of C#, public means it is can be accessed publicly from anywhere in the application.

static = this is another keyword in C#, here static defines that this class method, can be called without needing of the object ( you will learn more about Class/Object in Here ), basically we create objects of class and then call methods inside the class using those objects created by us, but as this method is defined as "static", it doesn't need to called using Class Object.

void = return type of method, means this method will return anything, some methods can return data-type like int, string etc., but as this method returns nothing so "void" is used.

Main = method name,this method is the entry-point of our application, that is, the first piece of code to be executed, and in our example, the only method to be executed.

string[] args= argument passed to method, which is string array, which is used to store the command line arguments. Writing this is optional.

Now, the last line of code "Console.WriteLine("Hello World");", this line basically, prints 'hello world' on the console, Console.WriteLine is method in "System" namespace which is used here and "Hello World" is passed as a string argument inside this method.

Check if a number is prime in C#

Prime number is a number which is divisible by itself or 1, so we will apply logic to get number by user.

We will divide it by 2, get remainder value and loop it using for loop until we reach the remainder value, deivide each number modulu 2, each value from 2 to remainder value, if number remainder is 0 then it is not prime and set flag =1, else flag =0 and number is prime.

using System;
					
public class Program
{
	public static void Main()
	{
		  int n, i, m=0, flag=0;  
          Console.Write("Enter the Number to check Prime: ");
		  //read number
          n = int.Parse(Console.ReadLine());  
		  //divide it by 2 and get remainder
          m=n/2;    
		  //loop until the remainder is reach, check if it is divisble
          for(i = 2; i <= m; i++)    
          {    
			  // if divisible by any number from 2 to m, then it is not prime
             if(n % i == 0)    
             {    
               Console.WriteLine("Number is not Prime.");    
               flag=1;    
               break;    
             }    
          }    
		  // if flag =0, means,above code when flag =1 is assigned is not executed and hence it is prime number
          if (flag==0){
			   Console.WriteLine("Number is Prime.");
		  }
	}
}

I have explained code line by line using comments, please do read them to understand it easily.

Output:

Enter the Number to check Prime: 37
Number is Prime.

https://dotnetfiddle.net/SJDQ2v

prime-number-program-in-c-sharp-min.png

C# Program to check if given number is odd or even

In this program, we will ask user a number and then we will check if user inputed number is even or odd

using System;
					
public class EvenOddProgram
{
	public static void Main()
	{
		    int num;
            Console.Write("Enter a Number : ");
            num = int.Parse(Console.ReadLine());
		
		    //divide it by 2, if remainder is 0 then it is even number
            if (num % 2 == 0)
            {
                Console.WriteLine(num+" is an Even Number");               
            }
            else
            {
                Console.WriteLine(num+ " is an Odd Number");               
            }
	}
}

Output:

Enter a Number : 5
5 is an Odd Number

In the above code, we are asking user to Enter a number, then we are reading it using Console.Readline, once we have the number we try to get modulus ( % ) or remainder of that number if it is 0, then it is Even else odd number.

https://dotnetfiddle.net/SZIHvF

Check if string is palindrome in C#

Palindrome string is a string, in which if we reverse the string and it still remains same, then it is a palindrome string.

using System;
					
public class Program
{
	public static void Main()
	{
		    string initial = "";
		    
		    Console.WriteLine("Enter a String to check for Palindrome");
 
            string input = Console.ReadLine();
 
            int iLength = input.Length;
 
		    //check if string length is not 0, basically if it is not empty
            if (iLength == 0)
            {
                Console.WriteLine("You did not enter the string");
 
            }
            else
            { 
                for (int j = iLength - 1; j >= 0; j--)
                {
                    initial = initial + input[j];
                }				
 				//if initial string is same as input
                if (initial == input)
                {
                    Console.WriteLine(input + " is palindrome");
                }
                else
                {
                    Console.WriteLine(input + " is not a palindrome");
                }
             
            }
	}
}

Output:

Enter a String to check for Palindrome
mom
mom is palindrome

In the above code, we are asking user to enter the string to check if it is palindrome, then we are checking if it is empty string or not using .Length() method, if it is not empty, we will loop it using for loop.

While looping, we start from last character of string and then append it with second last character and so on, until string is empty.

Once we are done, we match it with intial string, if both are same, then string is palindrome.

https://dotnetfiddle.net/NZkMzh

Check if int is palindrome or not in C#

Checking if int is palindrome or not, is much easier than checking string, here is the code for it.

using System;
					
public class Program
{
	public static void Main()
	{
		    int num = 0, reverseNumber=0, temp, rem;
		
            Console.Write("Enter a Number : ");
		    //read number and parse it for int
            num = int.Parse(Console.ReadLine());
		
            temp = num;
		    //loop through number
            while (temp != 0)
            {
                rem = temp % 10; //get remainder, means last digit of number
                temp = temp / 10; // get remaining value
                reverseNumber = reverseNumber * 10 + rem;   //save it is new number       
            }
            //if number = reverse number
            if(num==reverseNumber)
            {
                Console.WriteLine(num +" is a palindrome number");
            }
            else
            {
                Console.WriteLine(num +" is not a palindrome number");
            }
	}
}

Output:

Enter a Number : 121
121 is a palindrome number

https://dotnetfiddle.net/ALGot9

I have explained code using comments.

Printing right angle triangle pattern using * in C#

using System;
					
public class RightAngleTrianglePatternProgram
{
	public static void Main()
	{
	   for (int i = 1; i <= 6; i++)
           {
             for (int j = 1; j <= i; j++)
             {
                Console.Write("*");
             }
            Console.WriteLine();
           }       
	}
}

Output:

*
**
***
****
*****
******

https://dotnetfiddle.net/NrOInw

In the above code, we are using two for loops.

Loop 1 runs until the value of i is less than or equal to 6, means we will be creating 6 rows to print star.

Loop 2 prints star's, whenever this loop is executed, it will print 1 column for 1st row, as value of i =1, and j =1, when value of i=2, it will print 2 times, as loop can run twice and so on.

You may like to read: Various Star pattern program in C#

Swap two numbers using third variable in C#

using System;
					
public class Program
{
	public static void Main()
	{
		    //declare two numbers and temp variable
		    int num1, num2, temp;
		    //ask for numbers
            Console.WriteLine("\nEnter the First Number : ");
            num1 = int.Parse(Console.ReadLine());
            Console.WriteLine("\nEnter the Second Number : ");
            num2 = int.Parse(Console.ReadLine());
		   //swap them using third variable
            temp = num1;
            num1 = num2;
            num2 = temp;
		    //print numbers
            Console.WriteLine("After Swapping : ");
            Console.WriteLine("First Number : "+num1);
            Console.WriteLine("Second Number : "+num2);
           
	}
}

Output:

Enter the First Number : 
10

Enter the Second Number : 
20
After Swapping : 
First Number : 20
Second Number : 10

In the above code, we are swapping number using third temporary variable.

Printing fibonacci series in C#

Fibonacci series

using System;
					
public class Program
{
	public static void Main()
	{
		int number, next=1, previous=-1;
		Console.WriteLine("Enter a maximum number for the Fibonacci sequence: ");
		number= int.Parse(Console.ReadLine());
		
		for (int i = 0; i < number; i++)
		{
		  int iSum = next + previous; 
		  previous = next;
		  next = iSum;
		  Console.WriteLine(next);
		}
		
	}
}

Output:

Enter a maximum number for the Fibonacci sequence: 
10
0
1
1
2
3
5
8
13
21
34

In the above code, we are initializing three variable, one for asking user maximum number for fibonacci series, second is for saving previous number from current number and third variable to save next number.

Once, we have the number, we loop until the max. number using for loop and print the sum of next and previous value.

C# program to search an element in an array

In this program, we will be using a basic C# linear search, to search an element in an array.

using System;
					
public class Program
{
	public static void Main()
	{
		string[] array1 = { "cat", "dogs", "donkey", "camel" };
		string ItemToSearch="dogs";
		bool ItemFound=false;
		
		for(int i=0;i<array1.Length;i++)
		{
			if(array1[i]==ItemToSearch)
			{
				ItemFound=true;		
			}
		}
		
		if(ItemFound)
		{
			Console.WriteLine(ItemToSearch+ " found");
		}
		else
		{
			Console.WriteLine(ItemToSearch+ " is not found");
		}
	}
}

Output:

dogs found

In the above code, we have created a string array and then using for loop we are looping each element of an array to check if it is our required item or not.

If an item is found, we are setting the flag "ItemFound" to true.

Get Character to ASCII Value

In this example, we will use typecasting to get character to ASCII value in C#.

using System;

namespace CharToAscii
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string str = "HELLO WORLD";
            foreach (char c in str)
            {
                Console.WriteLine((int)c);
            }
        }
    }
}

Output:

72
69
76
76
79
32
87
79
82
76
68

You may also like to read:

Remove Duplicates from Array in C#

How to add a item or multiple items in C# List

Get Character to ASCII value in C#