• 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
Showing posts with label Programs. Show all posts
Showing posts with label Programs. Show all posts

Sunday, August 16, 2020

Merge Sort in C#

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

In this article, I am going to discuss the Merge Sort in C# with Example. Please read our previous article before proceeding to this article where we discussed the Bubble Sort Algorithm in C# with example. The Merge Sort Algorithm in C# is a sorting algorithm and used by the many programmers in real-time applications.

The Merge Sort Algorithm:
The Merge Sort Algorithm is a comparison-based sorting algorithm that is based on the divide and conquers approach.

What is the Divide and Conquer Approach?
The divide and conquer approach means it will divide the input the array into sub-arrays and then further it divide the sub-arrays into sub-arrays until each sub-array contains a single element. Then each sub-arrays merge together in such a way that it will form a single sorted array.

How does the Merge Sort Algorithm work?
The Merge Sort Algorithm works as follows:
  1. Divide the unsorted array into n sub-arrays, each array containing a single element.
  2. Repeatedly merge the sub-arrays to produce a new sorted array until there is only 1 array remaining.
Note: The idea behind the merge sort is that it is going to merge two sorted arrays.

Let us understand this with an example. We have an input integer array having the elements as 38, 27, 43, 3, 9, 82, and 10. Let’s have a look at the following diagram which shows how the merge sort is work.
Merge Sort Algorithm in C#

Let us understand the step by step procedure to understand the merge with the example shown in the above image.

Step1: Dividing
In step1, we need to divide the array into two sub-arrays. Here the first sub-array will contain four elements (such as 38, 27, 43, and 3) and the other sub-array will contain 3 elements such as (9, 82, and 10).

The first subarray which contains 38, 27, 43, and 3 is further divided into two subarrays (38, 27) and (43, 3). The subarray which contains (38, 27) is further divided into (28) and (27). Similarly, the subarray which contains (43, 3) will be divided into subarrays (43) and (3). At this point, the division will stop as each sub-array contains a single element.

The second subarray which contains 9, 82, and 10 is further divided into two subarrays. One sub-array with two elements i.e. 9 and 82 and the other sub-array with a single element i.e. 10. Further, the subarray which contains (9, 82) is divided into (9) and (82). At this point as each sub-array contains a single element so the division will stop here.

Step2: Merge
At the end of step1, we have seven subarrays, and each one containing a single element in it. In step2, we need to merge the sub-arrays. The Subarrays (38) and (27) will merge together to form a sorted subarray i.e. (27, 38). Similarly, the other subarrays (43) and (3) will merge together to form sorted subarray (3, 43) and the subarrays (9) and (82) will merge together to form sorted subarray (9, 82). In this step, we will keep 10 as it is.

Now the sub-arrays (27, 38) and (43, 3) will merge together to form a sorted subarray i.e. (3, 27, 38, and 43). Similarly, the other two subarrays (9, 82) and 10 merge together to form a sorted subarray (i.e. 9, 10, and 82).

Now, we have two sub-arrays i.e. (3, 27, 38, and 43), and (9, 10, and 82) will merge together to finally produce the sorted array such as (3, 9, 10, 27, 38, 43, and 82).

Program to Implement Merge Sort in C#:
using System;
namespace LogicalPrograms
{
    class Program
    {
        static public void MergeMethod(int[] numbers, int left, int mid, int right)
        {
            int[] temp = new int[25];
            int i, left_end, num_elements, tmp_pos;
            left_end = (mid - 1);
            tmp_pos = left;
            num_elements = (right - left + 1);
            while ((left <= left_end) && (mid <= right))
            {
                if (numbers[left] <= numbers[mid])
                    temp[tmp_pos++] = numbers[left++];
                else
                    temp[tmp_pos++] = numbers[mid++];
            }
            while (left <= left_end)
                temp[tmp_pos++] = numbers[left++];
            while (mid <= right)
                temp[tmp_pos++] = numbers[mid++];
            for (i = 0; i < num_elements; i++)
            {
                numbers[right] = temp[right];
                right--;
            }
        }
        static public void SortMethod(int[] numbers, int left, int right)
        {
            int mid;
            if (right > left)
            {
                mid = (right + left) / 2;
                SortMethod(numbers, left, mid);
                SortMethod(numbers, (mid + 1), right);
                MergeMethod(numbers, left, (mid + 1), right);
            }
        }
        static void Main(string[] args)
        {
            int[] numbers = { 38, 27, 43, 3, 9, 82, 10 };
            int len = numbers.Length;
            Console.WriteLine("Before Merge Sort:");
            foreach(int item in numbers)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.WriteLine("After Merge Sort");
            SortMethod(numbers, 0, len - 1);
            foreach (int item in numbers)
            {
                Console.Write(item + " ");
            }
            Console.Read();
        }
    }
}
Output:
Merge Sort Program in C#

Time Complexity of Merge Sort in C#:
The Merge Sort Algorithm is a recursive algorithm. The array of size N is divided into the maximum of logN parts, and the merging of all the subarrays into a single array takes O(N) time. Hence in all the three cases (worst, average, best), the time complexity of Merge sort is O(NLogN).

Algorithm for C# Merge Sort:
To sort the array A[1 .. n], make the initial call to the procedure MERGE-SORT (A, 1, n).

MERGE-SORT (A, p, r)
  1. IF p < r // Check for base case
  2. THEN q = FLOOR[(p + r)/2] // Divide step
  3. MERGE (A, p, q) // Conquer step.
  4. MERGE (A, q + 1, r) // Conquer step.
  5. MERGE (A, p, q, r) // Conquer step.
In the next article, I am going to discuss the Quick Sort in C# with examples. Here, in this article, I try to explain the Merge Sort in C# with example. I hope now you understood how Merge Sort Algorithm Works in C# to sort an unsorted array.

Summary:
I hope this post will be helpful to understand the concept of Merge Sort 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

Bubble Sort in C#

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

