• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Monday, August 10, 2020

Armstrong Number Program in C# with Examples

 Admin     August 10, 2020     C#, Interview Question, Programming, Programs     No comments   

In this article, I am going to discuss the Armstrong Number Program in C# with some examples. Please read our previous article before proceeding to this article where we discussed the How to Reverse a Number and a String Program in C# with some examples. As part of this article, we are going to discuss the following pointers.
  1. What is an Armstrong Number?
  2. How to check if a given number is Armstrong or not?
  3. Program to find Armstrong number between a range of numbers.
What is an Armstrong Number?
An Armstrong Number is a number that is equal to the sum of, power of each digit by the total number of digits. For example, the numbers such as 0, 1, 153, 370, 371, and 407, 1634, 8208, 9474 are Armstrong numbers. Let us have a look at the following diagram which shows how the Armstrong number is calculated.
Armstrong Number Program in C# with Examples

Let us understand this with an example:
In the following program, first, we are finding the total number of digits in a given number, and storing each digit into an array. And then by using the power method of Math class, we are finding the power of each digit and then calculate the sum of each result. Finally, we are comparing the sum and the input number. If both are equal then it is an Armstrong number else it is not an Armstrong number.
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            int digitCount = 0;
            int[] digitArray = new int[10];
            double sum = 0;
            //Step1: Take the input
            Console.Write("Enter the Number : ");
            int number = int.Parse(Console.ReadLine());
            //Step3: Store the number in a temporary variable
            int temporaryNumber = number;
            //Step3: Find the total number of digits in number as well as
            //Store each each digit in the digit array
            while (number > 0)
            {
                digitArray[i++] = number % 10;
                number = number / 10;
                digitCount++;
            }
            //Step4: Calculate the result
            for (i = 0; i < digitCount; i++)
            {
                sum += Math.Pow(digitArray[i], digitCount);
            }
            //Step5: Check whether it is prime number or not
            if (sum == temporaryNumber)
            {
                Console.WriteLine($"The Number {temporaryNumber} is armstrong");
            }
            else
            {
                Console.WriteLine($"The Number {temporaryNumber} is not armstrong");
            }
            Console.ReadLine();
        }
    }
}
Output:
Armstrong Number in C#

Finding Armstrong number between ranges of numbers in C#:
In the following program, we are taking two input i.e. start and end numbers from the console and then finding the Armstrong numbers between these two numbers.
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the Start Number : ");
            int StartNumber = int.Parse(Console.ReadLine());
            Console.Write("Enter the End Number : ");
            int EndNumber = int.Parse(Console.ReadLine());
            Console.WriteLine($"The Armstrong Numbers between {StartNumber} and {EndNumber} are : ");
            for (int i = StartNumber; i <= EndNumber; i++)
            {
                if (IsArmstrongNumber(i))
                    Console.WriteLine(i);
            }
            
            Console.ReadLine();
        }
        static bool IsArmstrongNumber(int number)
        {
            int sum = 0;
            int temporaryNumber = number;
            int temp = 0;
            int length = number.ToString().Length;
            while (number != 0)
            {
                temp = number % 10;
                number = number / 10;
                sum += (int)Math.Pow(temp, length);
            }
            
            if (sum == temporaryNumber)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
Output:
Finding Armstrong number between ranges of numbers in C#

In the next article, I am going to discuss the Factorial Number Program in C# with some examples. Here, in this article, I try to explain how to check whether a given number is Armstrong or not in C# with some examples.

Summary:
I hope this post will be helpful to write a Armstrong Number Program in C#
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Reverse Number Program in C# with Examples

 Admin     August 10, 2020     C#, Interview Question, Programming, Programs     No comments   

In this article, I am going to discuss the Reverse Number Program in C# with some examples. Please read our previous article where we discussed the Palindrome Program in C# with some examples. This is one of the most frequently asked interview questions in C#. As part of this article, we are going to discuss the following pointers.
  1. How to reverse a given number in C#?
  2. How to reverse a string in C#?
How to reverse a given number in C#?
In the following program, we take the input number from the console and then reverse that number.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a Number : ");
            int number = int.Parse(Console.ReadLine());
            int reminder, reverse = 0;
            while (number > 0)
            {
                //Get the remainder by dividing the number with 10  
                reminder = number % 10;
                //multiply the sum with 10 and then add the reminder
                reverse = (reverse * 10) + reminder;
                //Get the quotient by dividing the number with 10 
                number = number / 10;
            }
            Console.WriteLine($"The Reverse order is : {reverse}");
            Console.ReadKey();
        }
    }
}
Output:
How to reverse a given number in C#?

