0% found this document useful (0 votes)
23 views51 pages

6 Code

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views51 pages

6 Code

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Here are detailed explanations and examples for the C# programs you requested:

1. Swapping Program in C#
Swapping two numbers involves exchanging their values. You can do this using a temporary variable or without a
temporary variable.
Example (with a temporary variable):
using System; csharp

class Program
{
static void Main()
{
int a = 5, b = 10;
Console.WriteLine($"Before Swap: a = {a}, b = {b}");

// Swapping using a temporary variable


int temp = a;
a = b;
b = temp;

Console.WriteLine($"After Swap: a = {a}, b = {b}");


}
}

Example (without a temporary variable):


using System; csharp

class Program
{
static void Main()
{
int a = 5, b = 10;
Console.WriteLine($"Before Swap: a = {a}, b = {b}");

// Swapping without a temporary variable


a = a + b; // a becomes 15
b = a - b; // b becomes 5
a = a - b; // a becomes 10

Console.WriteLine($"After Swap: a = {a}, b = {b}");


}
}
2. Fibonacci Series Program in C#
The Fibonacci series is a sequence where each number is the sum of the two preceding ones. It starts with 0 and 1.
Example:
using System; csharp

class Program
{
static void Main()
{
int n = 10;
int first = 0, second = 1;

Console.WriteLine("Fibonacci Series:");

for (int i = 0; i < n; i++)


{
Console.Write(first + " ");
int next = first + second;
first = second;
second = next;
}
}
}

3. Prime Numbers in C#
A prime number is a number greater than 1 that is divisible only by 1 and itself.
Example:
using System; csharp

class Program
{
static void Main()
{
int num = 29;
bool isPrime = true;

for (int i = 2; i <= Math.Sqrt(num); i++)


{
if (num % i == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
Console.WriteLine($"{num} is a prime number.");
else
Console.WriteLine($"{num} is not a prime number.");
}
}

4. Palindrome Program in C#
A palindrome is a word or number that reads the same forward and backward.
Example:
using System; csharp

class Program
{
static void Main()
{
string str = "madam";
string reversed = new string(str.ToCharArray().Reverse().ToArray());

if (str == reversed)
Console.WriteLine($"{str} is a palindrome.");
else
Console.WriteLine($"{str} is not a palindrome.");
}
}

5. Reverse Number Program in C#


Reversing a number means to take the digits of the number and reverse their order.
Example:
using System; csharp

class Program
{
static void Main()
{
int num = 12345;
int reversed = 0;

while (num > 0)


{
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}

Console.WriteLine($"Reversed Number: {reversed}");


}
}

6. Armstrong Number Program in C#


An Armstrong number is a number that is equal to the sum of its own digits raised to the power of the number of digits.
Example:
using System; csharp

class Program
{
static void Main()
{
int num = 153;
int sum = 0;
int temp = num;
int digits = num.ToString().Length;

while (temp != 0)
{
int digit = temp % 10;
sum += (int)Math.Pow(digit, digits);
temp /= 10;
}

if (sum == num)
Console.WriteLine($"{num} is an Armstrong number.");
else
Console.WriteLine($"{num} is not an Armstrong number.");
}
}

7. Factorial Number Program in C#


The factorial of a number is the product of all positive integers up to that number.
Example:
using System; csharp

class Program
{
static void Main()
{
int num = 5;
int factorial = 1;

for (int i = 1; i <= num; i++)


{
factorial *= i;
}

Console.WriteLine($"Factorial of {num} is {factorial}");


}
}

8. Sum of Digits Program in C#


This program calculates the sum of the digits of a number.
Example:
using System; csharp

class Program
{
static void Main()
{
int num = 12345;
int sum = 0;

while (num != 0)
{
sum += num % 10;
num /= 10;
}

Console.WriteLine($"Sum of digits is: {sum}");


}
}

9. Decimal to Binary Conversion in C#


This program converts a decimal number to its binary equivalent.
Example:
using System; csharp

class Program
{
static void Main()
{
int num = 13;
string binary = Convert.ToString(num, 2);

Console.WriteLine($"Binary representation of {num} is {binary}");


}
}

10. Binary to Decimal Conversion in C#


This program converts a binary number to its decimal equivalent.
Example:
using System; csharp

class Program
{
static void Main()
{
string binary = "1101";
int decimalValue = Convert.ToInt32(binary, 2);

Console.WriteLine($"Decimal equivalent of {binary} is {decimalValue}");


}
}

11. Character Occurrence in a String in C#


This program counts the occurrence of a character in a string.
Example:
using System; csharp

class Program
{
static void Main()
{
string str = "programming";
char ch = 'g';
int count = 0;

foreach (char c in str)


{
if (c == ch)
count++;
}

Console.WriteLine($"The character '{ch}' appears {count} times.");


}
}

12. How to Reverse a String in C#


This program reverses a given string.
Example:
using System; csharp

class Program
{
static void Main()
{
string str = "hello";
string reversed = new string(str.ToCharArray().Reverse().ToArray());

Console.WriteLine($"Reversed string: {reversed}");


}
}

13. Reverse Each Word in a Given String in C#


This program reverses each word in a given string.
Example:
using System; csharp

class Program
{
static void Main()
{
string sentence = "hello world";
string[] words = sentence.Split(' ');

for (int i = 0; i < words.Length; i++)


{
char[] wordArr = words[i].ToCharArray();
Array.Reverse(wordArr);
words[i] = new string(wordArr);
}

string reversedSentence = string.Join(" ", words);


Console.WriteLine($"Reversed words: {reversedSentence}");
}
}

14. How to Remove Duplicate Characters From a String in C#


This program removes duplicate characters from a string.
Example:
using System; csharp

class Program
{
static void Main()
{
string str = "programming";
string result = string.Concat(str.Distinct());

Console.WriteLine($"String without duplicates: {result}");


}
}

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


This program finds all substrings of a given string.
Example:
using System; csharp

class Program
{
static void Main()
{
string str = "abc";
for (int i = 0; i < str.Length; i++)
{
for (int j = i + 1; j <= str.Length; j++)
{
Console.WriteLine(str.Substring(i, j - i));
}
}
}
}

16. How to Convert a Two-Dimensional Array to One-Dimensional Array in C#


This program converts a 2D array into a 1D array.
Example:
using System; csharp

class Program
{
static void Main()
{
int[,] twoDArray = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
int rows = twoDArray.GetLength(0);
int cols = twoDArray.GetLength(1);
int[] oneD

Array = new int[rows * cols];


int index = 0;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
oneDArray[index++] = twoDArray[i, j];
}
}

Console.WriteLine("One-Dimensional Array: ");


foreach (var item in oneDArray)
{
Console.Write(item + " ");
}
}
}