In this article, I am going to discuss the Bubble Sort in C# with Examples. The Bubble sort is a sorting algorithm and used by the many developers in real-time applications. You can use this algorithm with any type of collection such as an array, string, numbers, or characters.

The Bubble Sort Algorithm:
The Bubble Sort Algorithm works on the concept of iterating through the array from the first index to the last index and comparing it with the adjacent elements and then swapping the elements if they appear in the wrong order i.e. if the next element is smaller than the current element, they are swapped.

Pictorial Representation of Bubble Sort:
In order to sort an array, there will be n-1 passes where n is the number of elements in the array. For better understanding please have a look at the following diagram. Let us take an input array such as 8 5 7 3 1.
Bubble Sort in C#

As you can see in the above image we have an integer array with 5 elements such as 8 5 7 3 1.

Iteration1:
The bubble sort starts with the first two elements i.e. 8 and 5. As 5 is smaller than 8, so swap both of them. Now the list is 5 8 7 3 1. Again 7 is less than 8, so swap them which results as 5 7 8 3 1. Now, 3 is less than 8, so swap them which results in the sequence like 5 7 3 8 1. Finally 1 is less than 8, so swap them which concludes the iteration1 as 5 7 3 1 and 8.

Iteration2:
For iteration2 the sequence is 5 7 3 1 and 8. Here, the first 2 elements are 5 and 7. 7 is greater than 5, so no need to swap them. The 7 is compared with 3 and 3 is less than 7, so swap them which results in the sequences as 5 3 7 1 8. Then 1 is less than 7 so swap them which results in the sequence like 5 3 1 7 8.

Iteration3: For the iteration3, the sequence will be 5 3 1 7 8. Here, the first two elements are 5 and 3. 3 is less than 5, so swap them which results in the sequences as 3 5 1 7 and 8. Again 1 is less than 5, so swap them which concludes the iteration3 with the sequences as 3 1 5 7 and 8.

Iteration4:
This is the last iteration. This iteration starts with the sequence as 3 1 5 7 and 8. Here the first two elements are 3 and 1. 1 is less than 3, so swap them which results in the elements in the sorted order as 1 3 5 7 and 8.

Program to implement bubble sort in C#:
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            int count = 0;
            int[] intArray = new int[5];
            Console.WriteLine("Enter the Array Elements : ");
            for (int i = 0; i < intArray.Length; i++)
            {
                intArray[i] = int.Parse(Console.ReadLine());
            }
            //Sorting the array
            for (int j = 0; j <= intArray.Length - 2; j++)
            {
                //intArray.Length - 2
                for (int i = 0; i <= intArray.Length - 2; i++)
                {
                    count = count + 1;
                    if (intArray[i] > intArray[i + 1])
                    {
                        int temp = intArray[i + 1];
                        intArray[i + 1] = intArray[i];
                        intArray[i] = temp;
                    }
                }
            }
            Console.WriteLine("After Sorting Array :");
            foreach (int item in intArray)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.WriteLine("The Loop iterates :" + count);
            Console.ReadKey();
        }
    }
}
Output:
Bubble Sort in C# with Example

As you can see the number of iterates is 16. You can improve the performance of the bubble sort by using a bool flag.

Performance Improvement in Bubble sort:
In the following example, we are using a flag variable.
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            int count = 0;
            int[] intArray = new int[5];
            Console.WriteLine("Enter the Array Elements : ");
            for (int i = 0; i < intArray.Length; i++)
            {
                intArray[i] = int.Parse(Console.ReadLine());
            }
            bool flag = true;
            for (int i = 1; (i <= (intArray.Length - 1)) && flag; i++)
            {
                flag = false;
                for (int j = 0; j < (intArray.Length - 1); j++)
                {
                    count = count + 1;
                    if (intArray[j + 1] > intArray[j])
                    {
                        int temp = intArray[j];
                        intArray[j] = intArray[j + 1];
                        intArray[j + 1] = temp;
                        flag = true;
                    }
                }
            }
            Console.WriteLine("After Sorting Array :");
            foreach (int item in intArray)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.WriteLine("The Loop iterates :" + count);
            Console.ReadKey();
        }
    }
}
Output:
Performance Improvement in C# Bubble sort

Time Complexity of Bubble Sort:
In bubble sort, as we are iterating through the entire array for each element, the average and the worst-case complexity of bubble sort is O(n²).

Algorithm for Bubble Sort:

Procedure BubbleSort(DATA: list of sortable items)
N= DATA.Length
1. Set Flag: = True
2. Repeat Steps from 3 to 5 for I = 1 to N-1 while Flag == true
3. Set Flag:= False
4. Set J:=0. [Initialize pass pointer J]
5. Repeat while JDATA[J], then:
       Swap DATA[J] and DATA[J+1]
       Set Flag:= True
       [End of If structure]

       (b) Set J:=J+1
       [End of inner loop]
       [End of step 1 outer loop]

6. Exit
In the next article, I am going to discuss the Merge Sort Algorithm In C# with examples. Here, in this article, I try to explain the Bubble Sort in C# with example. I hope now you understood how bubble sort works in C# and I also hope you enjoy this article.

Summary:
I hope this post will be helpful to understand the concept of Bubble Sort 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

How to find the angle between hour and minute hands of a clock at any given time in C#

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

In this article, I am going to discuss how to find the angle between the hour and minute hands of a clock at any given time in C# with an example. Please read our previous article where we discussed How to Perform Right Circular Rotation of an Array in C# with an example.

Program Description:
Here, the user will input the hour and minute. Then we need to calculate the angle between the given hours and minute. For example, if the user input as 9hour 30 minutes, then the angle between the hour hand and minute hand should be 105 degrees. If the input is 13 hour 30 minutes then the output should be 135 degrees

Finding the angle between the hour and minute hands of a clock at any given time:
The logic that we need to implement is to find the difference in the angle of an hour and minute hand from the position of 12 O Clock when the angle between them is zero. Each hour on the clock represents an angle of 30 degrees (360 divided by 12). Similarly, each minute on the clock will represent an angle of 6 degrees (360 divided by 60) and the angle for an hour will increase as the minutes for that hour increases.
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the hours : ");
            int hours = int.Parse(Console.ReadLine());
            Console.Write("Enter the Minutes : ");
            int minutes = int.Parse(Console.ReadLine());
            
            double hourInDegrees = (hours * 30) + (minutes * 30.0 / 60);
            double minuteInDegrees = minutes * 6;
            double diff = Math.Abs(hourInDegrees - minuteInDegrees);
            if (diff > 180)
            {
                diff = 360 - diff;
            }
            Console.WriteLine($"Angle between {hours} hour and {minutes} minute is {diff} degrees");
            Console.ReadKey();
        }
    }
}
Output:
How to find the angle between the hour and minute hands of a clock at any given time in C#

I hope now you understood how to find the angle between the hour and minute hands of a clock at any given time in C#.

Summary:
I hope this post will be helpful to understand How to find the angle between hour and minute hands of a clock at any given time 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

How to Perform Right Circular Rotation of an Array in C#

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

In this article, I am going to discuss How to Perform Right Circular Rotation of an Array in C# with an example. Please read our previous article where we discussed How to Perform Left Circular Rotation of an Array in C# with an example.

Program Description:
Here, the user will input a one-dimensional integer array. Then we need to shift each element of the array to its right by one position in a circular fashion. The logic that we need to implement should iterate the loop from 0 t0 Length – 1 and then swap each element with the first element. Please have a look at the following diagram for a better understanding of our requirements.
How to Perform Right Circular Rotation of an Array in C#

Right Circular Rotation of an Array in C#:
In the following example, first, we take the input integer array from the user. Then we perform right circular rotation using for loop.
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] oneDimensionalArray = new int[6];
            Console.WriteLine("Enter the 1D Array Elements : ");
            for (int i = 0; i< oneDimensionalArray.Length; i++)
            {
                oneDimensionalArray[i] = int.Parse(Console.ReadLine());
            }
            
            int temp;
            for (int j = 0; j < oneDimensionalArray.Length - 1; j++)
            {
                temp = oneDimensionalArray[0];
                oneDimensionalArray[0] = oneDimensionalArray[j + 1];
                oneDimensionalArray[j + 1] = temp;
            }
            Console.WriteLine("Array Elements After Right Circular Rotation: ");
            foreach (int num in oneDimensionalArray)
            {
                Console.Write(num + " ");
            }
            
            Console.ReadKey();
        }
    }
}
Output:
How to Perform Right Circular Rotation of an Array in C#

In the next article, I am going to discuss how to find the angle between the hour and minute hands of a clock at any given time in C# with examples. I hope now you understood How to Perform Right Circular Rotation of an Array in C#.

Summary:
I hope this post will be helpful to understand How to Perform Right Circular Rotation of an Array 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

How to Perform Left Circular Rotation of an Array in C#

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

In this article, I am going to discuss How to Perform Left Circular Rotation of an Array in C# with an example. Please read our previous article where we discussed how to convert a one-dimensional array to a two-dimensional array in C# with an example.

Program Description:
Here, the user will input an integer array. Then we need to shift each element of the input array to its left by one position in the circular fashion. The logic we need to implement should iterate the loop from Length – 1 to 0 and then swap each element with the last element. Please have a look at the following diagram for a better understanding of what we want to achieve.
How to Perform Left Circular Rotation of an Array in C#

Left Circular Rotation of an Array in C#:
In the following example, first, we take the input integer array from the user. Then we perform the left circular rotation using for loop.
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] oneDimensionalArray = new int[6];
            Console.WriteLine("Enter the 1D Array Elements : ");
            for (int i = 0; i< oneDimensionalArray.Length; i++)
            {
                oneDimensionalArray[i] = int.Parse(Console.ReadLine());
            }
            
            int temp;
            for (int j = 0; j < oneDimensionalArray.Length - 1; j++)
            {
                temp = oneDimensionalArray[0];
                oneDimensionalArray[0] = oneDimensionalArray[j + 1];
                oneDimensionalArray[j + 1] = temp;
            }
            Console.WriteLine("Array Elements After Right Circular Rotation: ");
            foreach (int num in oneDimensionalArray)
            {
                Console.Write(num + " ");
            }
            
            Console.ReadKey();
        }
    }
}
Output:
How to Perform Left Circular Rotation of an Array in C#

In the next article, I am going to discuss how to perform the Right circular rotation of an array in C# with examples. I hope now you understood How to Perform Left Circular Rotation of an Array in C#.

Summary:
I hope this post will be helpful to understand How to Perform Left Circular Rotation of an Array 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

How to convert a one-dimensional array to a two-dimensional array in C#

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

In this article, I am going to discuss how to convert a one-dimensional array to a two-dimensional array in C# with an example. Please read our previous article where we discussed how to convert a two-dimensional array to a one-dimensional array in C# with some examples.

Program Description:
Here, the user will input a one-dimensional array along with the number of rows and columns for the two-dimensional array. Then we need to convert the one-dimensional array to a two-dimensional array based on the given rows and columns. For a better understanding of what we want to do, please have a look at the following diagram.
How to convert a one-dimensional array to a two-dimensional array in C#

Note: The number of elements in the array should be the multiplication of the number of rows and number of columns.