How to reverse a string in C#?
In the following program, we take the string as an input from the console. Then we reverse the string using for loop.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string name = Console.ReadLine();
            string reverse = string.Empty;
            for (int i = name.Length - 1; i >= 0; i--)
            {
                reverse += name[i];
            }
            Console.WriteLine($"The Reverse string is : {reverse}");
            Console.ReadKey();
        }
    }
}
Output:
How to reverse a string in C#?

Reverse a string Using Foreach loop in C#:
Let us see how to reverse a string using for each loop in C#.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string name = Console.ReadLine();
            string reverse = string.Empty;
            foreach (char c in name)
            {
                reverse = c + reverse;
            }
            
            Console.WriteLine($"The Reverse string is : {reverse}");
            Console.ReadKey();
        }
    }
}
Output:
Reverse a string Using Foreach loop in C#:

Reverse a string using Array.Reverse Method in C#:
In the following example, we take a string as an input from the console and then convert that string to a character array. Then we use the Array class Reverse method to reverse the elements of the character array. Once we reverse the elements of the character array, then we create a string from that character array.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string name = Console.ReadLine();
            char[] nameArray = name.ToCharArray();
            Array.Reverse(nameArray);
            string reverse = new string(nameArray);
            
            Console.WriteLine($"The Reverse string is : {reverse}");
            Console.ReadKey();
        }
    }
}
Output:
Reverse a string using Array.Reverse Method in C#

In the next article, I am going to discuss the Armstrong Number Program in C# with some examples. Here, in this article, I try to explain the different ways to reverse a number and a string using C# with some examples. I hope you understand the Reverse Number Program in C# with examples.

Summary:
I hope this post will be helpful to write a Reverse Number Program in C# with Examples
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Palindrome Program in C# with Examples

 Admin     August 10, 2020     C#, Interview Question, Programming, Programs     No comments   

In this article, I am going to discuss the Palindrome Program in C# with some examples. Please read our previous article where we discussed the Prime Number Program with some examples. This is one of the interview questions asked in the interview to write the logic to check whether a number or string is a palindrome or not. As part of this article, we are going to discuss the following pointers.
  1. What is Palindrome?
  2. How to check if a given number is Palindrome or not?
  3. How to check if a given string is Palindrome or not?
Palindrome Number:
A Palindrome number is a number that is going to be the same after reversing the digits of that number. For example, the numbers such as 121, 232, 12344321, 34543, 98789, etc. are the palindrome numbers.

How to check if a given number is Palindrome or not?
Algorithm to check Palindrome Number in C#:
  1. First, get the number from the user which you check
  2. Hold that number in a temporary variable
  3. Reverse that number
  4. Compare the temporary number with the reversed number
  5. If both numbers are same, then print it is palindrome number else print it is not a palindrome number
Let us implement the above algorithm with a program in C# to check whether a number is a Palindrome or not.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a Number To Check Palindrome : ");
            int number = int.Parse(Console.ReadLine());
            int remineder, sum = 0;
            int temp = number;
            while (number > 0)
            {
                //Get the remainder by dividing the number with 10  
                remineder = number % 10;
                //multiply the sum with 10 and then add the remainder
                sum = (sum * 10) + remineder;
                //Get the quotient by dividing the number with 10 
                number = number / 10; 
            }
            if (temp == sum)
            {
                Console.WriteLine($"Number {temp} is Palindrome.");
            }
            else
            {
                Console.WriteLine($"Number {temp} is not Palindrome");
            }
            Console.ReadKey();
        }
    }
}
Output:
How to check if a given number is Palindrome or not?

