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

  1. Hello World program in C#
  2. Check if number is prime in C#
  3. Check if string is palindrame 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#

Hello world program in c#

Let's start with 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

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 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.

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.

Check if string is palindrame in C#

Palindrome string is a string, in which if we reverse the string and it still remains same, then it is 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.

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

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:

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

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.

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.