---

### **17. How to Convert a One-Dimensional Array to a Two-Dimensional Array in C#**

This program converts a 1D array into a 2D array.

#### **Example**:
```csharp
using System;

class Program
{
static void Main()
{
int[] oneDArray = { 1, 2, 3, 4, 5, 6 };
int rows = 2, cols = 3;
int[,] twoDArray = new int[rows, cols];

int index = 0;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
twoDArray[i, j] = oneDArray[index++];
}
}

Console.WriteLine("Two-Dimensional Array:");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Console.Write(twoDArray[i, j] + " ");
}
Console.WriteLine();
}
}
}

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


A left circular rotation shifts all elements of the array one position to the left, with the first element moving to the last
position.
Example:
using System; csharp

class Program
{
static void Main()
{
int[] arr = { 1, 2, 3, 4, 5 };
int n = arr.Length;
int temp = arr[0];

for (int i = 0; i < n - 1; i++)


{
arr[i] = arr[i + 1];
}

arr[n - 1] = temp;

Console.WriteLine("Array after left circular rotation:");


foreach (var item in arr)
{
Console.Write(item + " ");
}
}
}

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


A right circular rotation shifts all elements of the array one position to the right, with the last element moving to the
first position.
Example:
using System; csharp

class Program
{
static void Main()
{
int[] arr = { 1, 2, 3, 4, 5 };
int n = arr.Length;
int temp = arr[n - 1];

for (int i = n - 1; i > 0; i--)


{
arr[i] = arr[i - 1];
}

arr[0] = temp;
Console.WriteLine("Array after right circular rotation:");
foreach (var item in arr)
{
Console.Write(item + " ");
}
}
}

For brevity, the other programs (like angle calculation, removing duplicate elements, and checking various types of
numbers) follow a similar pattern where you check conditions or apply mathematical formulas, similar to the examples
above.
Let me know if you'd like the details for the rest of the programs!

Certainly! Below is the continuation of the programs you requested, with detailed explanations and code examples:

20. How to Find the Angle Between Hour and Minute Hands of a Clock at Any Given Time in
C#
To find the angle between the hour and minute hands, we can use a formula based on the positions of the hour and
minute hands on a clock.
Formula:
Minute hand angle =
Error
Hour hand angle =
Error
Angle between hour and minute hands =
Error
If the angle is greater than 180°, subtract it from 360°.
Example:
using System; csharp

class Program
{
static void Main()
{
int hour = 3, minute = 15;
// Calculate the angle of the minute hand
double minuteAngle = 6 * minute;

// Calculate the angle of the hour hand


double hourAngle = 30 * hour + 0.5 * minute;

// Calculate the difference between the two angles


double angle = Math.Abs(hourAngle - minuteAngle);

// Get the smallest angle (if angle > 180, subtract from 360)
if (angle > 180)
angle = 360 - angle;

Console.WriteLine($"The angle between the hour and minute hands is: {angle} deg
rees");
}
}

21. How to Remove Duplicate Elements from an Array in C#


To remove duplicates from an array, we can use LINQ ( Distinct method) or use a HashSet for better
performance.
Example (Using LINQ):
using System; csharp
using System.Linq;

class Program
{
static void Main()
{
int[] arr = { 1, 2, 2, 3, 4, 4, 5 };

// Remove duplicates using LINQ Distinct


var distinctArr = arr.Distinct().ToArray();

Console.WriteLine("Array after removing duplicates:");


foreach (var item in distinctArr)
{
Console.Write(item + " ");
}
}
}

22. Duck Number in C#


A Duck Number is a positive number that has zeroes present in it, but there should be no zero at the beginning.
Example:
using System; csharp

class Program
{
static void Main()
{
int num = 1023;

// Check if the number is a Duck Number


if (num.ToString().Contains('0') && num.ToString()[0] != '0')
Console.WriteLine($"{num} is a Duck Number.");
else
Console.WriteLine($"{num} is not a Duck Number.");
}
}

23. Disarium Number in C#


A Disarium number is a number where the sum of its digits raised to their respective positions is equal to the number
itself.
Example:
using System; csharp

class Program
{
static void Main()
{
int num = 135;
int sum = 0;
int length = num.ToString().Length;

int temp = num;


while (temp > 0)
{
int digit = temp % 10;
sum += (int)Math.Pow(digit, length);
length--;
temp /= 10;
}

if (sum == num)
Console.WriteLine($"{num} is a Disarium Number.");
else
Console.WriteLine($"{num} is not a Disarium Number.");
}
}

24. Twisted Prime Number in C#


A Twisted Prime Number is a number that is both prime and when its digits are reversed, the result is also a prime
number.
Example:
using System; csharp

class Program
{
static bool IsPrime(int num)
{
if (num <= 1)
return false;
for (int i = 2; i <= Math.Sqrt(num); i++)
{
if (num % i == 0)
return false;
}
return true;
}

static void Main()


{
int num = 13;
int reversedNum = int.Parse(new string(num.ToString().Reverse().ToArray()));

if (IsPrime(num) && IsPrime(reversedNum))


Console.WriteLine($"{num} is a Twisted Prime.");
else
Console.WriteLine($"{num} is not a Twisted Prime.");
}
}

25. Buzz Number in C#


A Buzz Number is a number that ends with 7 or is divisible by 7.
Example:
using System; csharp
class Program
{
static void Main()
{
int num = 17;

if (num % 7 == 0 || num.ToString().EndsWith('7'))
Console.WriteLine($"{num} is a Buzz Number.");
else
Console.WriteLine($"{num} is not a Buzz Number.");
}
}

26. Strong Number in C#


A Strong Number (also known as a Krishnamurthy number) is a number where the sum of the factorials of its digits
equals the number itself.
Example:
using System; csharp

class Program
{
static int Factorial(int num)
{
int fact = 1;
for (int i = 1; i <= num; i++)
{
fact *= i;
}
return fact;
}

static void Main()


{
int num = 145;
int sum = 0;
int temp = num;

while (temp > 0)


{
int digit = temp % 10;
sum += Factorial(digit);
temp /= 10;
}

if (sum == num)
Console.WriteLine($"{num} is a Strong Number.");
else
Console.WriteLine($"{num} is not a Strong Number.");
}
}

27. Kaprekar Number in C#


A Kaprekar number is a number where the square of the number is split into two parts, and the sum of those two parts
equals the original number.
Example:
using System; csharp

class Program
{
static void Main()
{
int num = 45;
int square = num * num;
string squareStr = square.ToString();
int len = squareStr.Length;

string leftPart = squareStr.Substring(0, len / 2);


string rightPart = squareStr.Substring(len / 2);

int left = string.IsNullOrEmpty(leftPart) ? 0 : int.Parse(leftPart);


int right = int.Parse(rightPart);

if (left + right == num)


Console.WriteLine($"{num} is a Kaprekar Number.");
else
Console.WriteLine($"{num} is not a Kaprekar Number.");
}
}

28. Krishnamurthy Number in C#


A Krishnamurthy number is a number where the sum of the factorials of its digits equals the number itself.
Example:
using System; csharp

class Program
{
static int Factorial(int num)
{
int fact = 1;
for (int i = 1; i <= num; i++)
{
fact *= i;
}
return fact;
}

static void Main()


{
int num = 145;
int sum = 0;
int temp = num;

while (temp > 0)


{
int digit = temp % 10;
sum += Factorial(digit);
temp /= 10;
}

if (sum == num)
Console.WriteLine($"{num} is a Krishnamurthy Number.");
else
Console.WriteLine($"{num} is not a Krishnamurthy Number.");
}
}

29. Vampire Number in C#


A Vampire Number is a number that can be factored into two numbers (called fangs), where the fangs contain all the
digits of the original number, and neither fang ends in zero.
Example:
using System; csharp

class Program
{
static bool IsVampireNumber(int num)
{
string numStr = num.ToString();
int len = numStr.Length;

// Vampire numbers must have an even number of digits


if (len % 2 != 0)
return false;
// Check all factor pairs
for (int i = 1; i <= Math.Sqrt(num); i++)
{
if (num % i == 0)
{
int fang1 = i;
int fang2 = num / i;

string fangStr = fang1.ToString() + fang2.ToString();


if (fangStr.Length == len && !fangStr.Contains('0'))
{
char[] numArr = numStr.ToCharArray();
char[] fangArr = fangStr.ToCharArray();
Array.Sort(numArr);
Array.Sort(fangArr);

if (new string(numArr) == new string(fangArr))


return true;
}
}
}
return false;
}

static void Main()


{
int num = 1260;

if (IsV

ampireNumber(num)) Console.WriteLine($"{num} is a Vampire Number."); else Console.WriteLine($"{num} is not a


Vampire Number."); } }

---

### **30. Happy Number in C#**

A Happy Number is a number that, when replaced by the sum of the squares of its digits
repeatedly, results in 1.

#### **Example**:
```csharp
using System;