How to check if a given string is Palindrome or not in C#?
In the following program, we take the string as an input from the console. Then we reverse the string using for loop and storing the reverse string value in the reverse variable. Finally, we check whether the original and reverse values are the same or not. If both are same then the string is Palindrome else it is not Palindrome.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a string to Check Palindrome : ");
            string name = Console.ReadLine();
            string reverse = string.Empty;
            
            for (int i = name.Length - 1; i >= 0; i--)
            {
                reverse += name[i];
            }
            
            if (name == reverse)
            {
                Console.WriteLine($"{name} is Palindrome.");
            }
            else
            {
                Console.WriteLine($"{name} is not Palindrome");
            }
            Console.ReadKey();
        }
    }
}
Output:
How to check if a given string is Palindrome or not in C#

Using the for-each loop:
Let us see how to do the previous program using a for each loop.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main()
        {
            Console.Write("Enter a string to Check Palindrome : ");
            string name = Console.ReadLine();
            string reverse = string.Empty;
            foreach (char c in name)
            {
                reverse = c + reverse;
            }
            if (name.Equals(reverse, StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine($"{name} is Palindrome");
            }
            else
            {
                Console.WriteLine($"{name} is not Palindrome");
            }
            Console.ReadKey();
        }
    }
}
Output:
How to check if a given string is Palindrome or not using Foreach Loop

Another Approach:
In the following example, first, we convert the string to a character array. Then using the Array class Reverse method we are reversing the elements of the character array. Once we reverse the elements of the character array, then we create a string from this array. Finally, we are comparing this newly created string with the original string and printing it is Palindrome if both the strings are the same else we are just printing it is not Palindrome.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main()
        {
            Console.Write("Enter a string to Check Palindrome : ");
            string name = Console.ReadLine();
            char[] nameArray = name.ToCharArray();
            Array.Reverse(nameArray);
            string reverse = new string(nameArray);
            
            if (name.Equals(reverse, StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine($"{name} is Palindrome");
            }
            else
            {
                Console.WriteLine($"{name} is not Palindrome");
            }
            Console.ReadKey();
        }
    }
}
Output:
Palindrome Program in C# with Examples

That’s it for today. Here, in this article, I try to explain the different ways to check whether a number or a string is Palindrome or not using C#. In the next article, I am going to discuss how to reverse a number and a string in C# with some examples.

Summary:
I hope this post will be helpful to write a Palindrome Program in C# with Examples
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Prime Numbers in C# with Examples

 Admin     August 10, 2020     C#, Interview Question, Programming, Programs     No comments   

In this article, I am going to discuss the Prime Numbers in C# with some examples. Please read our previous article where we discussed the Fibonacci Series Program with some examples. C# prime number example program is one of the most frequently asked written exam interview questions in C# Interview. As part of this article, we are going to discuss the following pointers.
  1. What is a Prime Number?
  2. How to check if a given number is prime or not in C#?
  3. How to Print the Prime Numbers between a range of numbers in C#?
What is a Prime Number?
A Prime Number is a number which should be greater than 1 and it only is divided by 1 and itself. In other words, we can say that the prime numbers can’t be divided by other numbers than itself and 1. For example, 2, 3, 5, 7, 11, 13, 17, 19, 23…., are the prime numbers.

How to check if a given number is prime or not in C#?
The following example takes one input from the console and then checks whether that number is a prime number or not.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a Number : ");
            int number = int.Parse(Console.ReadLine());
            bool IsPrime = true;
            for (int i = 2; i < number/2; i++)
            {
                if (number % i == 0)
                {
                    IsPrime = false;
                    break;
                }
            }
            if (IsPrime)
            {
                Console.Write("Number is Prime.");
            }
            else
            {
                Console.Write("Number is not Prime.");
            }
            Console.ReadKey();
        }
    }
}
Output:
Prime Numbers in C#