Creating a 2d Array from 1D Array in C#:
In the following program, first, we take the number of rows and columns for the 2d array from the user. Then we create and populate the 1d array with the required data. Based on the number of rows and columns we created the 2d array and using two loops we populate the 2d array with data coming from the 1d array.
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the Number of Rows : ");
            int Rows = int.Parse(Console.ReadLine());
            Console.Write("Enter the Number of Columns : ");
            int Columns = int.Parse(Console.ReadLine());
            //Creating a 1d Array 
            Console.WriteLine("Enter the 1D Array Elements : ");
            int[] oneDimensionalArray = new int[Rows * Columns];
            for(int i = 0; i< oneDimensionalArray.Length; i++)
            {
                oneDimensionalArray[i] = int.Parse(Console.ReadLine());
            }
            
            //Creating 2d Array
            int index = 0;
            int[,] twoDimensionalArray = new int[Rows, Columns];
            
            for (int x = 0; x < Rows; x++)
            {
                for (int y = 0; y < Columns; y++)
                {
                    twoDimensionalArray[x, y] = oneDimensionalArray[index];
                    index++;
                }
            }
            //Printing the 2D array elements
            Console.WriteLine("2D Array Elements : ");
            foreach (int item in twoDimensionalArray)
            {
                Console.Write(item + " ");
            }
            Console.ReadKey();
        }
    }
}
Output:
How to convert a one-dimensional array to a two-dimensional array in C#

In the next article, I am going to discuss How to perform Left circular rotation of an array in C# with examples. I hope now you understood How to convert a one-dimensional array to a two-dimensional array in C#.

Summary:
I hope this post will be helpful to understand How to convert a one-dimensional array to a two-dimensional array 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

How to convert a two-dimensional array to one-dimensional array in C#

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

In this article, I am going to discuss how to convert a two-dimensional array to a one-dimensional array in C# with some examples. Please read our previous article where we discussed How to Find All Possible Substring of a Given String in C# with some examples. As part of this article, we will discuss the following two approaches.
  1. How to convert a 2d array into 1d array column-wise in C#?
  2. How to convert a 2d array into 1d array row-wise in C#?
Program Description:
Here, the user will input a two-dimensional array (i.e. matrix) and we need to convert that 2D array to a one-dimensional array. Here, we will create the one-dimensional array row-wise as well as column-wise. For better understanding please have a look at the following diagram.
How to convert a two-dimensional array to one-dimensional array in C#

Creating a 1D Array from 2D Array Column Wise in C#:
The following program is self-explained. So, please go through the comment lines for better understanding. In the following example, we convert the 2d array to 1d array column-wise.
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating a 2d Array with 2 rows and three columns
            int[,] int2DArray = new int[2, 3];
            Console.Write("Enter 2D Array Elements : ");
            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    int2DArray[i, j] = Convert.ToInt32(Console.ReadLine());
                }
            }
            int index = 0;
            //Getting the no of rows of 2d array 
            int NoOfRows = int2DArray.GetLength(0);
            //Getting the no of columns of the 2d array
            int NoOfColumns = int2DArray.GetLength(1);
            //Creating 1d Array by multiplying NoOfRows and NoOfColumns
            int[] OneDimensionalArray = new int[NoOfRows * NoOfColumns];
            
            //Assigning the elements to 1d Array from 2d array
            for (int y = 0; y < NoOfColumns; y++)
            {
                for (int x = 0; x < NoOfRows ; x++)
                {
                    OneDimensionalArray[index] = int2DArray[x, y];
                    index++;
                }
            }
            //Printing the 1d array elements
            Console.WriteLine("1D Array Elements : ");
            foreach (int item in OneDimensionalArray)
            {
                Console.Write(item + " ");
            }
            Console.ReadKey();
        }
    }
}
Output:
Creating a 1D Array from 2D Array Column Wise in C#

Creating the 1D Array From 2D Array Row Wise in C#:
In the following program, we convert the two-dimensional array to one-dimensional row-wise. For better understanding please go through the comment lines.
using System.Linq;
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating a 2d Array with 2 rows and three columns
            int[,] int2DArray = new int[2, 3];
            Console.Write("Enter 2D Array Elements : ");
            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    int2DArray[i, j] = Convert.ToInt32(Console.ReadLine());
                }
            }
            int index = 0;
            //Getting the no of rows of 2d array 
            int NoOfRows = int2DArray.GetLength(0);
            //Getting the no of columns of the 2d array
            int NoOfColumns = int2DArray.GetLength(1);
            //Creating 1d Array by multiplying NoOfRows and NoOfColumns
            int[] OneDimensionalArray = new int[NoOfRows * NoOfColumns];
            
            //Assigning the elements to 1d Array from 2d array
            for (int y = 0; y < NoOfRows ; y++)
            {
                for (int x = 0; x < NoOfColumns; x++)
                {
                    OneDimensionalArray[index] = int2DArray[y, x];
                    index++;
                }
            }
            //Printing the 1d array elements
            Console.WriteLine("1D Array Elements : ");
            foreach (int item in OneDimensionalArray)
            {
                Console.Write(item + " ");
            }
            Console.ReadKey();
        }
    }
}
Output:
Creating the 1D Array From 2D Array Row Wise in C#

In the next article, I am going to discuss how to convert a one-dimensional array to a two-dimensional array in C# with examples. I hope now you understood how to convert a two-dimensional array to a one-dimensional array in C# with different mechanisms.

Summary:
I hope this post will be helpful to understand How to convert a two-dimensional array to one-dimensional array 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

Saturday, August 15, 2020

How to Find All Substrings of a Given String in C#

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

In this article, I am going to discuss How to Find All Substrings of a Given String in C# with some examples. Please read our previous article where we discussed how to remove duplicate characters from a string in C# with some examples. As part of this article, we are going to implement the above program in the following ways.
  1. Without and with using Built-in Methods to Find all Possible Substrings of a Given String.
  2. How to find only the unique substrings of a given string in C#.
  3. Using Linq to Find ALL possible substring as well as Unique substring of a given string.
Program Description:
Here, we will take the input as a string from the console and then need to print all the possible substrings of that string. The substring of a given string is nothing but the characters or the group of characters that are present within the string. To understand this better please have a look at the following diagram which shows the string and its possible substrings.
How to Find All Substrings of a Given String in C#

Algorithm to find all possible substring of a given string:

Step1: Define a string.
Step2: The first loop (i.e. the outer loop) will keep the first character of the substring.
Step3: The second loop (i.e. the inner loop) will build the substring by adding one character in each iteration till the end of the string is reached.
    For Example, if the given String is “ABCD”
    Then the first loop will hold the position of A, then B then C and finally D
    The second loop will be substring the string into
       For i=1: A, AB, ABC, then ABCD for the last iteration
       For i=2: B, BC and then BCD
       For i=3: C and then CD
       For i=4: D
Step4: Print the substring

Using a Simple Approach:
In the following example, we used two loops. The outer loop is used to maintain the relative position of the first character and the inner loop is used to create all possible substrings one by one and print them on the console.
using System;
using System.Text;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string inputString = Console.ReadLine();
           
            Console.WriteLine("All substrings for given string are : ");
            
            for (int i = 0; i < inputString.Length; ++i)
            {
                StringBuilder subString = new StringBuilder(inputString.Length - i);
                for (int j = i; j < inputString.Length; ++j)
                {
                    subString.Append(inputString[j]);
                    Console.Write(subString + " ");
                }
            }
            Console.ReadKey();
        }
    }
}
Output:
Algorithm to find all possible substring of a given string in C#

Using Substring method:
In the following example, we use the built-in substring method to create the string. The Substring (i, len) creates a substring of length ‘len’ starting from index i in the given string.
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string inputString = Console.ReadLine();
            
            int len = inputString.Length;
            Console.WriteLine("All substrings for given string are : ");
            
            //This loop maintains the starting character  
            for (int i = 0; i < len; i++)
            {
                //This loop adds the next character every iteration for the substring and then print
                for (int j = 0; j < len - i; j++)
                {
                    Console.Write (inputString.Substring(i, j + 1) + " ");
                }
            }
            
            Console.ReadKey();
        }
    }
}
Output:
Using Substring method to create a string in C#

As you can see in the above output, it prints all the possible substrings of a given string. Further, if you observe it is not maintaining the uniqueness of the strings. That is some substrings (such as A, AB, B) are appear multiple times.

Finding Unique Substrings of a Given String in C#:
In the following example, we are storing all the possible substrings into an array. Then use the Linq Distinct method to get the distinct values only.
using System.Linq;
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string inputString = Console.ReadLine();
            int len = inputString.Length;
            int temp = 0;
            //Total possible substrings for string of size n is n*(n+1)/2  
            String[] SubstringArray = new String[len * (len + 1) / 2];
            
            //This loop maintains the starting character  
            for (int i = 0; i < len; i++)
            {
                //This loop adds the next character every iteration for the substring 
                //and then store into the array
                for (int j = 0; j < len - i; j++)
                {
                    SubstringArray[temp] = inputString.Substring(i, j + 1);
                    temp++;
                }
            }
            //Get the distinct array  
            SubstringArray = SubstringArray.Distinct().ToArray();
            //Print the array  
            Console.WriteLine("All Unique substrings for given string are : ");
            for (int i = 0; i < SubstringArray.Length; i++)
            {
                Console.Write(SubstringArray[i] + " ");
            }
            
            Console.ReadKey();
        }
    }
}
Output:
Finding Unique Substrings of a Given String in C#:

Note: All the possible substrings for a string will be n*(n + 1)/2. So, here we are creating the string array with the size n*(n+1)/2.

Using LINQ to Find All and Unique Substrings of a Given String in C#:
In the following example, we show you how to use the LINQ query to find all the possible substrings as well as unique strings of a given string.
using System.Linq;
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string inputString = Console.ReadLine();
            
            var Substrings =
                from i in Enumerable.Range(0, inputString.Length)
                from j in Enumerable.Range(0, inputString.Length - i + 1)
                where j >= 1
                select inputString.Substring(i, j);
            //Print the array 
            Console.WriteLine();
            Console.WriteLine("All substrings for given string are : ");
            foreach (string substring in Substrings)
            {
                Console.Write(substring + " ");
            }
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("All Unique substrings for given string are : ");
            foreach (string substring in Substrings.Distinct())
            {
                Console.Write(substring + " ");
            }
            Console.ReadKey();
        }
    }
}
Output:
Using LINQ to Find All and Unique Substrings of a Given String in C#

In the next article, I am going to discuss how to convert a 2d array to a 1d array in C# using different mechanisms. I hope now you understood How to Find All Substrings of a Given String in C# with different mechanisms.

Summary:
I hope this post will be helpful to understand How to Find All Substrings of a Given String 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

How to Remove Duplicate Characters From a String in C#

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

In this article, I am going to discuss how to remove duplicate characters from a string in C# with some examples. Please read our previous article where we discussed How to Reverse Each Word in a Given String in C# with some examples. As part of this article, we are going to use the following three approaches to remove the duplicate characters from the given string C#.
  1. The simple way of Implementation to remove duplicate characters
  2. Using HashSet to Remove Duplicate Characters from a string
  3. Using LINQ to Remove Duplicate Characters from a string
Program Description:
Here, the user will input a string and that string may contain some characters multiple times. Our requirement is to have a character only once in the string. So here we need to remove the duplicate characters from the string. For better understanding, please have a look at the following diagram which shows the input and the expected output.
How to Remove Duplicate Characters from a String in C#

The Simple way of Implementation:
In the following program, we are looping through all the characters of the input and string and then checking whether that character is already there in the result string. If it is already there then we simply ignore it else we add that character to the end of the result string.
using System;
using System.Linq;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string inputString = Console.ReadLine();
            string resultString = string.Empty;
            for (int i = 0; i < inputString.Length; i++)
            {
                if (!resultString.Contains(inputString[i]))
                {
                    resultString += inputString[i];
                }
            }
            Console.WriteLine(resultString);
            Console.ReadKey();
        }
    }
}
Here, we use the Contains method which will check whether a character is present or not.

Using HashSet to Remove Duplicate Characters:
In the following example, we use HashSet to map the string to char. This will remove the duplicate characters from a string.
using System;
using System.Collections.Generic;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string inputString = Console.ReadLine();
            string resultString = string.Empty;
            var unique = new HashSet<char>(inputString);
            foreach (char c in unique)
            {
                resultString += c;
            }
            Console.WriteLine("After Removing Duplicates : " + resultString);
            Console.ReadKey();
        }
    }
}
Using LINQ to Remove Duplicate Characters From a String:
In the following example, first we are converting the string into a character array and then we are applying the LINQ Distinct method to remove the duplicate characters. Finally, we convert the character array into a string which should contain the unique characters.
using System.Linq;
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string inputString = Console.ReadLine();
            
            var uniqueCharArray = inputString.ToCharArray().Distinct().ToArray();
            var resultString = new string(uniqueCharArray);
            Console.WriteLine("After Removing Duplicates : " + resultString);
            Console.ReadKey();
        }
    }
}
Output:
Using LINQ to Remove Duplicate characters from a string in C#

In the next article, I am going to discuss how to find all possible substrings of a given string in C# with some examples. I hope now you understood How to remove duplicate characters from a string with different ways.

Summary:
I hope this post will be helpful to write a program to Remove Duplicate Characters From a String 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 Each Word in a Given String in C#

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

In this article, I am going to discuss How to Reverse Each Word in a Given String in C# with some examples. Please read our previous article where we discussed How to Reverse a String in C# program with some examples. As part of this article, we are going to use the following three approaches to reverse each word in a given string C#.
  1. Without using a built-in function
  2. Using Stack
  3. Using LINQ
Program Description:
The user will input a string and we need to reverse each word individually without changing its position in the string. Here, we will take the input as a string from the user, and then we need to reverse each word individually without changing their position in the sentence as shown in the below image.
How to Reverse Each Word in a Given String in C#

Method1: Without using any built-in function:
In the following example, we generate all words separated by space. Then reverse the words one by one.
using System;
using System.Collections.Generic;
using System.Text;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string originalString = Console.ReadLine();
            StringBuilder reverseWordString = new StringBuilder();
            List<char> charlist = new List<char>();
            for (int i = 0; i < originalString.Length; i++)
            {
                if (originalString[i] == ' ' || i == originalString.Length - 1)
                {
                    if (i == originalString.Length - 1)
                        charlist.Add(originalString[i]);
                    for (int j = charlist.Count - 1; j >= 0; j--)
                        reverseWordString.Append(charlist[j]);
                    reverseWordString.Append(' ');
                    charlist = new List<char>();
                }
                else
                {
                    charlist.Add(originalString[i]);
                }    
            }
            Console.WriteLine($"Reverse Word String : {reverseWordString.ToString()}");
            Console.ReadKey();
        }      
    }
}
Output:
Reverse Each Word in a Given String in C# without using built-in method

Method2: Using Stack to Reverse Each Word in C#
Here, we are using a stack to push all words before space. Then as soon as we encounter a space, we empty the stack. The program is self-explained, so please go through the comments line.
using System;
using System.Collections.Generic;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string originalString = Console.ReadLine();
            Stack<char> charStack = new Stack<char>();
            // Traverse the given string and push all characters
            // to stack until we see a space.  
            for (int i = 0; i < originalString.Length; ++i)
            {
                if (originalString[i] != ' ')
                {
                    charStack.Push(originalString[i]);
                }
                // When seeing a space, then print contents of the stack.  
                else
                {
                    while (charStack.Count > 0)
                    {
                        Console.Write(charStack.Pop());
                    }
                    Console.Write(" ");
                }
            }
            // Since there may not be space after last word.  
            while (charStack.Count > 0)
            {
                Console.Write(charStack.Pop());
            }
            
            Console.ReadKey();
        }      
    }
}
Method3: Using Linq to Reverse Each Word in C#
using System;
using System.Linq;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string originalString = Console.ReadLine();
            
            string reverseWordString = string.Join(" ", originalString
            .Split(' ')
            .Select(x => new String(x.Reverse().ToArray())));
            Console.WriteLine($"Reverse Word String : {reverseWordString}");
            Console.ReadKey();
        }      
    }
}
Output:
Reverse Each Word in a Given String in C# without using Linq

Code Explanation:
Split the input string using a single space as the separator.

The Split method is used for returning a string array that contains each word of the input string. We use the Select method for constructing a new string array, by reversing each character in each word. Finally, we use the Join method for converting the string array into a string.

In the next article, I am going to discuss How to Remove Duplicate Characters from a given string in C# using different mechanisms. I hope now you understood How to Reverse Each Word in a Given String in C# with different mechanisms.

Summary:
I hope this post will be helpful to write a program to Reverse Each Word in a Given String 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

Tuesday, August 11, 2020

How to Reverse a String in C#

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

In this article, I am going to discuss How to Reverse a String in C# with and without using built-in Methods. Please read our previous article where we discussed Character Occurrence in a String in C# program with some examples. As part of this article, we are going to use the following three approaches to reverse a string C#.
  1. Using For Loop
  2. Using For Each Loop
  3. Using the built-in Reverse method of Array class
Program Description:
Here, we will take the input as a string from the user, and then we will convert that string in reverse order as shown in the below image.
How to Reverse a String in C# with Different Mechanisms:

Reverse a String in C# without using Built-in method:
In the below program, we are using for loop to reverse a string.
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string originalString = Console.ReadLine();
            string reverseString = string.Empty;
            for (int i = originalString.Length - 1; i >= 0; i--)
            {
                reverseString += originalString[i];
            }
            Console.Write($"Reverse String is : {reverseString} ");
            Console.ReadLine();
        }      
    }
}
Output:
Reverse a String in C# without using Built-in method

Using the for-each loop to reverse a string in C#:
In the following example, we use for each loop to reverse a string in C#.
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string originalString = Console.ReadLine();
            string reverseString = string.Empty;
            foreach (char c in originalString)
            {
                reverseString = c + reverseString;
            }
            Console.Write($"Reverse String is : {reverseString} ");
            Console.ReadLine();
        }      
    }
}
Reverse a String Using in-built Reverse Method in C#:
In the following example, we use the built-in Reverse method of the Array class to reverse a string.
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a String : ");
            string originalString = Console.ReadLine();
            char[] stringArray = originalString.ToCharArray();
            Array.Reverse(stringArray);
            string reverseString = new string(stringArray);
            
            Console.Write($"Reverse String is : {reverseString} ");
            Console.ReadLine();
        }      
    }
}
In the next article, I am going to discuss how to reverse each word in a given string in C# using different mechanisms. I hope now you understood how to reverse a string with and without using any built-in method in C#.

Summary:
I hope this post will be helpful to understand How to Reverse a String 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

Character Occurrence in a String in C# with Examples

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

In this article, I am going to discuss the Character Occurrence in a String in C# program with some examples. Please read our previous article where we discussed the Binary to Decimal Conversion Program in C# with some examples. This is one of the most frequently asked interview questions in the interview. Here as part of this article, we are going to discuss the following mechanisms to count the character occurrences in a string.
  1. Using Loop to Count the Character Occurrence in a String.
  2. How to use Dictionary to Count the Number of Occurrences of character in C#.
  3. Using LINQ Group By method to count character occurrences.
Using Loop to Count the Character Occurrence in a String in C#:
Here in the following program, we take the input from Console and then remove the blank spaces from the input if any. Check the length of the input message and if it is greater than 0, then using for loop we calculate the number of occurrences of each character,
using System;
namespace LogicalProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the string : ");
            string message = Console.ReadLine();
            //Remove the empty spaces from the message
            message = message.Replace(" ", string.Empty);
            
            while (message.Length > 0)
            {
                Console.Write(message[0] + " : ");
                int count = 0;
                for (int j = 0; j < message.Length; j++)
                {
                    if (message[0] == message[j])
                    {
                        count++;
                    }
                }
                Console.WriteLine(count);
                message = message.Replace(message[0].ToString(), string.Empty);
            }
            Console.ReadKey();
        }
    }
}
Output:
Using Loop to Count the Character Occurrence in a String in C#

Using Dictionary to Count the Number of Occurrences of character in C#:
In the below program, we created a dictionary to store each character and its count. We take the input message from the console and then loop through each character of the input message. For each character, we check whether that character already there in the dictionary or not. If already there then just increased its count by 1 else add that character to the dictionary with count as 1.
using System;
using System.Collections.Generic;
namespace LogicalProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the string : ");
            string message = Console.ReadLine();
            Dictionary<char, int> dict = new Dictionary<char, int>();
            foreach (char ch in message.Replace(" ", string.Empty))
            {
                if (dict.ContainsKey(ch))
                {
                    dict[ch] = dict[ch] + 1;
                }
                else
                {
                    dict.Add(ch, 1);
                }
            }
            foreach (var item in dict.Keys)
            {
                Console.WriteLine(item + " : " + dict[item]);
            }
            Console.ReadKey();
        }
    }
}
Output:
Using Dictionary to Count the Number of Occurrences of character in C#

Using LINQ Group By method to count character occurrences in C#:
In the following program, we take the input message from the console and replace the blank spaces with an empty string. Then we use Linq Group By method to group each character and convert the result into a dictionary where the character is the key and the number of counts is its value.
using System;
using System.Collections.Generic;
using System.Linq;
namespace LogicalProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the string : ");
            string message = Console.ReadLine();
            Dictionary<char, int> dict = message.Replace(" ", string.Empty)
                                         .GroupBy(c => c)
                                         .ToDictionary(gr => gr.Key, gr => gr.Count());
            foreach (var item in dict.Keys)
            {
                Console.WriteLine(item + " : " + dict[item]);
            }
            Console.ReadKey();
        }
    }
}
Output:
Using LINQ Group By method to count character occurrences

In the next article, I am going to discuss how to reverse a string in C# with and without using a built-in function. Here, in this article, I try to explain the different mechanisms to find the count of each character in a string.

Summary:
I hope this post will be helpful to write a program to find Character Occurrence in a String 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

Binary to Decimal Conversion in C# with Examples

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

In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where we discussed the Decimal to Binary Conversion Program in C# with examples. In C#, we can easily convert a binary number (base-2 (i.e. 0 or 1)) into decimal number (base-10 (i.e. 0 to 9)).

How to Convert Binary Number to Decimal Number in C#?
The following diagram shows how to convert a binary number i.e. 10101 into its equivalent decimal number i.e. 21.
Binary to Decimal Conversion in C#

Implementing Binary to Decimal Conversion Program in C#:
In the following example, first, we extract the digits of a given binary number starting from rightmost digits using the modulus operator. Once we extract the number, then we multiply the digit with the proper base i.e. the power of 2 and add the result into the decimal value variable. In the end, the decimal value variable will hole the required decimal number.
using System;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the Binary Number : ");
            int binaryNumber = int.Parse(Console.ReadLine());
            int decimalValue = 0;
            // initializing base1 value to 1, i.e 2^0 
            int base1 = 1;
            
            while (binaryNumber > 0)
            {
                int reminder = binaryNumber % 10;
                binaryNumber = binaryNumber / 10;
                decimalValue += reminder * base1;
                base1 = base1 * 2;
            }
            Console.Write($"Decimal Value : {decimalValue} ");
            Console.ReadKey();
        }
    }
}
Output:
Implementing Binary to Decimal Conversion in C#

Please Note: The above program works with binary numbers within the range of integers. If you want to work with long binary numbers such as 20 bits or 30 bit, then you need to use the string variable to store the binary numbers.

Binary to Decimal Conversion using Convert.ToInt32() method:
In the following example, we are using the ToInt32 method to convert a binary number to a decimal number. This except expects two parameters. The first parameter is the string representation of the binary number and the second parameter is the base value i.e. in our case it is 2.
using System;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the Binary Number : ");
            int binaryNumber = int.Parse(Console.ReadLine());
            int decimalValue = Convert.ToInt32(binaryNumber.ToString(), 2);           
            Console.Write($"Decimal Value : {decimalValue} ");
            Console.ReadKey();
        }
    }
}
Output:
Binary to Decimal Conversion using Convert.ToInt32() method

In the next article, I am going to discuss the Character Occurrences in a String Program in C# with some examples. Here, in this article, I try to explain the Binary to Decimal Conversion Program in C# with some examples.

Summary:
I hope this post will be helpful to understand Binary to Decimal Conversion 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

Decimal to Binary Conversion in C# with Examples

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

In this article, I am going to discuss the Decimal to Binary Conversion in C# with some examples. Please read our previous article where we discussed the Sum of Digits of a given number Program in C# in many different ways. In C#, we can easily convert any decimal number (base-10 (i.e. 0 to 9)) into binary number (base-2 (i.e. 0 or 1)). As part of this article, we are going to discuss the following pointers.
  1. What are Decimal Numbers?
  2. What are Binary Numbers?
  3. How to Convert Decimal to Binary in C#?
What are Decimal Numbers?
The Decimal numbers are the numbers whose base is 10. That means the decimal numbers are range from 0 to 9. Any combination of such digits (digits from 0 to 9) is a decimal number such as 2238, 1585, 227, 0, 71, etc.

What are Binary Numbers?
The Binary numbers are the numbers whose base is 2. That means the binary numbers can be represent using only two digits i.e. 0 and 1. So, any combination of these two numbers (i.e. 0 and 1) is a binary number such as 101, 10o1, 111111, 10101, etc.

Let us have a look which shows the decimal number along with its binary representation.
Decimal to Binary Conversion in C#

Algorithm: Decimal to Binary Conversion

Step1: First, divide the number by 2 through modulus (%) operator and store the remainder in an array
Step2: Divide the number by 2 through division (/) operator.
Step3: Repeat step 2 until the number is greater than zero.


Program: Decimal to Binary Conversion in C#
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the Decimal Number : ");
            int number = int.Parse(Console.ReadLine());
            int i;
            int[] numberArray = new int[10];
            for (i = 0; number > 0; i++)
            {
                numberArray[i] = number % 2;
                number = number / 2;
            }
            Console.Write("Binary Represenation of the given Number : ");
            for (i = i - 1; i >= 0; i--)
            {
                Console.Write(numberArray[i]);
            }
            Console.ReadKey();
        }
    }
}
Output:
Decimal to Binary Conversion Program in C#

Let us see another way of doing the conversion from Decimal to Binary in C#.
In the following program, we created a string variable to hold the binary representation of the Decimal number.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the Decimal Number : ");
            int number = int.Parse(Console.ReadLine());
            
            string Result = string.Empty;
            for (int i = 0; number > 0; i++)
            {
                Result = number % 2 + Result;
                number = number / 2;
            }
            Console.WriteLine($"Binary Represenation of the given Number : {Result}");
            
            Console.ReadKey();
        }
    }
}
Output:
Conversion from Decimal to Binary in C#

In the next article, I am going to discuss the Binary to Decimal Conversion Program in C# with some examples. Here, in this article, I try to explain the Decimal to Binary Conversion in C# with some examples.

Summary:
I hope this post will be helpful to understand Decimal to Binary Conversion 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

Sum of Digits Program in C# with Examples

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

In this article, I am going to discuss the Sum of Digits Program in C# with some examples. Please read our previous article where we discussed the Factorial Program in C# in many different ways. This is one of the frequently asked interview questions. As part of this article, we will discuss the following things.
  1. How to find the sum of digits of a given number using a loop?
  2. How to find the sum of digits of a given number using recursion?
  3. Using LINQ to find the sum of digits of a number in C#.
Finding the sum of digits of a given number using a loop in C#:
Sum of Digits Program in C# with Examples

Let us first understand the algorithm to find the sum digits of a number.

Algorithm: Sum of Digits Program in C#

Step1: Get the number from the user
Step2: Get the modulus/remainder of that number by doing the modulus operation
Step3: Sum the remainder of the number
Step4: Divide the number by 10
Step5: Repeat step 2 while the number is greater than 0.

Let us put the above steps into a program.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the Number : ");
            int number = int.Parse(Console.ReadLine());
            int sum = 0, reminder;
           
            while (number > 0)
            {
                reminder = number % 10;
                sum = sum + reminder;
                number = number / 10;
            }
            
            Console.WriteLine($"The Sum of Digits is : {sum}");
            Console.ReadKey();
        }
    }
}
Output:
Finding the sum of digits of a given number using a loop in C#

Finding the sum of digits of a number using Recursion in C#:
Let us understand how to find the sum of digits of a number using Recursion in C#. Please have a look at the following program.
using System;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the Number : ");
            int number = int.Parse(Console.ReadLine());
            int sum = SumOfDigits(number);
            Console.WriteLine($"The Sum of Digits is : {sum}");
            Console.ReadKey();
        }
        static int SumOfDigits(int number)
        {
            if (number != 0)
            {
                return (number % 10 + SumOfDigits(number / 10));
            }
            else
            {
                return 0;
            }
        }
    }
}
Output:
Finding the sum of digits of a number using Recursion in C#

Using Linq to find the sum of digits of a number in C#:
In the following program, first, we convert the integer into a string. As we know a string is an array of characters, so we use the Select operator to iterate over the array. For each character digit, first, we parse it to a string and then we parse it to an int. Send the resulting enum to an int[] array. And then apply the Sum extension method on it to get the desired result.
using System;
using System.Linq;
namespace LogicalPrograms
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the Number : ");
            int number = int.Parse(Console.ReadLine());
            
            int sum = number.ToString().Select(digit => int.Parse(digit.ToString())).ToArray().Sum();
            
            Console.WriteLine($"The Sum of Digits is : {sum}");
            Console.ReadKey();
        }
    }
}
Output:
Using Linq to find the sum of digits of a number in C#

In the next article, I am going to discuss Decimal to Binary Conversion Program in C# with some examples. Here, in this article, I try to explain the Sum of Digits Program in C# in many different ways. I hope you enjoy this article.

Summary:
I hope this post will be helpful to write Sum of Digits 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
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...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • 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...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

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