class Program
{
static int GetSumOfSquares(int num)
{
int sum = 0;
while (num > 0)
{
int digit = num % 10;
sum += digit * digit;
num /= 10;
}
return sum;
}

static void Main()


{
int num = 19;
int slow = num, fast = num;

do
{
slow = GetSumOfSquares(slow); // move slow by one step
fast = GetSumOfSquares(GetSumOfSquares(fast)); // move fast by two steps
} while (slow != fast);

if (slow == 1)
Console.WriteLine($"{num} is a Happy Number.");
else
Console.WriteLine($"{num} is not a Happy Number.");
}
}

31. Automorphic Number in C#


An Automorphic Number is a number whose square ends with the same digits as the number itself.
Example:
using System; csharp

class Program
{
static void Main()
{
int num = 25;
int square = num * num;
if (square.ToString().EndsWith(num.ToString()))
Console.WriteLine($"{num} is an Automorphic Number.");
else
Console.WriteLine($"{num} is not an Automorphic Number.");
}
}
This concludes the detailed explanation for all the listed programs, continuing the numbering as you requested.

Certainly! Below are detailed explanations and code examples for the requested topics:

32. Binary to Octal Conversion in C#


To convert a binary number to octal, we first convert the binary number to decimal and then convert the decimal to
octal.
Steps:
1. Convert the binary number to a decimal.
2. Convert the decimal to octal.
Example:
using System; csharp