How to display Prints the Prime Numbers between a range of numbers in C#? In the following example, we will take two numbers from the console and then print the prime numbers present between those two numbers.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter The Start Number: ");
            int startNumber = int.Parse(Console.ReadLine());
            Console.Write("Enter the End Number : ");
            int endNumber = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine($"The Prime Numbers between {startNumber} and {endNumber} are : ");
            for (int i = startNumber; i <= endNumber; i++)
            {
                int counter = 0;
                for (int j = 2; j <= i / 2; j++)
                {
                    if (i % j == 0)
                    {
                        counter++;
                        break;
                    }
                }
                
                if (counter == 0 && i != 1)
                {
                    Console.Write("{0} ", i);
                }    
            }
            Console.ReadKey();
        }
    }
}
Output:
How to display Prints the Prime Numbers between a range of numbers in C#?

That’s it for today. Here, in this article, I try to explain what is a prime number and how to check whether a number is prime or not using a console application. In the end, we also discussed how to print the prime numbers between a range. In the next article, I am going to discuss how to check whether a number or string is Palindrome or not in C#.

Summary:
I hope this post will be helpful to write Prime Numbers in C# with Examples
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Fibonacci Series Program in C# with Examples

 Admin     August 10, 2020     C#, Interview Question, Programming, Programs     No comments   

In this article, I am going to discuss the Fibonacci Series Program in C# with some examples. This is one of the most frequently asked C# written interview questions. Please read our previous article where we discussed the Swapping Program with and without using the third variable in C#. As part of this article, we are going to discuss the following pointers.
  1. What is the Fibonacci Series?
  2. What are the different ways to implement the Fibonacci in C#?
  3. How to find the nth Fibonacci number in C#?
  4. How to Print the Fibonacci Series up to a given number in C#?
What is the Fibonacci Series?
The Fibonacci series is nothing but a sequence of numbers in the following order:
Fibonacci Series Program in C# with Examples

The numbers in this series are going to starts with 0 and 1. The next number is the sum of the previous two numbers. The formula for calculating the Fibonacci Series is as follows:

F(n) = F(n-1) + F(n-2) where:
      F(n) is the term number.
      F(n-1) is the previous term (n-1).
      F(n-2) is the term before that (n-2).
What are the different ways to implement the Fibonacci in C#?
In C#, we can print the Fibonacci Series in two ways. They are as follows:
  1. Iterative Approach
  2. Recursion Approach
Iterative Approach to Print Fibonacci Series in C#:
This is the simplest approach and it will print the Fibonacci series by using the length. The following program shows how to use the iterative approach to print the Fibonacci Series in C#.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        public static void Main()
        {
            int firstNumber = 0, SecondNumber = 1, nextNumber, numberOfElements;
            Console.Write("Enter the number of elements to Print : ");
            numberOfElements = int.Parse(Console.ReadLine());
            if(numberOfElements < 2)
            {
                Console.Write("Please Enter a number greater than two");
            }
            else
            {
                //First print first and the second number
                Console.Write(firstNumber + " " + SecondNumber + " ");
                //Starts the loop from 2 because 0 and 1 are already printed
                for(int i = 2; i < numberOfElements; i++)
                {
                    nextNumber = firstNumber + SecondNumber;
                    Console.Write(nextNumber + " ");
                    firstNumber = SecondNumber;
                    SecondNumber = nextNumber;
                }
            }
            
            Console.ReadKey();
        }
    }
}
Output:
Iterative Approach to Print Fibonacci Series in C#

Recursive Approach to Print Fibonacci Series in C#:
In the Recursive Approach, we need to pass the length of the Fibonacci Series to the recursive method and then it will iterate continuously until it reaches the goal. Let us understand this with an example.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please enter the Length of the Fibonacci Series : ");
            int number = int.Parse(Console.ReadLine());
            FibonacciSeries(0, 1, 1, number);
            Console.ReadKey();
        }
        public static void FibonacciSeries(int firstNumber, int secondNumber, int counter, int number)
        {
            Console.Write(firstNumber + " ");
            if (counter < number)
            {
                FibonacciSeries(secondNumber, firstNumber + secondNumber, counter + 1, number);
            }
        }
    }
}
Output:
Recursive Approach to Print Fibonacci Series in C#

How to find the nth Fibonacci number in the Fibonacci Series in C#?
It is also possible to print the nth Fibonacci number from the Fibonacci series in C#. The following example prints the nth number from the Fibonacci series.

Using Recursion:
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please enter the Nth number of the Fibonacci Series : ");
            int NthNumber = int.Parse(Console.ReadLine());
            //Decrement the Nth Number by 1. This is because the series starts with 0
            NthNumber = NthNumber - 1;
            Console.Write(NthFibonacciNumber(NthNumber));
            Console.ReadKey();
        }
        private static int NthFibonacciNumber(int number)
        {
            if ((number == 0) || (number == 1))
            {
                return number;
            }
            else
            {
                return (NthFibonacciNumber(number - 1) + NthFibonacciNumber(number - 2));
            }
        }
    }
}
Output:
How to find the nth Fibonacci number in the Fibonacci Series using Recursive Function?

You can observe that, in the above implementation, it does a lot of repeated work. So this is a bad implementation to find the nth Fibonacci number in the Fibonacci series. We can avoid this using the iterative approach.

Without Using Recursive Function:

Let us understand how to implement this with an example. Here we are not going to use the Recursive function.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please enter the Nth number of the Fibonacci Series : ");
            int NthNumber = int.Parse(Console.ReadLine());
            //Decrement the Nth Number by 1. This is because the series starts with 0
            NthNumber = NthNumber - 1;
            Console.Write(NthFibonacciNumber(NthNumber));
            Console.ReadKey();
        }
        private static int NthFibonacciNumber(int number)
        {
            int firstNumber = 0, secondNumber = 1, nextNumber = 0;
            // To return the first Fibonacci number  
            if (number == 0)
                return firstNumber;
            for (int i = 2; i <= number; i++)
            {
                nextNumber = firstNumber + secondNumber;
                firstNumber = secondNumber;
                secondNumber = nextNumber;
            }
            return secondNumber;
        }
    }
}
Output:
How to find the nth Fibonacci number in the Fibonacci Series without using Recursive Function?

How to Print the Fibonacci Series up to a given number in C#?
Now we will see how to print the Fibonacci up to a given number in C#. Please have a look at the following program.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            int firstNumber = 0, SecondNumber = 1, nextNumber, number;
            Console.Write("Enter the number upto which print the Fibonacci series : ");
            number = int.Parse(Console.ReadLine());
            //First print first and second number
            Console.Write(firstNumber + " " + SecondNumber + " ");
            nextNumber = firstNumber + SecondNumber;
            //Starts the loop from 2 because 0 and 1 are already printed
            for (int i = 2; nextNumber < number; i++)
            {
                Console.Write(nextNumber + " ");
                firstNumber = SecondNumber;
                SecondNumber = nextNumber;
                nextNumber = firstNumber + SecondNumber;
            }
            
            Console.ReadKey();
        }
    }
}
Output:
How to Print the Fibonacci Series up to a given number in C#?

That’s it for today. Here, in this article, I try to explain the Fibonacci Program in C# in different ways. I hope you enjoy this article. In the next article, I am going to discuss the Prime Number Program in C# with some examples.

Summary:
I hope this post will be helpful to write a Fibonacci Series Program in C# with Examples
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Swapping Program in C# with Examples

 Admin     August 10, 2020     C#, Interview Question, Programming, Programs     No comments   

In this article, I am going to discuss the Swapping Program in C# with and without using third variables. In many C#.NET interviews, the interviewers asked this question to write the logic to swap two numbers. As part of this article, we are going to discuss the following pointers.
  1. How to swap two numbers using a third variable in C#?
  2. How to swap two numbers without using third variable in C#?
  3. Examples using both numbers and strings.
First, we will discuss how to swap two numbers using the third variable. Then we will discuss how to swap two integers and two strings without using the third variable in C#.

Swapping two numbers using a third variable in C#:
In the following program, in order to swap two numbers, we use a third variable, firstly we assign the first variable to the temporary variable then assign the second variable to the first variable and finally assigns the value which is in the third variable (which holds the first number) to the second variable.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        public static void Main()
        {
            int number1 = 10, number2 = 20, temp = 0;
            Console.WriteLine($"Before SWapping number1= {number1}, number2 = {number2}");
            temp = number1; //temp=10
            number1 = number2; //number1=20      
            number2 = temp; //number2=10    
            Console.WriteLine($"After swapping number1= {number1}, number2 = {number2}");
            Console.ReadKey();
        }
    }
}
Output:
Swapping two numbers using a third variable in C#

Swap two integers without using the third variable in C#
There are two ways you can use to swap two numbers without using the third variable:
  1. By using * and /
  2. By using + and –
Program using * and /
Swap two integers without using the third variable in C#

The following program uses * and / to swaps two integer numbers without using the third variable in C#.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        public static void Main()
        {
            int number1 = 10, number2 = 20;
            Console.WriteLine($"Before SWapping number1= {number1}, number2 = {number2}");
            number1 = number1 * number2; //number1=200 (10*20)      
            number2 = number1 / number2; //number2=10 (200/20)      
            number1 = number1 / number2; //number1=20 (200/10)    
            Console.WriteLine($"After swapping number1= {number1}, number2 = {number2}");
            Console.ReadKey();
        }
    }
}
Output:
Swapping Program in C# with Examples

Program using + and –
The following program uses + and – operator to swaps two integer values without using the third variable in C#.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        public static void Main()
        {
            int number1 = 10, number2 = 20;
            Console.WriteLine($"Before SWapping number1= {number1}, number2 = {number2}");
            number1 = number1 + number2; //number1=30 (10+20)      
            number2 = number1 - number2; //number2=10 (30-20)      
            number1 = number1 - number2; //number1=20 (30-10)    
            Console.WriteLine($"After swapping number1= {number1}, number2 = {number2}");
            Console.ReadKey();
        }
    }
}
It will give you the same output as the previous program.

Swap two strings without using the third variable in C#.
Algorithm: To swap two strings in C#
Step1: First Append the second string with the first string and store in the first string:

String1 = String1 + String2

Step2: In step2, call the Substring Method (int startIndex, int length) bypassing the start index as 0 and length as String1.Length – String2.Length:

String2 = Substring(0, String1.Length – String2.Length);

Step3: In step3, Call the Substring Method (int startIndex) bypassing the start index as String2.Length.

String1 = Substring(String2.Length);

The following program swaps two strings without using the third variable in C#.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        public static void Main()
        {
            string name1 = "Dotnet", name2 = "Tutorials";
            Console.WriteLine($"Before SWapping name1= {name1}, name2 = {name2}");
            // Step1: append 2nd string with the 1st string 
            name1 = name1 + name2;
            //Step2: store intial string name1 in string name2 
            name2 = name1.Substring(0, name1.Length - name2.Length);
            //Step3:  store initial string name2 in string name1 
            name1 = name1.Substring(name2.Length);
   
            Console.WriteLine($"After swapping name1= {name1}, name2 = {name2}");
            Console.ReadKey();
        }
    }
}
Output:
Swap two Strings without using a third variable in C#.

As you can see, here we are using the Substring() built-in method. Let us understand this method in detail.

Understanding String.Substring Method in C#:
The Substring() method in C# comes in two forms. They are as follows:

String.Substring Method (startIndex): This Substring() method is used to extract a substring from the current instance of the string. The parameter “startIndex” will specify the starting position of substring and then the substring will continue to the end of the string.

String.Substring Method (int startIndex, int length): This Substring() method is used to retrieve a substring that begins from the specified position described by parameter “startIndex” and has a specified length. If the startIndex is equal to the length of string and parameter length is zero, then it will return nothing as a substring.

I hope you understood how to swap two values with and without using the third variable in C#. In the next article, I am going to discuss the Fibonacci Series program in different ways.

Summary:
I hope this post will be helpful to write a swapping program in C# with examples
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Friday, August 7, 2020

Development Approach with Entity Framework

 Admin     August 07, 2020     .Net, C#, Entity Framework     No comments   

In this article, I will discuss Development Approach with Entity Framework. The entity framework provides three different approaches when working with the database and data access layer in your application as per your project requirement. These are
  1. Database-First
  2. Code-First
  3. Model-First
Database-First Approach:
We can use the Database First approach if the database schema already existing.

In this approach, we generate the context and entities for the existing database using the EDM wizard.

This approach is best suited for applications that use an already existing database.
Development Approach with Entity Framework

Database First approach is useful:
  1. When we are working with a legacy database
  2. If we are working in a scenario where the database design is being done by another team and the application development starts only when the database is ready
  3. When we are working on a data-centric application
Code-First Approach:
You can use the Code First approach when you do not have an existing database for your application. In the code-first approach, you start writing your entities (domain classes) and context class first and then create the database from these classes using migration commands.

This approach is best suited for applications that are highly domain-centric and will have the domain model classes created first. The database here is needed only as a persistence mechanism for these domain models.

That means Developers who follow the Domain-Driven Design (DDD) principles, prefer to begin coding with their domain classes first and then generate the database required to persist their data.
Development Approach with Entity Framework

Code First approach is useful:
  1. If there is no logic is in the database
  2. When full control over the code, that is, there is no auto-generated model and context code
  3. If the database will not be changed manually
Model-First Approach:
This approach is very much similar to the Code First approach, but in this case, we use a visual EDM designer to design our models. So in this approach, we create the entities, relationships, and inheritance hierarchies directly on the visual designer and then generate entities, the context class, and the database script from your visual model.

Note: The visual model will give us the SQL statements needed to create the database, and we can use it to create our database and connect it up with our application.
Development Approach with Entity Framework

The Model First approach is useful:
  1. When we really want to use the Visual Entity Designer
Choosing the Development Approach for Your Application:
The below flowchart explaining which is the right approach to develop your application using Entity Framework?
Development Approach with Entity Framework

As per the above diagram, if you have an existing database, then you can go with Database First approach because you can create an EDM from your existing database.

But if you don’t have an existing database but you have an existing application with domain classes then you can go with code first approach because you can create a database from your existing classes.

But if you don’t have either existing database or domain model classes then you can go with the model first approach.

In the next article, I will discuss the DB First approach of Entity Framework.

In this article, I try to explain the Development Approach with Entity Framework. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Summary:
I hope this post will be helpful to understand the Development Approach with Entity Framework
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • ASP.NET State Management
    State management is a technique or way to maintain / store the state of an Asp.Net controls, web page information, object/data, and user in ...
  • HTTP Client Message Handler in Web API
    In this article, I am going to discuss HTTP Client Message Handler in Web API with real-time examples. As we already discussed in HTTP Mes...
  • ASP.NET Web API Basic Authentication
    In this article, I am going to discuss how to implement the ASP.NET Web API Basic Authentication step by step with an example. Please read...
  • Navigation Menus in ASP.NET Core
    In this article, I am going to discuss how to create Responsive Navigation Menus in ASP.NET Core Application using bootstrap and JQuery. P...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • ViewModel in ASP.NET Core MVC
    In this article, I am going to discuss ViewModel in ASP.NET Core MVC application with an example. Please read our previous article before ...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape