C#

C# Basic Examples

Programmingempire

In this post on C# Basic Examples, you will learn some of the simple code examples that you must know to start learning the C# language. In fact, these are the basic examples that we do to learn any new programming language. As the C# is an object-oriented language, so we can only write code inside a class.

For the purpose of our example, we will create a class that we name BasicOperations. Another key point is that we will define the static functions since these methods don’t necessarily represent the behavior of the objects of this class. In fact, we will not create an object of this class in this example to call a method. Let us look at the functions defined below one-by-one. The complete code with the Main() method is provided at the end.

Write a Program to Determine Whether a Number is Prime or Not.

The following function determines whether the given number is prime or not and returns a boolean value indicating true or false. The for loop in the function will execute from 2 to half of that number and divides the number with each value. If the remainder is non-zero for all values from 2 to half of that number, then the number is prime and the true value is returned. Otherwise, a false value is returned.

 public static bool FindPrime(int p)
 {
            for(int i=2;i<p/2;i++)
            {
                if (p % i == 0)
                    return false;
            }
            return true;
 }       

Show Prime Numbers in upto a maximum Value

The following function displays all prime numbers starting from 2 and up to a maximum value which we provide as a parameter. In similar way, as we did in previous example, we will find where a number in the given range is prime or not. If it is prime, the number is displayed.

public static void PrimeInRange(int n)
{
    bool prime=true;
    for(int i=2;i<=n;i++)
    {
       prime = true;
       for(int j=2;j<=i/2;j++)
       {
            if(i%j==0)
            {
                 prime = false;
                 break;
             }
        }
        if (prime)
             Console.Write(i + " ");
     }
            Console.WriteLine();
  }

Swap Two Numbers

The following function swaps the two numbers passed as parameters and displays both original and swapped values.

        public static void SwapWithThirdNumber(int a, int b)
        {
            int c;
            Console.WriteLine("Numbers before swapping: ");
            Console.WriteLine("a = " + a + " b = " + b);
            c = a;
            a = b;
            b = c;
            Console.WriteLine("Numbers after swapping: ");
            Console.WriteLine("a = " + a + " b = " + b);
        }

Write a program to Swap Two Numbers without using a Third Variable

The following function also swaps two numbers. However, here we don’t use any third variable. The swapping is done using simple computations which are illustrated in comments.

        public static void SwapWithoutThirdVariable(int a, int b)
        {
            Console.WriteLine("Numbers before swapping: ");
            Console.WriteLine("a = " + a + " b = " + b);
            a = a + b;//a=3, b=4, a=7
            b = a - b; //b=3
            a = a - b; //a = 4
            Console.WriteLine("Numbers after swapping: ");
            Console.WriteLine("a = " + a + " b = " + b);

        }

Find Factorial of a Number

In the function given below, we compute the factorial of a number which is passed as a parameter. The function returns the value of factorial.

 public static int Factorial(int v)
        {
            int fact = 1;
            if (v == 0) return 1;
            for(int i=1;i<=v;i++)
            {
                fact = fact * i;
            }
            return fact;
        }

Write a program to find Factorial of Number Using a Recursive Function

The function given below is a recursive version of the previous function. Here, we return a value of 1 when the parameter becomes 0. Otherwise, the function is called recursively with the parameter value decremented by 1 and multiplying this new function call with the current value of the parameter.

public static int RecursiveFactorial(int v)
        {
            if (v == 0)
                return 1;
            else
                return v * RecursiveFactorial(v - 1);
        }

Show the Terms of a Fibonacci series up to a given Maximum Value

The following function shows the Fibonacci number from the starting term 0 up to a maximum term specified as a parameter. When the next term exceeds the given maximum value, the break; statement in the while loop executes and terminates the loop.

 public static void Fibonacci(int m)
        {
            int a, b, c;
            a = -1; b = 1;
            Console.WriteLine("Fibonacci Numbers upto the number: " + m);
            while(true)
            {
                c = a + b;
                if (c > m) break;
                Console.Write(c + " ");
                a = b;
                b = c;
            }
            Console.WriteLine();
        }

Find the Sum of Digits of a Number

The following function finds the sum of digits of a number and returns it. In the while loop, in each iteration, the remainder on dividing the number by 10 is computed and then the number is divided by zero. The remainder represents each digit of the number. The while loop terminates when the number vanishes. All the values of the remainder are added in the loop to compute the sum.

 public static int SumOfDigits(int n)
        {
            int sum = 0;
            int remainder;
            while(n != 0)
            {
                remainder = n % 10;
                sum += remainder;
                n = n / 10;
            }
            return sum;
        }

Reverse a Number

The following function computes the reverse of a number by following the logic in the previous example. However, each previously extracted digit is multiplied by 10 before adding it to the current remainder and thereby computing the reverse.

 public static int ReverseNumber(int n)
        {
            int sum = 0;
            int n1 = n;
            int remainder;
            int reverse = 0;
            while (n != 0)
            {
                remainder = n % 10;
                reverse = reverse * 10+remainder;

                sum += remainder;
                n = n / 10;
            }
            return reverse;
        }

Find Whether a Number is a Palindrome or Not

We determine thwhether a number is palindrome or not by comparing the number with its reverse. If both are equal, then it is a palindrome number, otherwise not.

 public static bool PelindromeNumber(int n)
        {
            int reverse = ReverseNumber(n);
            if (n == reverse)
                return true;
            else
                return false;
        }

Find Whether the Given Number is an Armstrong Number or Not

An Armstrong Number is that number which is equal to a number computed by adding the cube of each digit of the given number. In the following function, we compute the sum of the cube of each digit of the number passed as a parameter. If both are equal, then it is an Armstrong Number.

        public static bool FindArmstrong(int n)
        {
            int sum = 0;
            int n1 = n;
            int remainder;
            int result = 0;
            while (n != 0)
            {
                remainder = n % 10;
                result += remainder * remainder * remainder;

                sum += remainder;
                n = n / 10;
            }
            if (n1 == result)
                return true;
            else
                return false;
        }

Now, as all functions are explained, let us use them by calling in the main method. Further, as the functions are declared as static, there is no need of creating an object and we can call these function by simply using the class name and dot operator. The Complete Code is Given Below.

using System;
namespace BasicExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            int num;
            Console.WriteLine("Enter a Numner: ");
            num = Int32.Parse(Console.ReadLine());
            if (BasicOperations.FindPrime(num))
                Console.WriteLine(num + " is prime");
            else
                Console.WriteLine(num + " is not prime");
            Console.WriteLine("Enter a Number: ");
            num = Int32.Parse(Console.ReadLine());
            Console.WriteLine("All Prime Numbers fro 2 to " + num);
            BasicOperations.PrimeInRange(num);


            int a, b;
            Console.WriteLine("Enter two numbers for swapping: ");
            a = Int32.Parse(Console.ReadLine());
            b = Int32.Parse(Console.ReadLine());

            BasicOperations.SwapWithThirdNumber(a, b);
            BasicOperations.SwapWithoutThirdVariable(a, b);

            int n;
            Console.WriteLine("Enter a number to find its factorial: ");
            n = Int32.Parse(Console.ReadLine());
            int fact = BasicOperations.Factorial(n);
            Console.WriteLine("Factorial of " + n+" = " + fact);
            fact = BasicOperations.RecursiveFactorial(n);
            Console.WriteLine("Factorial of " + n + " = " + fact);

            int m;
            Console.WriteLine("Enter the limit of fibonacci Series: ");
            m = Int32.Parse(Console.ReadLine());
            BasicOperations.Fibonacci(m);

            int sum;
            Console.WriteLine("Enter a Number: ");
            n = Int32.Parse(Console.ReadLine());
            sum = BasicOperations.SumOfDigits(n);
            Console.WriteLine("Sum of Digits of Number " + n + " =" + sum);

            int reverse;
            reverse = BasicOperations.ReverseNumber(n);
            Console.WriteLine("Reverse of Number " + n + " =" + reverse);

            Console.WriteLine("Enter a Number: ");
            n = Int32.Parse(Console.ReadLine());
            bool b1 = BasicOperations.PelindromeNumber(n);
            if (b1)
                Console.WriteLine(n + " is pelindrome.");
            else
                Console.WriteLine(n + " is not pelindrome.");

            Console.WriteLine("Enter a Number: ");
            n = Int32.Parse(Console.ReadLine());
            bool b2;
            b2 = BasicOperations.FindArmstrong(n);
            if (b1)
                Console.WriteLine(n + " is an Armstrong Number.");
            else
                Console.WriteLine(n + " is not an Armstrong Number.");
        }
    }
    class BasicOperations
    {
        public static bool FindPrime(int p)
        {
            for(int i=2;i<p/2;i++)
            {
                if (p % i == 0)
                    return false;
            }
            return true;
        }

        public static void PrimeInRange(int n)
        {
            bool prime=true;
                              
            for(int i=2;i<=n;i++)
            {
                prime = true;
                for(int j=2;j<=i/2;j++)
                {
                    if(i%j==0)
                    {
                        prime = false;
                        break;
                    }
                    
                }
                if (prime)
                    Console.Write(i + " ");
               
            }
            Console.WriteLine();
        }
        public static void SwapWithThirdNumber(int a, int b)
        {
            int c;
            Console.WriteLine("Numbers before swapping: ");
            Console.WriteLine("a = " + a + " b = " + b);
            c = a;
            a = b;
            b = c;
            Console.WriteLine("Numbers after swapping: ");
            Console.WriteLine("a = " + a + " b = " + b);
        }

        public static void SwapWithoutThirdVariable(int a, int b)
        {
            Console.WriteLine("Numbers before swapping: ");
            Console.WriteLine("a = " + a + " b = " + b);
            a = a + b;//a=3, b=4, a=7
            b = a - b; //b=3
            a = a - b; //a = 4
            Console.WriteLine("Numbers after swapping: ");
            Console.WriteLine("a = " + a + " b = " + b);

        }

        public static bool FindArmstrong(int n)
        {
            int sum = 0;
            int n1 = n;
            int remainder;
            int result = 0;
            while (n != 0)
            {
                remainder = n % 10;
                result += remainder * remainder * remainder;

                sum += remainder;
                n = n / 10;
            }
            if (n1 == result)
                return true;
            else
                return false;
        }

        public static int Factorial(int v)
        {
            int fact = 1;
            if (v == 0) return 1;
            for(int i=1;i<=v;i++)
            {
                fact = fact * i;
            }
            return fact;
        }

        public static int RecursiveFactorial(int v)
        {
            if (v == 0)
                return 1;
            else
                return v * RecursiveFactorial(v - 1);
        }
        public static void Fibonacci(int m)
        {
            int a, b, c;
            a = -1; b = 1;
            Console.WriteLine("Fibonacci Numbers upto the number: " + m);
            while(true)
            {
                c = a + b;
                if (c > m) break;
                Console.Write(c + " ");
                a = b;
                b = c;
            }
            Console.WriteLine();
        }

        public static bool PelindromeNumber(int n)
        {
            int reverse = ReverseNumber(n);
            if (n == reverse)
                return true;
            else
                return false;
        }

        public static int SumOfDigits(int n)
        {
            int sum = 0;
            int remainder;
            while(n != 0)
            {
                remainder = n % 10;
                sum += remainder;
                n = n / 10;
            }
            return sum;
        }

        public static int ReverseNumber(int n)
        {
            int sum = 0;
            int n1 = n;
            int remainder;
            int reverse = 0;
            while (n != 0)
            {
                remainder = n % 10;
                reverse = reverse * 10+remainder;

                sum += remainder;
                n = n / 10;
            }
            return reverse;
        }
    }
}

Output:

programmingempire

You may also like...