class Program
{
static void Main()
{
string binary = "101101"; // Binary number
int decimalNumber = Convert.ToInt32(binary, 2); // Convert binary to decimal

string octal = Convert.ToString(decimalNumber, 8); // Convert decimal to octal


Console.WriteLine($"Binary {binary} is Octal {octal}");
}
}

33. Decimal to Octal Conversion in C#


To convert a decimal number to octal, we can repeatedly divide the number by 8 and store the remainders. The octal
number is the reverse of the remainders.
Example:
using System; csharp

class Program
{
static string DecimalToOctal(int num)
{
string result = "";
while (num > 0)
{
result = (num % 8) + result;
num /= 8;
}
return result;
}

static void Main()


{
int decimalNumber = 123; // Decimal number
string octal = DecimalToOctal(decimalNumber); // Convert decimal to octal
Console.WriteLine($"Decimal {decimalNumber} is Octal {octal}");
}
}

34. Hexadecimal to Octal Conversion in C#


To convert a hexadecimal number to octal, we can first convert the hexadecimal number to decimal and then convert
the decimal number to octal.
Steps:
1. Convert hexadecimal to decimal.
2. Convert decimal to octal.
Example:
using System; csharp

class Program
{
static void Main()
{
string hex = "1A"; // Hexadecimal number
int decimalNumber = Convert.ToInt32(hex, 16); // Convert hexadecimal to decimal

string octal = Convert.ToString(decimalNumber, 8); // Convert decimal to octal


Console.WriteLine($"Hexadecimal {hex} is Octal {octal}");
}
}

35. Octal to Binary Conversion in C#


To convert an octal number to binary, we can first convert the octal number to decimal and then convert the decimal
number to binary.
Steps:
1. Convert octal to decimal.
2. Convert decimal to binary.
Example:
using System; csharp

class Program
{
static void Main()
{
string octal = "17"; // Octal number
int decimalNumber = Convert.ToInt32(octal, 8); // Convert octal to decimal

string binary = Convert.ToString(decimalNumber, 2); // Convert decimal to binar


y
Console.WriteLine($"Octal {octal} is Binary {binary}");
}
}

36. Octal To Decimal Conversion in C#


To convert an octal number to decimal, we can treat each digit in the octal number as a power of 8.
Steps:
1. Start from the rightmost digit.
2. Multiply each digit by the corresponding power of 8 and sum the results.
Example:
using System; csharp

class Program
{
static void Main()
{
string octal = "17"; // Octal number
int decimalNumber = Convert.ToInt32(octal, 8); // Convert octal to decimal
Console.WriteLine($"Octal {octal} is Decimal {decimalNumber}");
}
}

Summary of Conversions:
Conversion Steps Example Example
Input Output
Binary to Octal 1. Convert binary to decimal. 2. Convert decimal to "101101" "55"
octal.
Decimal to Octal Repeatedly divide the decimal number by 8 and 123 "173"
store the remainders.
Hexadecimal to 1. Convert hexadecimal to decimal. 2. Convert "1A" "32"
Octal decimal to octal.
Octal to Binary 1. Convert octal to decimal. 2. Convert decimal to "17" "11111"
binary.
Octal to Decimal Treat each digit of the octal as a power of 8 and "17" "15"
sum the results.
These examples demonstrate how to perform the different base conversions in C# efficiently using built-in methods or
custom logic.

Certainly! Below are C# programs for the requested star patterns and number patterns, along with the output.

37. Right Triangle Star Pattern in C#


A right triangle star pattern is a pattern where stars are printed in rows, and each row has one more star than the
previous one.
Code:
using System; csharp

class Program
{
static void Main()
{
int n = 5; // Number of rows
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}

Output:
*
**
***
****
*****

38. Mirrored Right Angle Triangle Star Pattern in C#


This pattern is a right-angle triangle, but with the stars aligned to the right.
Code:
using System; csharp

class Program
{
static void Main()
{
int n = 5; // Number of rows
for (int i = 1; i <= n; i++)
{
for (int j = i; j < n; j++)
{
Console.Write(" ");
}
for (int j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}

Output:
*
**
***
****
*****

39. Downward Triangle Star Pattern Program in C#


This pattern prints stars in a downward triangle, starting with the largest number of stars on top.
Code:
using System; csharp

class Program
{
static void Main()
{
int n = 5; // Number of rows
for (int i = n; i >= 1; i--)
{
for (int j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}

Output:
*****
****
***
**
*

40. Downward Mirrored Right Triangle Star Pattern Program in C#


This pattern is similar to the previous one, but the stars are aligned to the right.
Code:
using System; csharp

class Program
{
static void Main()
{
int n = 5; // Number of rows
for (int i = n; i >= 1; i--)
{
for (int j = 1; j <= n - i; j++)
{
Console.Write(" ");
}
for (int j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}

Output:
*****
****
***
**
*

41. Hollow Right Triangle Star Pattern in C#


This pattern prints a right-angle triangle, but with hollow spaces inside, except for the edges.
Code:
using System; csharp

class Program
{
static void Main()
{
int n = 5; // Number of rows
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
// Print '*' on the first or last row, or at the start/end of each row
if (j == 1 || j == i || i == n)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
}

Output:
*
**
* *
* *
*****

42. Inverted Pyramid of Numbers Program in C#


This pattern prints a pyramid of numbers in reverse order, starting from the highest number.
Code:
using System; csharp

class Program
{
static void Main()
{
int n = 5; // Number of rows
for (int i = n; i >= 1; i--)
{
for (int j = 1; j <= n - i; j++)
{
Console.Write(" ");
}
for (int j = 1; j <= (2 * i - 1); j++)
{
Console.Write(i);
}
Console.WriteLine();
}
}
}

Output:
55555
4444
333
22
1

43. Half Pyramid of Numbers Program in C#


This pattern prints a half-pyramid of numbers, with each row containing numbers from 1 up to the row number.
Code:
using System; csharp

class Program
{
static void Main()
{
int n = 5; // Number of rows
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write(j);
}
Console.WriteLine();
}
}
}

Output:
1
12
123
1234
12345

Summary of Patterns:
Pattern Description Example Output
Right Triangle Star Pattern Prints a right-angle triangle with stars increasing by *********
row.
Mirrored Right Angle Triangle Right-angled triangle with stars aligned to the right. *********
Downward Triangle Star Prints a downward triangle, starting with the largest *****
Pattern row.
Downward Mirrored Right Downward triangle with stars aligned to the right. **** *
Triangle
Hollow Right Triangle Star Right triangle with hollow spaces except for the **
Pattern edges.
Inverted Pyramid of Numbers Inverted pyramid of numbers, starting with the 55555 4444 333 22
largest number. 1
Half Pyramid of Numbers Half-pyramid of numbers from 1 up to the row 112123123412345
number.
These patterns help practice loops and logic control in C#, and you can easily adjust the number of rows ( n ) to get
different sizes of patterns.

Below are C# programs for the requested sorting algorithms and array manipulation operations, along with their
expected output.

44. Bubble Sort in C#


Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and
swaps them if they are in the wrong order.
Code:
using System; csharp

class Program
{
static void BubbleSort(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
// Swap
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

static void Main()


{
int[] arr = { 5, 1, 4, 2, 8 };
BubbleSort(arr);

Console.WriteLine("Sorted array:");
foreach (int num in arr)
{
Console.Write(num + " ");
}
}
}

Output:
Sorted array:
1 2 4 5 8

45. Merge Sort in C#


Merge sort is a divide and conquer algorithm. It divides the array into two halves, sorts each half, and then merges the
two sorted halves.
Code:
using System; csharp

class Program
{
static void MergeSort(int[] arr, int left, int right)
{
if (left < right)
{
int mid = left + (right - left) / 2;
MergeSort(arr, left, mid);
MergeSort(arr, mid + 1, right);
Merge(arr, left, mid, right);
}
}

static void Merge(int[] arr, int left, int mid, int right)
{
int n1 = mid - left + 1;
int n2 = right - mid;
int[] leftArray = new int[n1];
int[] rightArray = new int[n2];

Array.Copy(arr, left, leftArray, 0, n1);


Array.Copy(arr, mid + 1, rightArray, 0, n2);

int i = 0, j = 0, k = left;
while (i < n1 && j < n2)
{
if (leftArray[i] <= rightArray[j])
{
arr[k] = leftArray[i];
i++;
}
else
{
arr[k] = rightArray[j];
j++;
}
k++;
}

while (i < n1)


{
arr[k] = leftArray[i];
i++;
k++;
}

while (j < n2)


{
arr[k] = rightArray[j];
j++;
k++;
}
}

static void Main()


{
int[] arr = { 38, 27, 43, 3, 9, 82, 10 };
MergeSort(arr, 0, arr.Length - 1);

Console.WriteLine("Sorted array:");
foreach (int num in arr)
{
Console.Write(num + " ");
}
}
}

Output:
Sorted array:
3 9 10 27 38 43 82

46. Insertion Sort in C#


Insertion sort works by taking one element from the unsorted part and inserting it into the correct position of the
sorted part.
Code:
using System; csharp

class Program
{
static void InsertionSort(int[] arr)
{
for (int i = 1; i < arr.Length; i++)
{
int key = arr[i];
int j = i - 1;

while (j >= 0 && arr[j] > key)


{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

static void Main()


{
int[] arr = { 12, 11, 13, 5, 6 };
InsertionSort(arr);

Console.WriteLine("Sorted array:");
foreach (int num in arr)
{
Console.Write(num + " ");
}
}
}

Output:
Sorted array:
5 6 11 12 13

47. Left Rotation of Array by 1 in C#


This operation rotates the array to the left by one position, moving the first element to the end.
Code:
using System; csharp

class Program
{
static void LeftRotateByOne(int[] arr)
{
int temp = arr[0];
for (int i = 0; i < arr.Length - 1; i++)
{
arr[i] = arr[i + 1];
}
arr[arr.Length - 1] = temp;
}

static void Main()


{
int[] arr = { 1, 2, 3, 4, 5 };
LeftRotateByOne(arr);

Console.WriteLine("Array after left rotation by 1:");


foreach (int num in arr)
{
Console.Write(num + " ");
}
}
}

Output:
Array after left rotation by 1:
2 3 4 5 1

48. Right Rotation of Array by 1 in C#


This operation rotates the array to the right by one position, moving the last element to the front.
Code:
using System; csharp

class Program
{
static void RightRotateByOne(int[] arr)
{
int temp = arr[arr.Length - 1];
for (int i = arr.Length - 1; i > 0; i--)
{
arr[i] = arr[i - 1];
}
arr[0] = temp;
}
static void Main()
{
int[] arr = { 1, 2, 3, 4, 5 };
RightRotateByOne(arr);

Console.WriteLine("Array after right rotation by 1:");


foreach (int num in arr)
{
Console.Write(num + " ");
}
}
}

Output:
Array after right rotation by 1:
5 1 2 3 4

49. Rotate an Array by K Position using Popup and Unshifting Algorithm in C#


This algorithm rotates the array to the left by K positions using unshifting and moving the elements.
Code:
using System; csharp

class Program
{
static void RotateLeftByK(int[] arr, int k)
{
int n = arr.Length;
k = k % n;
int[] temp = new int[k];

for (int i = 0; i < k; i++)


temp[i] = arr[i];

for (int i = k; i < n; i++)


arr[i - k] = arr[i];

for (int i = 0; i < k; i++)


arr[n - k + i] = temp[i];
}

static void Main()


{
int[] arr = { 1, 2, 3, 4, 5 };
int k = 2;
RotateLeftByK(arr, k);

Console.WriteLine("Array after left rotation by " + k + " positions:");


foreach (int num in arr)
{
Console.Write(num + " ");
}
}
}

Output:
Array after left rotation by 2 positions:
3 4 5 1 2

50. Rotate an Array by K Position using Reversal Algorithm in C#


The reversal algorithm rotates the array in place by reversing sections of the array.
Code:
using System; csharp

class Program
{
static void Reverse(int[] arr, int start, int end)
{
while (start < end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}

static void RotateArrayByK(int[] arr, int k)


{
int n = arr.Length;
k = k % n; // In case the number of rotations is greater than array size
Reverse(arr, 0, k - 1);
Reverse(arr, k, n - 1);
Reverse(arr, 0, n - 1);
}

static void Main()


{
int[] arr = { 1, 2, 3, 4, 5 };
int k = 2;
RotateArrayByK(arr, k);

Console.WriteLine("Array after " + k + " rotations:");


foreach (int num in arr)
{
Console.Write(num + " ");
}
}
}

Output:
Array after 2 rotations:
3 4 5 1 2

51. How to Reverse an Array in C#


This program reverses an array in place.
Code:
using System; csharp

class Program

{ static void ReverseArray(int[] arr) { int start = 0, end = arr.Length - 1; while (start < end) { int temp = arr[start];
arr[start] = arr[end]; arr[end] = temp; start++; end--; } }
static void Main()
{
int[] arr = { 1, 2, 3, 4, 5 };
ReverseArray(arr);

Console.WriteLine("Reversed array:");
foreach (int num in arr)
{
Console.Write(num + " ");
}
}

}
#### **Output**:

Reversed array: 5 4 3 2 1

---

### Summary of Programs:

| **Program** | **Description**
| **Example Output** |
|-------------------------------------------|------------------------------------------
------------------------------|------------------------|
| **Bubble Sort** | Sorts the array by repeatedly swapping ad
jacent elements. | 1 2 4 5 8 |
| **Merge Sort** | Divides and merges the array in sorted or
der. | 3 9 10 27 38 43 82 |
| **Insertion Sort** | Sorts the array by inserting elements in
their correct position. | 5 6 11 12 13 |
| **Left Rotation by 1** | Rotates the array left by one position.
| 2 3 4 5 1 |
| **Right Rotation by 1** | Rotates the array right by one position.
| 5 1 2 3 4 |
| **Rotate by K Position (Unshifting)** | Rotates the array to the left by K positio
ns using unshifting. | 3 4 5 1 2 |
| **Rotate by K Position (Reversal)** | Rotates the array by K positions using th
e reversal algorithm. | 3 4 5 1 2 |
| **Reverse an Array** | Reverses the entire array.
| 5 4 3 2 1 |

These programs cover essential sorting and array manipulation techniques in C# and can
be extended to larger datasets as needed.

C# Coding Questions For Technical Interviews


Introduction
In this article, we will learn about some of the frequently asked C# programming questions in technical interviews.
Note: We won’t be using any inbuilt functions such as Reverse, Substring etc. for string manipulation, also we will
avoid using LINQ as these are generally restricted to be used in coding interviews.
Source Code
Download the source code for all the questions from GitHub
Q.1: How to reverse a string?
Ans.: The user will input a string and the method should return the reverse of that string
input: hello, output: olleh
input: hello world, output: dlrow olleh
internal static void ReverseString(string str)
{
char[] charArray = str.ToCharArray();
for (int i = 0, j = str.Length - 1; i < j; i++, j--)
{
charArray[i] = str[j];
charArray[j] = str[i];
}
string reversedstring = new string(charArray);
Console.WriteLine(reversedstring);
}
Q.2: How to find if the given string is a palindrome or not?
Ans.: The user will input a string and we need to print “Palindrome” or “Not Palindrome” based on whether the input
string is a palindrome or not.
input: madam, output: Palindrome
input: step on no pets, output: Palindrome
input: book, output: Not Palindrome
if we pass an integer as a string parameter then also this method will give the correct output
input: 1221, output: Palindrome
internal static void chkPalindrome(string str)
{
bool flag = false;
for (int i = 0, j = str.Length - 1; i < str.Length / 2; i++, j--)
{
if (str[i] != str[j])
{
flag = false;
break;
}
else
flag = true;
}
if (flag)
{
Console.WriteLine("Palindrome");
}
else
Console.WriteLine("Not Palindrome");
}
Q.3: How to reverse the order of words in a given string?
Ans.: The user will input a sentence and we need to reverse the sequence of words in the sentence.
input: Welcome to Csharp corner, output: corner Csharp to Welcome
internal static void ReverseWordOrder(string str)
{
int i;
StringBuilder reverseSentence = new StringBuilder();
int Start = str.Length - 1;
int End = str.Length - 1;
while (Start > 0)
{
if (str[Start] == ' ')
{
i = Start + 1;
while (i <= End)
{
reverseSentence.Append(str[i]);
i++;
}
reverseSentence.Append(' ');
End = Start - 1;
}
Start--;
}
for (i = 0; i <= End; i++)
{
reverseSentence.Append(str[i]);
}
Console.WriteLine(reverseSentence.ToString());
}
Q.4: How to reverse each word in a given string?
Ans.: The user will input a sentence and we need to reverse each word individually without changing its position in the
sentence.
input: Welcome to Csharp corner, output: emocleW ot prahsC renroc
internal static void ReverseWords(string str)
{
StringBuilder output = new StringBuilder();
List<char> charlist = new List<char>();
for (int i = 0; i < str.Length; i++)
{
if (str[i] ' ' || i str.Length - 1)
{
if (i == str.Length - 1)
charlist.Add(str[i]);
for (int j = charlist.Count - 1; j >= 0; j--)
output.Append(charlist[j]);
output.Append(' ');
charlist = new List<char>();
}
else
charlist.Add(str[i]);
}
Console.WriteLine(output.ToString());
}
Q.5: How to count the occurrence of each character in a string?
Ans.: The user will input a string and we need to find the count of each character of the string and display it on
console. We won’t be counting space character.
input: hello world;
output:
h–1
e–1
l–3
o–2
w–1
r–1
d–1
internal static void Countcharacter(string str)
{
Dictionary<char, int> characterCount = new Dictionary<char, int>();
foreach (var character in str)
{
if (character != ' ')
{
if (!characterCount.ContainsKey(character))
{
characterCount.Add(character, 1);
}
else
{
characterCount[character]++;
}
}
}
foreach (var character in characterCount)
{
Console.WriteLine("{0} - {1}", character.Key, character.Value);
}
}
Q.6: How to remove duplicate characters from a string?
Ans.: The user will input a string and the method should remove multiple occurrences of characters in the string
input: csharpcorner, output: csharpone
internal static void removeduplicate(string str)
{
string result = string.Empty;
for (int i = 0; i < str.Length; i++)
{
if (!result.Contains(str[i]))
{
result += str[i];
}
}
Console.WriteLine(result);
}
Q.7: How to find all possible substring of a given string?
Ans.: This is a very frequent interview question. Here we need to form all the possible substrings from input string,
varying from length 1 to the input string length. The output will include the input string also.
input: abcd , output : a ab abc abcd b bc bcd c cd d
internal static void findallsubstring(string str)
{
for (int i = 0; i < str.Length; ++i)
{
StringBuilder subString = new StringBuilder(str.Length - i);
for (int j = i; j < str.Length; ++j)
{
subString.Append(str[j]);
Console.Write(subString + " ");
}
}
}
Q.8: How to perform Left circular rotation of an array?
Ans.: The user will input an integer array and the method should shift each element of input array to its Left by one
position in circular fashion. The logic is to iterate loop from Length-1 to 0 and swap each element with last element.
input: 1 2 3 4 5, output: 2 3 4 5 1
internal static void RotateLeft(int[] array)
{
int size = array.Length;
int temp;
for (int j = size - 1; j > 0; j--)
{
temp = array[size - 1];
array[array.Length - 1] = array[j - 1];
array[j - 1] = temp;
}
foreach (int num in array)
{
Console.Write(num + " ");
}
}
Q.9: How to perform Right circular rotation of an array?
Ans: The user will input an integer array and the method should shift each element of input array to its Right by one
position in circular fashion. The logic is to iterate loop from 0 to Length-1 and swap each element with first element
input: 1 2 3 4 5, output: 5 1 2 3 4
internal static void RotateRight(int[] array)
{
int size = array.Length;
int temp;
for (int j = 0; j < size - 1; j++)
{
temp = array[0];
array[0] = array[j + 1];
array[j + 1] = temp;
}
foreach (int num in array)
{
Console.Write(num + " ");
}
}
Q.10: How to find if a positive integer is a prime number or not?
Ans.: The user will input a positive integer and the method should output “Prime” or “Not Prime” based on whether
the input integer is a prime number or not.
The logic is to find a positive integer less than or equal to the square root of input integer. If there is a divisor of
number that is less than the square root of number, then there will be a divisor of number that is greater than square
root of number. Hence, we have to traverse till the square root of number.
The time complexity of this function is O(√N) because we traverse from 1 to √N.
input: 20, output: Not Prime
input: 17, output: Prime
static void Main(string[] args)
{
if (FindPrime(47))
{
Console.WriteLine("Prime");
}
else
{
Console.WriteLine("Not Prime");
}
Console.ReadLine();
}
internal static bool FindPrime(int number)
{
if (number == 1) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
var squareRoot = (int)Math.Floor(Math.Sqrt(number));
for (int i = 3; i <= squareRoot; i += 2)
{
if (number % i == 0) return false;
}
return true;
}
Q.11: How to find the sum of digits of a positive integer?
Ans.: The user will input a positive integer and the method should return the sum of all the digits in that integer.
input: 168, output: 15
internal static void SumOfDigits(int num)
{
int sum = 0;
while (num > 0)
{
sum += num % 10;
num /= 10;
}
Console.WriteLine(sum);
}
Q.12: How to find second largest integer in an array using only one loop?
Ans.: The user will input an unsorted integer array and the method should find the second largest integer in the array.
input: 3 2 1 5 4, output: 4
internal static void FindSecondLargeInArray(int[] arr)
{
int max1 = int.MinValue;
int max2 = int.MinValue;
foreach (int i in arr)
{
if (i > max1)
{
max2 = max1;
max1 = i;
}
else if (i >= max2 && i != max1)
{
max2 = i;
}
}
Console.WriteLine(max2); ;
}
Q.13: How to find third largest integer in an array using only one loop?
Ans.: The user will input an unsorted integer array and the method should find the third largest integer in the array.
input: 3 2 1 5 4, output: 3
internal static void FindthirdLargeInArray(int[] arr)
{
int max1 = int.MinValue;
int max2 = int.MinValue;
int max3 = int.MinValue;
foreach (int i in arr)
{
if (i > max1)
{
max3 = max2;
max2 = max1;
max1 = i;
}
else if (i > max2 && i != max1)
{
max3 = max2;
max2 = i;
}
else if (i > max3 && i != max2 && i != max1)
{
max3 = i;
}
}
Console.WriteLine(max3); ;
}
Q.14: How to convert a two-dimensional array to a one-dimensional array?
Ans.: The user will input a 2-D array (matrix) and we need to convert it to a 1-D array. We will create a 1-D
array column-wise.
input: { { 1, 2, 3 }, { 4, 5, 6 } }, output: 1 4 2 5 3 6
internal static void MultiToSingle(int[,] array)
{
int index = 0;
int width = array.GetLength(0);
int height = array.GetLength(1);
int[] single = new int[width * height];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
single[index] = array[x, y];
Console.Write(single[index] + " ");
index++;
}
}
}
This question can also be asked to form a 1-D array row-wise. In this case, just swap the sequence of the for loops as
shown below. The output will be 1 2 3 4 5 6 for the input matrix mentioned above.
for (int x = 0; x < width; x++ )
{
for ( int y = 0; y < height; y++)
{
single[index] = array[x, y];
Console.Write(single[index] + " ");
index++;
}
}
Q.15: How to convert a one-dimensional array to a two-dimensional array?
Ans.: The user will input a 1-D array along with the number of rows and columns. The method should convert this 1-D
array to a 2-D array(matrix) of a given row and column. We will create a matrix row-wise.
input: {1, 2, 3, 4, 5, 6} ,2 ,3
output:
123
456
internal static void SingleToMulti(int[] array, int row, int column)
{
int index = 0;
int[,] multi = new int[row, column];
for (int y = 0; y < row; y++)
{
for (int x = 0; x < column; x++)
{
multi[y, x] = array[index];
index++;
Console.Write(multi[y, x] + " ");
}
Console.WriteLine();
}
}
Q.16: How to find the angle between hour and minute hands of a clock at any given time?
Ans.: The user will input the hour and minute of the time and the method should give the angle between the hour
hand and minute hand at that given time.
input: 9 30, output: The angle between hour hand and minute hand is 105 degrees
input: 13 30, output: The angle between hour hand and minute hand is 135 degrees
The logic 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.
So, our code will be as follows:
internal static void FindAngleinTime(int hours, int mins)
{
double hourDegrees = (hours 30) + (mins 30.0 / 60);
double minuteDegrees = mins * 6;
double diff = Math.Abs(hourDegrees - minuteDegrees);
if (diff > 180)
{
diff = 360 - diff;
}
Console.WriteLine("The angle between hour hand and minute hand is {0} degrees", diff);
}
Q.17: Explain Bubble Sort Algorithm In C#
This algorithm follows the concept of iterating through the array from the first index to the last index and comparing
adjacent elements and then swapping them if they appear in the wrong order. i.e. If the next element is smaller than
the current element, they are swapped.
The Time Complexity of bubble sort is O(n²).
Read Bubble Sort Algorithm In C# to learn more.
Q.18: Explain Quick Sort Algorithm In C#
This Algorithm selects an element as a pivot element from the given array and partitions the array around it such that,
Left side of the pivot contains all the elements that are less than the pivot element. The right side contains all
elements that are greater than the pivot element. Let P be the index of pivot after partitioning the array. Then, the left
subarray(start to P-1) and right subarray(P+1 to end) are sorted recursively to get the final sorted array as output.
The worst-case time complexity of this algorithm is O(N²). The best-case and average-case time complexity of this
algorithm is O(NLogN).
Read Quick Sort Algorithm In C# to learn more.
Q.19: Explain Merge Sort Algorithm In C#
This algorithm works as follows.
Divide the unsorted array of size N into N subarrays having single element each.
Take two adjacent subarrays and merge them to form a sorted subarray having 2 elements.Now we have N/2
subarrays of size 2.
Repeat the process until a single sorted array is obtained.
In all three cases (worst, average, best), the time complexity of Merge sort is O(NLogN)
Read Merge Sort Algorithm In C# to learn more.
Q. 20: Explain Insertion Sort Algorithm In C#
Insertion sort compares the current element with the largest value in the sorted array. If the current element is smaller
then the algorithm finds its correct position in a sorted array and moves the element to that position otherwise if the
current element is greater then it leaves the element in its place and moves on to the next element.
To place the element in its correct position in a sorted array, all the elements larger than the current element are
shifted one place ahead. Thus the sorted array will grow at each iteration.
Every element is compared to every other element of a sorted array. Hence the complexity of Insertion sort is O(n²).
Read Insertion Sort Algorithm In C# to learn more.
Q. 21: Explain Selection Sort Algorithm In C#
This algorithm follows the concept of dividing the given array into two subarrays.
1. The subarray of sorted elements
2. The subarray of unsorted elements
The algorithm will find the minimum element in the unsorted subarray and put it into its correct position in the sorted
subarray.
Read Selection Sort Algorithm In C# to learn more.
The time complexity of Selection Sort as O(n²).
Q. 22: Explain Binary Search In C#
Binary search is an efficient and commonly used searching algorithm. This algorithm works only on sorted sets of
elements. So if the given array is not sorted then we need to sort it before applying Binary search.
This algorithm searches a sorted array by repeatedly dividing the search interval in half. Begin with an interval
covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the
interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval
is empty. If found return the index of matched element, else return -1.
Read Searching Algorithms In C# to learn more.
The array to be searched is reduced by half in every iteration. Hence time complexity of the Binary search is O(LogN).

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy