CSharp Coding Practice 1

CSharp Coding Practice 1


1. Fibonacci Sequence (Beginner)

Write a C# program that generates the Fibonacci sequence up to a given number of terms. This is a good exercise to understand loops and recursion.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter the number of terms: ");

        int n = int.Parse(Console.ReadLine());

        int a = 0, b = 1, c;

 

        Console.WriteLine("Fibonacci Sequence:");

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

        {

            Console.Write(a + " ");

            c = a + b;

            a = b;

            b = c;

        }

    }

}

2. Palindrome Checker (Intermediate)

Write a program to check if a given string is a palindrome (reads the same forward and backward). This is a great way to practice string manipulation.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string str = Console.ReadLine();

        string reversed = string.Join("", str.Reverse());

       

        if (str.Equals(reversed, StringComparison.OrdinalIgnoreCase))

        {

            Console.WriteLine("The string is a palindrome.");

        }

        else

        {

            Console.WriteLine("The string is not a palindrome.");

        }

    }

}

3. Sum of Digits (Beginner/Intermediate)

Write a program to calculate the sum of the digits of a given number. This is useful for practicing loops and mathematical operations.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a number: ");

        int num = int.Parse(Console.ReadLine());

        int sum = 0;

 

        while (num > 0)

        {

            sum += num % 10;

            num /= 10;

        }

 

        Console.WriteLine("Sum of digits: " + sum);

    }

}

4. Prime Number Checker (Intermediate)

Write a program to check if a number is prime. This will help you practice loops and conditions.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a number: ");

        int num = int.Parse(Console.ReadLine());

        bool isPrime = true;

 

        if (num <= 1) isPrime = false;

 

        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.");

    }

}

5. Sorting Algorithm (Intermediate/Advanced)

Implement the Bubble Sort or any other sorting algorithm in C# to practice arrays and algorithms.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { 5, 2, 9, 1, 5, 6 };

 

        Console.WriteLine("Original Array:");

        foreach (int num in arr)

            Console.Write(num + " ");

       

        BubbleSort(arr);

 

        Console.WriteLine("\nSorted Array:");

        foreach (int num in arr)

            Console.Write(num + " ");

    }

 

    static void BubbleSort(int[] arr)

    {

        int n = arr.Length;

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

        {

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

            {

                if (arr[j] > arr[j + 1])

                {

                    // Swap elements

                    int temp = arr[j];

                    arr[j] = arr[j + 1];

                    arr[j + 1] = temp;

                }

            }

        }

    }

}

6. Find Maximum Subarray Sum (Advanced)

Write a program to find the maximum sum of a contiguous subarray in an array of integers. This will help you practice more complex algorithms.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };

        int maxSum = MaximumSubarraySum(arr);

        Console.WriteLine("Maximum Subarray Sum: " + maxSum);

    }

 

    static int MaximumSubarraySum(int[] arr)

    {

        int maxSum = arr[0];

        int currentSum = arr[0];

 

        for (int i = 1; i < arr.Length; i++)

        {

            currentSum = Math.Max(arr[i], currentSum + arr[i]);

            maxSum = Math.Max(maxSum, currentSum);

        }

 

        return maxSum;

    }

}

7. To-Do List Application (Advanced)

Create a simple console-based to-do list application where you can add, view, and delete tasks. This will help you practice data storage and managing state.

using System;

using System.Collections.Generic;

 

class Program

{

    static List<string> tasks = new List<string>();

 

    static void Main()

    {

        while (true)

        {

            Console.WriteLine("\n1. Add Task\n2. View Tasks\n3. Delete Task\n4. Exit");

            Console.Write("Choose an option: ");

            int choice = int.Parse(Console.ReadLine());

 

            switch (choice)

            {

                case 1:

                    AddTask();

                    break;

                case 2:

                    ViewTasks();

                    break;

                case 3:

                    DeleteTask();

                    break;

                case 4:

                    return;

                default:

                    Console.WriteLine("Invalid choice.");

                    break;

            }

        }

    }

 

    static void AddTask()

    {

        Console.Write("Enter the task: ");

        string task = Console.ReadLine();

        tasks.Add(task);

    }

 

    static void ViewTasks()

    {

        Console.WriteLine("\nYour Tasks:");

        for (int i = 0; i < tasks.Count; i++)

        {

            Console.WriteLine($"{i + 1}. {tasks[i]}");

        }

    }

 

    static void DeleteTask()

    {

        ViewTasks();

        Console.Write("Enter the task number to delete: ");

        int index = int.Parse(Console.ReadLine()) - 1;

       

        if (index >= 0 && index < tasks.Count)

        {

            tasks.RemoveAt(index);

            Console.WriteLine("Task deleted.");

        }

        else

        {

            Console.WriteLine("Invalid task number.");

        }

    }

}

 

8. Tic-Tac-Toe Game (Advanced)

Build a simple text-based Tic-Tac-Toe game to practice handling user input, displaying a board, and implementing game logic.

9. File Handling (Advanced)

Write a program that reads from and writes to a text file. This is useful for understanding I/O operations.

using System;

using System.IO;

 

class Program

{

    static void Main()

    {

        string filePath = "example.txt";

 

        // Write to file

        File.WriteAllText(filePath, "Hello, this is a test file.");

 

        // Read from file

        string content = File.ReadAllText(filePath);

        Console.WriteLine("File Content: " + content);

    }

}

 

 

10. Anagram Checker (Intermediate)

Write a program to check if two given strings are anagrams of each other. Anagrams are words or phrases formed by rearranging the letters of another, using all the original letters exactly once.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter the first string: ");

        string str1 = Console.ReadLine();

        Console.Write("Enter the second string: ");

        string str2 = Console.ReadLine();

 

        bool isAnagram = AreAnagrams(str1, str2);

 

        if (isAnagram)

            Console.WriteLine("The strings are anagrams.");

        else

            Console.WriteLine("The strings are not anagrams.");

    }

 

    static bool AreAnagrams(string str1, string str2)

    {

        var arr1 = str1.ToLower().Replace(" ", "").ToCharArray();

        var arr2 = str2.ToLower().Replace(" ", "").ToCharArray();

 

        Array.Sort(arr1);

        Array.Sort(arr2);

 

        return new string(arr1) == new string(arr2);

    }

}

11. Vowel Counter (Beginner)

Write a C# program to count the number of vowels (a, e, i, o, u) in a given string. This will help you practice string manipulation and conditional checks.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string str = Console.ReadLine().ToLower();

 

        int vowelCount = 0;

        foreach (char c in str)

        {

            if ("aeiou".Contains(c))

            {

                vowelCount++;

            }

        }

 

        Console.WriteLine("Number of vowels: " + vowelCount);

    }

}

12. Factorial Calculator (Beginner/Intermediate)

Write a program to compute the factorial of a number. This helps practice loops and recursion.

Iterative Method

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a number: ");

        int num = int.Parse(Console.ReadLine());

        long factorial = 1;

 

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

        {

            factorial *= i;

        }

 

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

    }

}

Recursive Method

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a number: ");

        int num = int.Parse(Console.ReadLine());

 

        long result = Factorial(num);

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

    }

 

    static long Factorial(int n)

    {

        if (n == 0)

            return 1;

        return n * Factorial(n - 1);

    }

}

13. Reverse a String (Beginner/Intermediate)

Write a program to reverse a given string without using built-in reverse methods. This exercise helps with string manipulation.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string input = Console.ReadLine();

        char[] charArray = input.ToCharArray();

        Array.Reverse(charArray);

        string reversedString = new string(charArray);

       

        Console.WriteLine("Reversed string: " + reversedString);

    }

}

14. Number Guessing Game (Intermediate)

Create a simple number guessing game where the computer randomly picks a number, and the user has to guess it. This helps with logic, user input, and loops.

using System;

 

class Program

{

    static void Main()

    {

        Random rand = new Random();

        int secretNumber = rand.Next(1, 101);

        int guess = 0;

        int attempts = 0;

 

        Console.WriteLine("Welcome to the Number Guessing Game!");

        Console.WriteLine("I have selected a number between 1 and 100. Try to guess it.");

 

        while (guess != secretNumber)

        {

            Console.Write("Enter your guess: ");

            guess = int.Parse(Console.ReadLine());

            attempts++;

 

            if (guess < secretNumber)

                Console.WriteLine("Too low! Try again.");

            else if (guess > secretNumber)

                Console.WriteLine("Too high! Try again.");

            else

                Console.WriteLine($"Correct! You've guessed the number in {attempts} attempts.");

        }

    }

}

15. Matrix Multiplication (Advanced)

Write a program to multiply two matrices. This will help you understand multidimensional arrays and the logic behind matrix operations.

using System;

 

class Program

{

    static void Main()

    {

        int[,] matrix1 = { { 1, 2 }, { 3, 4 } };

        int[,] matrix2 = { { 5, 6 }, { 7, 8 } };

 

        int rows1 = matrix1.GetLength(0);

        int cols1 = matrix1.GetLength(1);

        int rows2 = matrix2.GetLength(0);

        int cols2 = matrix2.GetLength(1);

 

        if (cols1 != rows2)

        {

            Console.WriteLine("Matrix multiplication is not possible.");

            return;

        }

 

        int[,] result = new int[rows1, cols2];

 

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

        {

            for (int j = 0; j < cols2; j++)

            {

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

                {

                    result[i, j] += matrix1[i, k] * matrix2[k, j];

                }

            }

        }

 

        Console.WriteLine("Result of Matrix Multiplication:");

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

        {

            for (int j = 0; j < cols2; j++)

            {

                Console.Write(result[i, j] + "\t");

            }

            Console.WriteLine();

        }

    }

}

16. Simple Calculator (Intermediate)

Create a simple calculator that can perform addition, subtraction, multiplication, and division. This is a good practice for handling user input, conditions, and basic arithmetic operations.

using System;

 

class Program

{

    static void Main()

    {

        Console.WriteLine("Simple Calculator");

        Console.Write("Enter the first number: ");

        double num1 = double.Parse(Console.ReadLine());

 

        Console.Write("Enter the operator (+, -, *, /): ");

        char op = Console.ReadLine()[0];

 

        Console.Write("Enter the second number: ");

        double num2 = double.Parse(Console.ReadLine());

 

        double result = 0;

 

        switch (op)

        {

            case '+':

                result = num1 + num2;

                break;

            case '-':

                result = num1 - num2;

                break;

            case '*':

                result = num1 * num2;

                break;

            case '/':

                if (num2 != 0)

                    result = num1 / num2;

                else

                    Console.WriteLine("Error: Division by zero.");

                break;

            default:

                Console.WriteLine("Invalid operator.");

                break;

        }

 

        Console.WriteLine("Result: " + result);

    }

}

17. Find the Missing Number (Intermediate)

Given an array of integers from 1 to N, one number is missing. Write a program to find the missing number.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { 1, 2, 4, 5, 6 }; // Missing 3

 

        int n = arr.Length + 1;

        int sumOfN = n * (n + 1) / 2;

        int sumOfArray = 0;

 

        foreach (int num in arr)

        {

            sumOfArray += num;

        }

 

        int missingNumber = sumOfN - sumOfArray;

        Console.WriteLine("The missing number is: " + missingNumber);

    }

}

18. Currency Converter (Intermediate)

Write a program to convert between different currencies. This could simulate the conversion between dollars, euros, and pounds.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter the amount in USD: ");

        double usd = double.Parse(Console.ReadLine());

 

        Console.Write("Enter the target currency (EUR/GBP): ");

        string currency = Console.ReadLine().ToUpper();

 

        double conversionRate = 0;

        if (currency == "EUR")

            conversionRate = 0.91; // Example conversion rate

        else if (currency == "GBP")

            conversionRate = 0.75; // Example conversion rate

        else

        {

            Console.WriteLine("Invalid currency.");

            return;

        }

 

        double convertedAmount = usd * conversionRate;

        Console.WriteLine($"Converted amount: {convertedAmount} {currency}");

    }

}

19. Command-Line Todo List with File Storage (Advanced)

Write a command-line to-do list application where the user can add tasks, remove tasks, and save/load tasks from a file.

This would involve:

  • Using File I/O to store tasks in a file.
  • Creating a simple menu system for managing tasks.

 

 

20. Reverse Words in a Sentence (Intermediate)

Write a program that reverses the words in a given sentence. For example, "Hello World" becomes "World Hello".

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a sentence: ");

        string sentence = Console.ReadLine();

       

        string[] words = sentence.Split(' ');

        Array.Reverse(words);

 

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

        Console.WriteLine("Reversed sentence: " + reversedSentence);

    }

}

21. Count Occurrences of a Character (Beginner)

Write a program to count how many times a specific character appears in a given string.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string input = Console.ReadLine();

        Console.Write("Enter the character to count: ");

        char character = Console.ReadLine()[0];

 

        int count = 0;

        foreach (char c in input)

        {

            if (c == character)

                count++;

        }

 

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

    }

}

22. Find Duplicate Elements in an Array (Intermediate)

Write a program that finds and prints duplicate elements in an array.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        int[] arr = { 1, 2, 3, 4, 5, 6, 2, 7, 8, 3, 9 };

        var seen = new HashSet<int>();

        var duplicates = new HashSet<int>();

 

        foreach (var num in arr)

        {

            if (!seen.Add(num))

                duplicates.Add(num);

        }

 

        Console.WriteLine("Duplicates: " + string.Join(", ", duplicates));

    }

}

23. Find the Largest and Smallest Numbers in an Array (Beginner/Intermediate)

Write a program that finds the largest and smallest number in an array.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { 10, 20, 4, 45, 99, 2, 3 };

 

        int max = arr[0];

        int min = arr[0];

 

        foreach (var num in arr)

        {

            if (num > max)

                max = num;

            if (num < min)

                min = num;

        }

 

        Console.WriteLine($"Largest number: {max}");

        Console.WriteLine($"Smallest number: {min}");

    }

}

24. FizzBuzz (Beginner)

Write a program that prints numbers from 1 to 100, but for multiples of 3, print "Fizz", and for multiples of 5, print "Buzz". For numbers which are multiples of both 3 and 5, print "FizzBuzz".

using System;

 

class Program

{

    static void Main()

    {

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

        {

            if (i % 3 == 0 && i % 5 == 0)

                Console.WriteLine("FizzBuzz");

            else if (i % 3 == 0)

                Console.WriteLine("Fizz");

            else if (i % 5 == 0)

                Console.WriteLine("Buzz");

            else

                Console.WriteLine(i);

        }

    }

}

25. Student Grade Calculator (Intermediate)

Write a program to calculate and display the grade of a student based on their marks. The grading scale can be like:

  • 90 and above: A
  • 80-89: B
  • 70-79: C
  • 60-69: D
  • Below 60: F

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter the marks (0-100): ");

        int marks = int.Parse(Console.ReadLine());

 

        char grade;

        if (marks >= 90)

            grade = 'A';

        else if (marks >= 80)

            grade = 'B';

        else if (marks >= 70)

            grade = 'C';

        else if (marks >= 60)

            grade = 'D';

        else

            grade = 'F';

 

        Console.WriteLine($"The grade is: {grade}");

    }

}

26. Implement a Basic Queue (Intermediate)

Create a simple queue data structure (FIFO: First In, First Out) using an array or a List in C#.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        Queue<int> queue = new Queue<int>();

 

        // Enqueue elements

        queue.Enqueue(10);

        queue.Enqueue(20);

        queue.Enqueue(30);

 

        Console.WriteLine("Dequeuing elements:");

       

        // Dequeue elements

        while (queue.Count > 0)

        {

            Console.WriteLine(queue.Dequeue());

        }

    }

}

27. Temperature Converter (Beginner/Intermediate)

Write a program to convert temperatures between Celsius, Fahrenheit, and Kelvin.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter temperature: ");

        double temperature = double.Parse(Console.ReadLine());

 

        Console.Write("Enter the scale (C/F/K): ");

        char scale = Console.ReadLine().ToUpper()[0];

 

        if (scale == 'C')

        {

            Console.WriteLine($"{temperature}°C = {CelsiusToFahrenheit(temperature)}°F");

            Console.WriteLine($"{temperature}°C = {CelsiusToKelvin(temperature)}K");

        }

        else if (scale == 'F')

        {

            Console.WriteLine($"{temperature}°F = {FahrenheitToCelsius(temperature)}°C");

            Console.WriteLine($"{temperature}°F = {FahrenheitToKelvin(temperature)}K");

        }

        else if (scale == 'K')

        {

            Console.WriteLine($"{temperature}K = {KelvinToCelsius(temperature)}°C");

            Console.WriteLine($"{temperature}K = {KelvinToFahrenheit(temperature)}°F");

        }

        else

        {

            Console.WriteLine("Invalid scale.");

        }

    }

 

    static double CelsiusToFahrenheit(double celsius) => (celsius * 9 / 5) + 32;

    static double CelsiusToKelvin(double celsius) => celsius + 273.15;

    static double FahrenheitToCelsius(double fahrenheit) => (fahrenheit - 32) * 5 / 9;

    static double FahrenheitToKelvin(double fahrenheit) => (fahrenheit - 32) * 5 / 9 + 273.15;

    static double KelvinToCelsius(double kelvin) => kelvin - 273.15;

    static double KelvinToFahrenheit(double kelvin) => (kelvin - 273.15) * 9 / 5 + 32;

}

28. Towers of Hanoi (Advanced)

Write a program to solve the Towers of Hanoi problem using recursion. This is a classic problem that involves moving disks between pegs according to specific rules.

using System;

 

class Program

{

    static void Main()

    {

        int n = 3;  // Number of disks

        SolveHanoi(n, 'A', 'C', 'B');

    }

 

    static void SolveHanoi(int n, char source, char target, char auxiliary)

    {

        if (n == 1)

        {

            Console.WriteLine($"Move disk 1 from {source} to {target}");

            return;

        }

 

        SolveHanoi(n - 1, source, auxiliary, target);

        Console.WriteLine($"Move disk {n} from {source} to {target}");

        SolveHanoi(n - 1, auxiliary, target, source);

    }

}

29. Caesar Cipher (Intermediate/Advanced)

Write a program to implement a Caesar Cipher for encryption and decryption. The Caesar Cipher is a simple substitution cipher where each letter is shifted by a certain number.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a message to encrypt: ");

        string message = Console.ReadLine();

        Console.Write("Enter shift value: ");

        int shift = int.Parse(Console.ReadLine());

 

        string encrypted = CaesarCipher(message, shift);

        Console.WriteLine("Encrypted message: " + encrypted);

 

        string decrypted = CaesarCipher(encrypted, -shift);

        Console.WriteLine("Decrypted message: " + decrypted);

    }

 

    static string CaesarCipher(string input, int shift)

    {

        char[] result = new char[input.Length];

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

        {

            char c = input[i];

            if (char.IsLetter(c))

            {

                char offset = char.IsUpper(c) ? 'A' : 'a';

                result[i] = (char)((c + shift - offset + 26) % 26 + offset);

            }

            else

            {

                result[i] = c;

            }

        }

        return new string(result);

    }

}

30. Find Prime Numbers up to N (Intermediate)

Write a program to find and display all prime numbers up to a given number N using the Sieve of Eratosthenes algorithm.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter the number N: ");

        int N = int.Parse(Console.ReadLine());

 

        bool[] isPrime = new bool[N + 1];

        for (int i = 2; i <= N; i++)

        {

            isPrime[i] = true;

        }

 

        for (int i = 2; i * i <= N; i++)

        {

            if (isPrime[i])

            {

                for (int j = i * i; j <= N; j += i)

                {

                    isPrime[j] = false;

                }

            }

        }

 

        Console.WriteLine("Prime numbers up to " + N + ":");

        for (int i = 2; i <= N; i++)

        {

            if (isPrime[i])

                Console.Write(i + " ");

        }

    }

}

 

 

31. Sum of Digits in a Number (Beginner)

Write a program that calculates the sum of the digits of a given number.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a number: ");

        int num = int.Parse(Console.ReadLine());

 

        int sum = 0;

        while (num > 0)

        {

            sum += num % 10;

            num /= 10;

        }

 

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

    }

}

32. Palindrome Check for Numbers (Beginner)

Write a program that checks if a given number is a palindrome. A number is a palindrome if it reads the same backward as forward.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a number: ");

        int num = int.Parse(Console.ReadLine());

 

        int original = num;

        int reversed = 0;

 

        while (num > 0)

        {

            reversed = reversed * 10 + num % 10;

            num /= 10;

        }

 

        if (original == reversed)

            Console.WriteLine("The number is a palindrome.");

        else

            Console.WriteLine("The number is not a palindrome.");

    }

}

33. Create a Simple Bank Account (Intermediate)

Write a simple program that simulates a bank account with basic functionality like deposit, withdraw, and check balance.

using System;

 

class BankAccount

{

    public double Balance { get; private set; }

 

    public BankAccount(double initialBalance)

    {

        Balance = initialBalance;

    }

 

    public void Deposit(double amount)

    {

        Balance += amount;

        Console.WriteLine($"Deposited {amount}. New balance: {Balance}");

    }

 

    public void Withdraw(double amount)

    {

        if (amount > Balance)

            Console.WriteLine("Insufficient funds.");

        else

        {

            Balance -= amount;

            Console.WriteLine($"Withdrew {amount}. New balance: {Balance}");

        }

    }

 

    public void DisplayBalance()

    {

        Console.WriteLine($"Current balance: {Balance}");

    }

}

 

class Program

{

    static void Main()

    {

        var account = new BankAccount(1000);

       

        while (true)

        {

            Console.WriteLine("\n1. Deposit\n2. Withdraw\n3. Check Balance\n4. Exit");

            Console.Write("Choose an option: ");

            int choice = int.Parse(Console.ReadLine());

 

            switch (choice)

            {

                case 1:

                    Console.Write("Enter deposit amount: ");

                    double depositAmount = double.Parse(Console.ReadLine());

                    account.Deposit(depositAmount);

                    break;

 

                case 2:

                    Console.Write("Enter withdrawal amount: ");

                    double withdrawAmount = double.Parse(Console.ReadLine());

                    account.Withdraw(withdrawAmount);

                    break;

 

                case 3:

                    account.DisplayBalance();

                    break;

 

                case 4:

                    return;

 

                default:

                    Console.WriteLine("Invalid option.");

                    break;

            }

        }

    }

}

34. Find Missing Number in an Array (Advanced)

Given an array with N-1 numbers in the range from 1 to N, find the missing number.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { 1, 2, 4, 5, 6 }; // Missing 3

 

        int n = arr.Length + 1;

        int totalSum = (n * (n + 1)) / 2;

        int arraySum = 0;

 

        foreach (int num in arr)

        {

            arraySum += num;

        }

 

        int missingNumber = totalSum - arraySum;

        Console.WriteLine("Missing number: " + missingNumber);

    }

}

35. Bubble Sort Implementation (Intermediate)

Write a program to implement the bubble sort algorithm to sort an array in ascending order.

using System;

 

class Program

{

    static void Main()

    {

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

        Console.WriteLine("Original array: " + string.Join(", ", arr));

 

        BubbleSort(arr);

 

        Console.WriteLine("Sorted array: " + string.Join(", ", arr));

    }

 

    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])

                {

                    int temp = arr[j];

                    arr[j] = arr[j + 1];

                    arr[j + 1] = temp;

                }

            }

        }

    }

}

36. Binary Search Algorithm (Advanced)

Write a program to perform a binary search on a sorted array.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { 1, 3, 5, 7, 9, 11, 13, 15 };

        Console.Write("Enter the number to search for: ");

        int target = int.Parse(Console.ReadLine());

 

        int result = BinarySearch(arr, target);

 

        if (result != -1)

            Console.WriteLine($"Element found at index {result}");

        else

            Console.WriteLine("Element not found.");

    }

 

    static int BinarySearch(int[] arr, int target)

    {

        int left = 0;

        int right = arr.Length - 1;

 

        while (left <= right)

        {

            int mid = left + (right - left) / 2;

 

            if (arr[mid] == target)

                return mid;

 

            if (arr[mid] < target)

                left = mid + 1;

            else

                right = mid - 1;

        }

 

        return -1; // Element not found

    }

}

37. Generate Fibonacci Sequence (Beginner/Intermediate)

Write a program to generate the Fibonacci sequence up to a given number of terms.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter the number of terms: ");

        int terms = int.Parse(Console.ReadLine());

 

        int a = 0, b = 1;

        Console.WriteLine("Fibonacci Sequence:");

 

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

        {

            Console.Write(a + " ");

            int next = a + b;

            a = b;

            b = next;

        }

    }

}

38. Calculate Power of a Number (Intermediate)

Write a program to calculate the power of a number (base raised to the exponent).

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter base: ");

        int baseNum = int.Parse(Console.ReadLine());

 

        Console.Write("Enter exponent: ");

        int exponent = int.Parse(Console.ReadLine());

 

        int result = Power(baseNum, exponent);

 

        Console.WriteLine($"{baseNum} raised to the power of {exponent} is: {result}");

    }

 

    static int Power(int baseNum, int exponent)

    {

        int result = 1;

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

        {

            result *= baseNum;

        }

        return result;

    }

}

39. Find GCD (Greatest Common Divisor) (Intermediate)

Write a program to find the GCD of two numbers using the Euclidean algorithm.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter the first number: ");

        int a = int.Parse(Console.ReadLine());

 

        Console.Write("Enter the second number: ");

        int b = int.Parse(Console.ReadLine());

 

        int gcd = FindGCD(a, b);

 

        Console.WriteLine($"The GCD of {a} and {b} is {gcd}");

    }

 

    static int FindGCD(int a, int b)

    {

        while (b != 0)

        {

            int temp = b;

            b = a % b;

            a = temp;

        }

        return a;

    }

}

40. Counting Words in a Sentence (Beginner)

Write a program to count the number of words in a given sentence.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a sentence: ");

        string sentence = Console.ReadLine();

 

        int wordCount = CountWords(sentence);

        Console.WriteLine($"The sentence contains {wordCount} words.");

    }

 

    static int CountWords(string sentence)

    {

        string[] words = sentence.Split(' ', StringSplitOptions.RemoveEmptyEntries);

        return words.Length;

    }

}

41. Create a Simple To-Do List Application (Intermediate)

Write a simple to-do list application where the user can add, view, and remove tasks. Store the tasks in a List.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        List<string> tasks = new List<string>();

 

        while (true)

        {

            Console.WriteLine("\n1. Add Task\n2. View Tasks\n3. Remove Task\n4. Exit");

            Console.Write("Choose an option: ");

            int choice = int.Parse(Console.ReadLine());

 

            switch (choice)

            {

                case 1:

                    Console.Write("Enter the task: ");

                    string task = Console.ReadLine();

                    tasks.Add(task);

                    Console.WriteLine("Task added.");

                    break;

 

                case 2:

                    Console.WriteLine("Tasks:");

                    foreach (var t in tasks)

                    {

                        Console.WriteLine(t);

                    }

                    break;

 

                case 3:

                    Console.Write("Enter the task to remove: ");

                    string taskToRemove = Console.ReadLine();

                    if (tasks.Remove(taskToRemove))

                        Console.WriteLine("Task removed.");

                    else

                        Console.WriteLine("Task not found.");

                    break;

 

                case 4:

                    return;

 

                default:

                    Console.WriteLine("Invalid option.");

                    break;

            }

        }

    }

}

 

42. Merge Two Sorted Arrays (Intermediate)

Write a program that merges two sorted arrays into a single sorted array.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr1 = { 1, 3, 5, 7 };

        int[] arr2 = { 2, 4, 6, 8 };

 

        int[] merged = MergeSortedArrays(arr1, arr2);

 

        Console.WriteLine("Merged sorted array: " + string.Join(", ", merged));

    }

 

    static int[] MergeSortedArrays(int[] arr1, int[] arr2)

    {

        int[] result = new int[arr1.Length + arr2.Length];

        int i = 0, j = 0, k = 0;

 

        while (i < arr1.Length && j < arr2.Length)

        {

            if (arr1[i] < arr2[j])

                result[k++] = arr1[i++];

            else

                result[k++] = arr2[j++];

        }

 

        while (i < arr1.Length)

            result[k++] = arr1[i++];

 

        while (j < arr2.Length)

            result[k++] = arr2[j++];

 

        return result;

    }

}

43. Find the Second Largest Number in an Array (Intermediate)

Write a program that finds the second largest number in an array.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { 10, 20, 4, 45, 99, 2 };

 

        int largest = arr[0];

        int secondLargest = int.MinValue;

 

        foreach (int num in arr)

        {

            if (num > largest)

            {

                secondLargest = largest;

                largest = num;

            }

            else if (num > secondLargest && num != largest)

            {

                secondLargest = num;

            }

        }

 

        Console.WriteLine($"Second largest number is: {secondLargest}");

    }

}

44. Check if Two Strings Are Anagrams (Intermediate)

Write a program to check if two strings are anagrams (contain the same characters in different orders).

using System;

using System.Linq;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter the first string: ");

        string str1 = Console.ReadLine();

 

        Console.Write("Enter the second string: ");

        string str2 = Console.ReadLine();

 

        bool areAnagrams = AreAnagrams(str1, str2);

        if (areAnagrams)

            Console.WriteLine("The strings are anagrams.");

        else

            Console.WriteLine("The strings are not anagrams.");

    }

 

    static bool AreAnagrams(string str1, string str2)

    {

        return str1.Length == str2.Length && str1.OrderBy(c => c).SequenceEqual(str2.OrderBy(c => c));

    }

}

45. Remove Duplicates from an Array (Beginner)

Write a program to remove duplicates from an array.

using System;

using System.Linq;

 

class Program

{

    static void Main()

    {

        int[] arr = { 1, 2, 2, 3, 4, 5, 5, 6 };

 

        int[] uniqueArr = arr.Distinct().ToArray();

        Console.WriteLine("Array without duplicates: " + string.Join(", ", uniqueArr));

    }

}

46. Find Factorial of a Number (Beginner)

Write a program to find the factorial of a number using both iterative and recursive methods.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a number: ");

        int num = int.Parse(Console.ReadLine());

 

        Console.WriteLine($"Factorial (Iterative): {FactorialIterative(num)}");

        Console.WriteLine($"Factorial (Recursive): {FactorialRecursive(num)}");

    }

 

    static int FactorialIterative(int n)

    {

        int result = 1;

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

        {

            result *= i;

        }

        return result;

    }

 

    static int FactorialRecursive(int n)

    {

        if (n == 0)

            return 1;

        return n * FactorialRecursive(n - 1);

    }

}

47. Check if a Number is Prime (Beginner/Intermediate)

Write a program to check if a number is prime.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a number: ");

        int num = int.Parse(Console.ReadLine());

 

        bool isPrime = IsPrime(num);

 

        if (isPrime)

            Console.WriteLine($"{num} is a prime number.");

        else

            Console.WriteLine($"{num} is not a prime number.");

    }

 

    static bool IsPrime(int n)

    {

        if (n <= 1) return false;

 

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

        {

            if (n % i == 0)

                return false;

        }

        return true;

    }

}

48. Count Vowels and Consonants in a String (Beginner)

Write a program to count the number of vowels and consonants in a string.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string input = Console.ReadLine();

 

        int vowels = 0, consonants = 0;

 

        foreach (char c in input.ToLower())

        {

            if ("aeiou".Contains(c))

                vowels++;

            else if (Char.IsLetter(c))

                consonants++;

        }

 

        Console.WriteLine($"Vowels: {vowels}");

        Console.WriteLine($"Consonants: {consonants}");

    }

}

49. Find the Most Frequent Element in an Array (Intermediate)

Write a program to find the most frequent element in an array.

using System;

using System.Linq;

 

class Program

{

    static void Main()

    {

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

 

        var mostFrequent = arr.GroupBy(x => x)

                              .OrderByDescending(g => g.Count())

                              .First()

                              .Key;

 

        Console.WriteLine($"The most frequent element is: {mostFrequent}");

    }

}

50. Implement Stack Using Arrays (Intermediate)

Write a program to implement a stack using arrays with basic stack operations (push, pop, peek).

using System;

 

class Stack

{

    private int[] stackArray;

    private int top;

 

    public Stack(int size)

    {

        stackArray = new int[size];

        top = -1;

    }

 

    public void Push(int value)

    {

        if (top == stackArray.Length - 1)

            Console.WriteLine("Stack is full.");

        else

            stackArray[++top] = value;

    }

 

    public int Pop()

    {

        if (top == -1)

        {

            Console.WriteLine("Stack is empty.");

            return -1;

        }

        else

            return stackArray[top--];

    }

 

    public int Peek()

    {

        if (top == -1)

        {

            Console.WriteLine("Stack is empty.");

            return -1;

        }

        else

            return stackArray[top];

    }

 

    public bool IsEmpty()

    {

        return top == -1;

    }

}

 

class Program

{

    static void Main()

    {

        Stack stack = new Stack(5);

 

        stack.Push(10);

        stack.Push(20);

        stack.Push(30);

 

        Console.WriteLine($"Top element: {stack.Peek()}");

 

        Console.WriteLine($"Popped element: {stack.Pop()}");

        Console.WriteLine($"Top element after pop: {stack.Peek()}");

    }

}

51. Find the Common Elements in Two Arrays (Intermediate)

Write a program to find and display the common elements between two arrays.

using System;

using System.Linq;

 

class Program

{

    static void Main()

    {

        int[] arr1 = { 1, 2, 3, 4, 5 };

        int[] arr2 = { 3, 4, 5, 6, 7 };

 

        var commonElements = arr1.Intersect(arr2).ToArray();

 

        Console.WriteLine("Common elements: " + string.Join(", ", commonElements));

    }

}

52. Convert a String to Title Case (Beginner/Intermediate)

Write a program to convert a string to title case, where the first letter of each word is capitalized.

using System;

using System.Globalization;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string input = Console.ReadLine();

 

        string titleCase = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input.ToLower());

        Console.WriteLine("Title case: " + titleCase);

    }

}

53. Count the Occurrences of Each Character in a String (Intermediate)

Write a program to count the occurrences of each character in a string.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string input = Console.ReadLine();

 

        var characterCount = new Dictionary<char, int>();

 

        foreach (char c in input)

        {

            if (char.IsLetter(c))

            {

                if (characterCount.ContainsKey(c))

                    characterCount[c]++;

                else

                    characterCount[c] = 1;

            }

        }

 

        foreach (var kvp in characterCount)

        {

            Console.WriteLine($"{kvp.Key}: {kvp.Value}");

        }

    }

}

 

 

54. Reverse Words in a Sentence (Intermediate)

Write a program that reverses the order of words in a given sentence, but keeps the characters in each word in the original order.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a sentence: ");

        string sentence = Console.ReadLine();

 

        string reversed = ReverseWords(sentence);

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

    }

 

    static string ReverseWords(string sentence)

    {

        string[] words = sentence.Split(' ');

        Array.Reverse(words);

        return string.Join(" ", words);

    }

}

55. Find the Missing Number in an Arithmetic Sequence (Advanced)

Write a program that finds the missing number in an arithmetic sequence.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { 3, 7, 11, 19, 23 }; // Missing 15

        int missing = FindMissingNumber(arr);

        Console.WriteLine($"The missing number is: {missing}");

    }

 

    static int FindMissingNumber(int[] arr)

    {

        int n = arr.Length + 1;

        int expectedSum = (arr[0] + arr[arr.Length - 1]) * n / 2;

        int actualSum = 0;

 

        foreach (int num in arr)

        {

            actualSum += num;

        }

 

        return expectedSum - actualSum;

    }

}

56. Check If a String Is a Palindrome (Intermediate)

Write a program to check if a string is a palindrome (ignoring spaces and case sensitivity).

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string input = Console.ReadLine();

 

        bool isPalindrome = IsPalindrome(input);

        if (isPalindrome)

            Console.WriteLine("The string is a palindrome.");

        else

            Console.WriteLine("The string is not a palindrome.");

    }

 

    static bool IsPalindrome(string str)

    {

        string cleaned = string.Join("", str.ToLower().ToCharArray().Where(c => char.IsLetterOrDigit(c)));

        string reversed = new string(cleaned.Reverse().ToArray());

        return cleaned == reversed;

    }

}

57. Find the Longest Substring Without Repeating Characters (Advanced)

Write a program to find the length of the longest substring without repeating characters in a string.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string str = Console.ReadLine();

 

        int result = LengthOfLongestSubstring(str);

        Console.WriteLine($"The length of the longest substring without repeating characters is: {result}");

    }

 

    static int LengthOfLongestSubstring(string s)

    {

        int maxLength = 0;

        Dictionary<char, int> charIndexMap = new Dictionary<char, int>();

        int start = 0;

 

        for (int end = 0; end < s.Length; end++)

        {

            if (charIndexMap.ContainsKey(s[end]))

                start = Math.Max(start, charIndexMap[s[end]] + 1);

 

            charIndexMap[s[end]] = end;

            maxLength = Math.Max(maxLength, end - start + 1);

        }

 

        return maxLength;

    }

}

58. Calculate the Sum of Natural Numbers (Beginner)

Write a program to calculate the sum of the first n natural numbers.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a number: ");

        int n = int.Parse(Console.ReadLine());

 

        int sum = SumOfNaturalNumbers(n);

        Console.WriteLine($"The sum of the first {n} natural numbers is: {sum}");

    }

 

    static int SumOfNaturalNumbers(int n)

    {

        return n * (n + 1) / 2;

    }

}

59. Find Common Characters Between Two Strings (Intermediate)

Write a program to find the common characters between two strings (case insensitive).

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter the first string: ");

        string str1 = Console.ReadLine();

 

        Console.Write("Enter the second string: ");

        string str2 = Console.ReadLine();

 

        string commonChars = FindCommonCharacters(str1, str2);

        Console.WriteLine($"Common characters: {commonChars}");

    }

 

    static string FindCommonCharacters(string str1, string str2)

    {

        str1 = str1.ToLower();

        str2 = str2.ToLower();

 

        var commonChars = new string(str1.Intersect(str2).ToArray());

        return string.Join("", commonChars);

    }

}

60. Check If Two Strings Are Rotation of Each Other (Advanced)

Write a program to check if two strings are rotations of each other (e.g., "abc" and "cab").

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter the first string: ");

        string str1 = Console.ReadLine();

 

        Console.Write("Enter the second string: ");

        string str2 = Console.ReadLine();

 

        bool areRotations = AreRotations(str1, str2);

        if (areRotations)

            Console.WriteLine("The strings are rotations of each other.");

        else

            Console.WriteLine("The strings are not rotations of each other.");

    }

 

    static bool AreRotations(string str1, string str2)

    {

        if (str1.Length != str2.Length)

            return false;

 

        string combined = str1 + str1;

        return combined.Contains(str2);

    }

}

61. Sort an Array of Strings by Length (Intermediate)

Write a program to sort an array of strings by the length of the strings.

using System;

using System.Linq;

 

class Program

{

    static void Main()

    {

        string[] arr = { "apple", "banana", "kiwi", "grape", "cherry" };

 

        var sorted = arr.OrderBy(s => s.Length).ToArray();

        Console.WriteLine("Sorted array by length: " + string.Join(", ", sorted));

    }

}

62. Sum of Elements in Two Arrays (Beginner)

Write a program that takes two arrays of integers and sums the elements at corresponding indices.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr1 = { 1, 2, 3, 4 };

        int[] arr2 = { 5, 6, 7, 8 };

 

        int[] summed = SumArrays(arr1, arr2);

        Console.WriteLine("Summed array: " + string.Join(", ", summed));

    }

 

    static int[] SumArrays(int[] arr1, int[] arr2)

    {

        int length = Math.Min(arr1.Length, arr2.Length);

        int[] result = new int[length];

 

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

        {

            result[i] = arr1[i] + arr2[i];

        }

 

        return result;

    }

}

63. Find the Intersection of Two Arrays (Advanced)

Write a program to find the intersection of two arrays, where each element in the intersection appears as many times as it shows up in both arrays.

using System;

using System.Linq;

 

class Program

{

    static void Main()

    {

        int[] arr1 = { 1, 2, 2, 1 };

        int[] arr2 = { 2, 2 };

 

        var intersection = arr1.Intersect(arr2).ToArray();

        Console.WriteLine("Intersection of arrays: " + string.Join(", ", intersection));

    }

}

64. Remove All Vowels From a String (Intermediate)

Write a program to remove all vowels from a given string.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string input = Console.ReadLine();

 

        string result = RemoveVowels(input);

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

    }

 

    static string RemoveVowels(string str)

    {

        string vowels = "aeiouAEIOU";

        return string.Join("", str.Where(c => !vowels.Contains(c)));

    }

}

65. Find the Sum of Odd and Even Numbers in an Array (Beginner)

Write a program to find the sum of odd and even numbers separately in an array.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

 

        (int oddSum, int evenSum) = SumOddAndEven(arr);

        Console.WriteLine($"Sum of odd numbers: {oddSum}");

        Console.WriteLine($"Sum of even numbers: {evenSum}");

    }

 

    static (int, int) SumOddAndEven(int[] arr)

    {

        int oddSum = 0, evenSum = 0;

        foreach (int num in arr)

        {

            if (num % 2 == 0)

                evenSum += num;

            else

                oddSum += num;

        }

        return (oddSum, evenSum);

    }

}

 

 

66. Find the Intersection of Two Lists (Advanced)

Write a program that finds the intersection (common elements) of two lists of integers.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        List<int> list1 = new List<int> { 1, 2, 3, 4, 5 };

        List<int> list2 = new List<int> { 4, 5, 6, 7, 8 };

 

        var intersection = FindIntersection(list1, list2);

        Console.WriteLine("Intersection: " + string.Join(", ", intersection));

    }

 

    static List<int> FindIntersection(List<int> list1, List<int> list2)

    {

        HashSet<int> set1 = new HashSet<int>(list1);

        HashSet<int> set2 = new HashSet<int>(list2);

       

        set1.IntersectWith(set2); // Modify set1 to contain only the elements that are also in set2

        return new List<int>(set1);

    }

}

67. Count the Number of Words in a Sentence (Beginner)

Write a program that counts the number of words in a given sentence.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a sentence: ");

        string sentence = Console.ReadLine();

 

        int wordCount = CountWords(sentence);

        Console.WriteLine($"Number of words: {wordCount}");

    }

 

    static int CountWords(string sentence)

    {

        string[] words = sentence.Split(new char[] { ' ', '\t', '\n' }, StringSplitOptions.RemoveEmptyEntries);

        return words.Length;

    }

}

68. Find the Longest Palindromic Substring (Advanced)

Write a program to find the longest palindromic substring in a given string.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string str = Console.ReadLine();

 

        string longestPalindrome = LongestPalindromeSubstring(str);

        Console.WriteLine($"Longest Palindromic Substring: {longestPalindrome}");

    }

 

    static string LongestPalindromeSubstring(string s)

    {

        if (s.Length == 0) return "";

 

        string longest = s.Substring(0, 1);

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

        {

            // Odd length palindrome

            string oddPalindrome = ExpandAroundCenter(s, i, i);

            if (oddPalindrome.Length > longest.Length)

                longest = oddPalindrome;

 

            // Even length palindrome

            string evenPalindrome = ExpandAroundCenter(s, i, i + 1);

            if (evenPalindrome.Length > longest.Length)

                longest = evenPalindrome;

        }

 

        return longest;

    }

 

    static string ExpandAroundCenter(string s, int left, int right)

    {

        while (left >= 0 && right < s.Length && s[left] == s[right])

        {

            left--;

            right++;

        }

 

        return s.Substring(left + 1, right - left - 1);

    }

}

69. Find the Missing Number in an Array (Intermediate)

Write a program to find the missing number from a given array that contains numbers from 1 to n.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { 1, 2, 4, 5, 6 };

        int n = 6;  // The array contains numbers from 1 to 6

 

        int missing = FindMissingNumber(arr, n);

        Console.WriteLine($"The missing number is: {missing}");

    }

 

    static int FindMissingNumber(int[] arr, int n)

    {

        int totalSum = n * (n + 1) / 2; // Sum of numbers from 1 to n

        int arraySum = 0;

       

        foreach (int num in arr)

        {

            arraySum += num;

        }

 

        return totalSum - arraySum;

    }

}

70. Convert a Number to Binary (Beginner)

Write a program that converts a given decimal number to binary.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a decimal number: ");

        int decimalNumber = int.Parse(Console.ReadLine());

 

        string binary = ConvertToBinary(decimalNumber);

        Console.WriteLine($"Binary representation: {binary}");

    }

 

    static string ConvertToBinary(int number)

    {

        return Convert.ToString(number, 2);

    }

}

71. Find the First Non-Repeated Character in a String (Intermediate)

Write a program to find the first non-repeated character in a given string.

using System;

using System.Linq;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string str = Console.ReadLine();

 

        char firstNonRepeated = FindFirstNonRepeated(str);

        Console.WriteLine($"First non-repeated character: {firstNonRepeated}");

    }

 

    static char FindFirstNonRepeated(string str)

    {

        var charCount = str.GroupBy(c => c)

                           .Where(g => g.Count() == 1)

                           .Select(g => g.Key)

                           .FirstOrDefault();

 

        return charCount;

    }

}

72. Generate a Random Password (Beginner)

Write a program that generates a random password of a specified length containing uppercase letters, lowercase letters, numbers, and special characters.

using System;

using System.Linq;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter the password length: ");

        int length = int.Parse(Console.ReadLine());

 

        string password = GenerateRandomPassword(length);

        Console.WriteLine($"Generated Password: {password}");

    }

 

    static string GenerateRandomPassword(int length)

    {

        const string upperCaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        const string lowerCaseChars = "abcdefghijklmnopqrstuvwxyz";

        const string numbers = "0123456789";

        const string specialChars = "!@#$%^&*()_-+=<>?";

 

        string allChars = upperCaseChars + lowerCaseChars + numbers + specialChars;

        Random rand = new Random();

 

        return new string(Enumerable.Range(0, length)

            .Select(_ => allChars[rand.Next(allChars.Length)])

            .ToArray());

    }

}

73. Print the Fibonacci Sequence (Beginner)

Write a program to print the Fibonacci sequence up to a specified number n.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter the number of terms: ");

        int n = int.Parse(Console.ReadLine());

 

        PrintFibonacci(n);

    }

 

    static void PrintFibonacci(int n)

    {

        int a = 0, b = 1;

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

        {

            Console.Write(a + " ");

            int nextTerm = a + b;

            a = b;

            b = nextTerm;

        }

    }

}

74. Count the Number of Vowels in a String (Beginner)

Write a program to count the number of vowels in a given string.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string input = Console.ReadLine();

 

        int vowelCount = CountVowels(input);

        Console.WriteLine($"Number of vowels: {vowelCount}");

    }

 

    static int CountVowels(string str)

    {

        int count = 0;

        string vowels = "aeiouAEIOU";

 

        foreach (char c in str)

        {

            if (vowels.Contains(c))

                count++;

        }

 

        return count;

    }

}

75. Find the Largest Palindrome in a String (Advanced)

Write a program to find the largest palindrome within a given string.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string input = Console.ReadLine();

 

        string largestPalindrome = FindLargestPalindrome(input);

        Console.WriteLine($"Largest palindrome: {largestPalindrome}");

    }

 

    static string FindLargestPalindrome(string str)

    {

        string longestPalindrome = "";

 

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

        {

            for (int j = i + 1; j <= str.Length; j++)

            {

                string substring = str.Substring(i, j - i);

                if (IsPalindrome(substring) && substring.Length > longestPalindrome.Length)

                {

                    longestPalindrome = substring;

                }

            }

        }

 

        return longestPalindrome;

    }

 

    static bool IsPalindrome(string s)

    {

        int left = 0;

        int right = s.Length - 1;

 

        while (left < right)

        {

            if (s[left] != s[right])

                return false;

            left++;

            right--;

        }

 

        return true;

    }

}

76. Find All Divisors of a Number (Beginner)

Write a program to find all divisors of a given number.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a number: ");

        int number = int.Parse(Console.ReadLine());

 

        FindDivisors(number);

    }

 

    static void FindDivisors(int num)

    {

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

        {

            if (num % i == 0)

                Console.Write(i + " ");

        }

    }

}

 

 

 

 

77. Find the Product of All Elements in an Array (Beginner)

Write a program to calculate the product of all elements in a given array.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { 1, 2, 3, 4 };

        int product = ProductOfArray(arr);

        Console.WriteLine($"Product of all elements: {product}");

    }

 

    static int ProductOfArray(int[] arr)

    {

        int product = 1;

        foreach (int num in arr)

        {

            product *= num;

        }

        return product;

    }

}

78. Check If a Number is Prime (Beginner)

Write a program to check if a number is prime.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a number: ");

        int num = int.Parse(Console.ReadLine());

 

        bool isPrime = IsPrime(num);

        Console.WriteLine(isPrime ? "The number is prime." : "The number is not prime.");

    }

 

    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;

    }

}

79. Find the Maximum Sum of Non-Adjacent Elements (Advanced)

Write a program to find the maximum sum of non-adjacent elements in an array.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { 3, 2, 7, 10 };

        int maxSum = MaxSumNonAdjacent(arr);

        Console.WriteLine($"Maximum sum of non-adjacent elements: {maxSum}");

    }

 

    static int MaxSumNonAdjacent(int[] arr)

    {

        int incl = arr[0];

        int excl = 0;

 

        for (int i = 1; i < arr.Length; i++)

        {

            int newIncl = excl + arr[i];

            excl = Math.Max(excl, incl);

            incl = newIncl;

        }

 

        return Math.Max(incl, excl);

    }

}

80. Count the Frequency of Each Character in a String (Intermediate)

Write a program to count the frequency of each character in a string.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string str = Console.ReadLine();

 

        var frequency = CountCharacterFrequency(str);

        foreach (var kvp in frequency)

        {

            Console.WriteLine($"Character: {kvp.Key}, Frequency: {kvp.Value}");

        }

    }

 

    static Dictionary<char, int> CountCharacterFrequency(string str)

    {

        Dictionary<char, int> frequency = new Dictionary<char, int>();

 

        foreach (char c in str)

        {

            if (frequency.ContainsKey(c))

                frequency[c]++;

            else

                frequency[c] = 1;

        }

 

        return frequency;

    }

}

81. Merge Two Sorted Arrays (Intermediate)

Write a program to merge two sorted arrays into a single sorted array.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr1 = { 1, 3, 5, 7 };

        int[] arr2 = { 2, 4, 6, 8 };

 

        int[] mergedArray = MergeSortedArrays(arr1, arr2);

        Console.WriteLine("Merged Array: " + string.Join(", ", mergedArray));

    }

 

    static int[] MergeSortedArrays(int[] arr1, int[] arr2)

    {

        int[] result = new int[arr1.Length + arr2.Length];

        int i = 0, j = 0, k = 0;

 

        while (i < arr1.Length && j < arr2.Length)

        {

            if (arr1[i] < arr2[j])

                result[k++] = arr1[i++];

            else

                result[k++] = arr2[j++];

        }

 

        while (i < arr1.Length)

            result[k++] = arr1[i++];

 

        while (j < arr2.Length)

            result[k++] = arr2[j++];

 

        return result;

    }

}

82. Find the Kth Largest Element in an Array (Advanced)

Write a program to find the kth largest element in an array.

using System;

using System.Linq;

 

class Program

{

    static void Main()

    {

        int[] arr = { 12, 3, 5, 7, 19 };

        int k = 2;  // Find 2nd largest element

        int kthLargest = FindKthLargest(arr, k);

        Console.WriteLine($"The {k}th largest element is: {kthLargest}");

    }

 

    static int FindKthLargest(int[] arr, int k)

    {

        var sortedArray = arr.OrderByDescending(x => x).ToArray();

        return sortedArray[k - 1];

    }

}

83. Rotate an Array to the Right by K Positions (Intermediate)

Write a program to rotate an array to the right by k positions.

using System;

 

class Program

{

    static void Main()

    {

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

        int k = 2;

 

        RotateArray(arr, k);

        Console.WriteLine("Rotated Array: " + string.Join(", ", arr));

    }

 

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

    {

        int n = arr.Length;

        k = k % n; // In case k is larger than array length

        ReverseArray(arr, 0, n - 1);

        ReverseArray(arr, 0, k - 1);

        ReverseArray(arr, k, n - 1);

    }

 

    static void ReverseArray(int[] arr, int start, int end)

    {

        while (start < end)

        {

            int temp = arr[start];

            arr[start] = arr[end];

            arr[end] = temp;

            start++;

            end--;

        }

    }

}

84. Find the Longest Consecutive Subsequence (Advanced)

Write a program to find the length of the longest consecutive subsequence in an unsorted array.

using System;

using System.Linq;

 

class Program

{

    static void Main()

    {

        int[] arr = { 100, 4, 200, 1, 3, 2 };

        int longestLength = FindLongestConsecutiveSubsequence(arr);

        Console.WriteLine($"Length of the longest consecutive subsequence: {longestLength}");

    }

 

    static int FindLongestConsecutiveSubsequence(int[] arr)

    {

        if (arr.Length == 0) return 0;

 

        var uniqueNumbers = new HashSet<int>(arr);

        int longestStreak = 1;

 

        foreach (int num in uniqueNumbers)

        {

            if (!uniqueNumbers.Contains(num - 1))  // Check if it's the start of a sequence

            {

                int currentNum = num;

                int currentStreak = 1;

 

                while (uniqueNumbers.Contains(currentNum + 1))

                {

                    currentNum++;

                    currentStreak++;

                }

 

                longestStreak = Math.Max(longestStreak, currentStreak);

            }

        }

 

        return longestStreak;

    }

}

85. Find the First Duplicate Number in an Array (Advanced)

Write a program to find the first duplicate number in an array.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        int[] arr = { 2, 3, 1, 4, 5, 2, 6 };

        int firstDuplicate = FindFirstDuplicate(arr);

        Console.WriteLine($"The first duplicate number is: {firstDuplicate}");

    }

 

    static int FindFirstDuplicate(int[] arr)

    {

        HashSet<int> seen = new HashSet<int>();

 

        foreach (int num in arr)

        {

            if (seen.Contains(num))

                return num;

            seen.Add(num);

        }

 

        return -1;  // No duplicates found

    }

}

86. Check If Two Strings Are Anagrams (Intermediate)

Write a program to check if two strings are anagrams (contain the same characters in any order).

using System;

using System.Linq;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter the first string: ");

        string str1 = Console.ReadLine();

 

        Console.Write("Enter the second string: ");

        string str2 = Console.ReadLine();

 

        bool isAnagram = AreAnagrams(str1, str2);

        Console.WriteLine(isAnagram ? "The strings are anagrams." : "The strings are not anagrams.");

    }

 

    static bool AreAnagrams(string str1, string str2)

    {

        var sortedStr1 = new string(str1.OrderBy(c => c).ToArray());

        var sortedStr2 = new string(str2.OrderBy(c => c).ToArray());

 

        return sortedStr1 == sortedStr2;

    }

}

87. Find the Union of Two Arrays (Intermediate)

Write a program to find the union of two arrays.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr1 = { 1, 2, 3, 4 };

        int[] arr2 = { 3, 4, 5, 6 };

 

        var union = FindUnion(arr1, arr2);

        Console.WriteLine("Union of arrays: " + string.Join(", ", union));

    }

 

    static int[] FindUnion(int[] arr1, int[] arr2)

    {

        var unionSet = new HashSet<int>(arr1);

        foreach (int num in arr2)

        {

            unionSet.Add(num);

        }

        return unionSet.ToArray();

    }

}

 

 

88. Reverse a Linked List (Intermediate)

Write a program to reverse a singly linked list.

using System;

 

class Program

{

    class ListNode

    {

        public int val;

        public ListNode next;

        public ListNode(int val = 0, ListNode next = null)

        {

            this.val = val;

            this.next = next;

        }

    }

 

    static void Main()

    {

        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4))));

        head = ReverseLinkedList(head);

 

        Console.WriteLine("Reversed Linked List: ");

        PrintList(head);

    }

 

    static ListNode ReverseLinkedList(ListNode head)

    {

        ListNode prev = null;

        ListNode curr = head;

        while (curr != null)

        {

            ListNode next = curr.next;

            curr.next = prev;

            prev = curr;

            curr = next;

        }

        return prev;

    }

 

    static void PrintList(ListNode head)

    {

        while (head != null)

        {

            Console.Write(head.val + " ");

            head = head.next;

        }

        Console.WriteLine();

    }

}

89. Find the Missing Number in an Array (Intermediate)

Given an array containing n-1 numbers taken from the range 1 to n, find the missing number.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { 1, 2, 4, 5 }; // Missing number is 3

        int missingNumber = FindMissingNumber(arr, 5);  // n is 5

        Console.WriteLine($"The missing number is: {missingNumber}");

    }

 

    static int FindMissingNumber(int[] arr, int n)

    {

        int totalSum = n * (n + 1) / 2;

        int arraySum = 0;

 

        foreach (int num in arr)

        {

            arraySum += num;

        }

 

        return totalSum - arraySum;

    }

}

90. Check If a String is a Palindrome (Beginner)

Write a program to check if a string is a palindrome.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string input = Console.ReadLine();

 

        bool isPalindrome = IsPalindrome(input);

        Console.WriteLine(isPalindrome ? "The string is a palindrome." : "The string is not a palindrome.");

    }

 

    static bool IsPalindrome(string str)

    {

        int start = 0;

        int end = str.Length - 1;

 

        while (start < end)

        {

            if (str[start] != str[end])

                return false;

 

            start++;

            end--;

        }

 

        return true;

    }

}

91. Find All Prime Numbers in a Range (Intermediate)

Write a program to find all prime numbers in a range from 1 to n.

using System;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a number n: ");

        int n = int.Parse(Console.ReadLine());

 

        Console.WriteLine("Prime numbers from 1 to " + n + ":");

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

        {

            if (IsPrime(i))

                Console.Write(i + " ");

        }

    }

 

    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;

    }

}

92. Find the Longest Substring Without Repeating Characters (Advanced)

Write a program to find the length of the longest substring without repeating characters.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string input = Console.ReadLine();

 

        int length = LongestSubstringWithoutRepeating(input);

        Console.WriteLine($"The length of the longest substring without repeating characters is: {length}");

    }

 

    static int LongestSubstringWithoutRepeating(string s)

    {

        HashSet<char> seenChars = new HashSet<char>();

        int maxLength = 0;

        int left = 0;

 

        for (int right = 0; right < s.Length; right++)

        {

            while (seenChars.Contains(s[right]))

            {

                seenChars.Remove(s[left]);

                left++;

            }

 

            seenChars.Add(s[right]);

            maxLength = Math.Max(maxLength, right - left + 1);

        }

 

        return maxLength;

    }

}

93. Find the Intersection of Two Arrays (Intermediate)

Write a program to find the intersection of two arrays.

using System;

using System.Linq;

 

class Program

{

    static void Main()

    {

        int[] arr1 = { 1, 2, 2, 1 };

        int[] arr2 = { 2, 2 };

 

        var intersection = FindIntersection(arr1, arr2);

        Console.WriteLine("Intersection: " + string.Join(", ", intersection));

    }

 

    static int[] FindIntersection(int[] arr1, int[] arr2)

    {

        return arr1.Intersect(arr2).ToArray();

    }

}

94. Find the Kth Smallest Element in an Array (Advanced)

Write a program to find the kth smallest element in an unsorted array.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { 12, 3, 5, 7, 19 };

        int k = 2;

 

        int kthSmallest = FindKthSmallest(arr, k);

        Console.WriteLine($"The {k}th smallest element is: {kthSmallest}");

    }

 

    static int FindKthSmallest(int[] arr, int k)

    {

        Array.Sort(arr);

        return arr[k - 1];

    }

}

95. Check if a String is a Valid Anagram (Beginner)

Write a program to check if two strings are valid anagrams.

using System;

using System.Linq;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter the first string: ");

        string str1 = Console.ReadLine();

 

        Console.Write("Enter the second string: ");

        string str2 = Console.ReadLine();

 

        bool isAnagram = AreAnagrams(str1, str2);

        Console.WriteLine(isAnagram ? "The strings are anagrams." : "The strings are not anagrams.");

    }

 

    static bool AreAnagrams(string str1, string str2)

    {

        if (str1.Length != str2.Length)

            return false;

 

        var sortedStr1 = new string(str1.OrderBy(c => c).ToArray());

        var sortedStr2 = new string(str2.OrderBy(c => c).ToArray());

 

        return sortedStr1 == sortedStr2;

    }

}

96. Find the First Non-Repeated Character in a String (Intermediate)

Write a program to find the first non-repeated character in a string.

using System;

using System.Linq;

 

class Program

{

    static void Main()

    {

        Console.Write("Enter a string: ");

        string str = Console.ReadLine();

 

        char firstNonRepeated = FindFirstNonRepeated(str);

        Console.WriteLine($"First non-repeated character: {firstNonRepeated}");

    }

 

    static char FindFirstNonRepeated(string str)

    {

        return str.FirstOrDefault(c => str.IndexOf(c) == str.LastIndexOf(c));

    }

}

97. Implement Binary Search (Beginner)

Write a program to implement the binary search algorithm.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        int target = 7;

        int index = BinarySearch(arr, target);

 

        if (index != -1)

            Console.WriteLine($"Element found at index: {index}");

        else

            Console.WriteLine("Element not found.");

    }

 

    static int BinarySearch(int[] arr, int target)

    {

        int left = 0, right = arr.Length - 1;

 

        while (left <= right)

        {

            int mid = left + (right - left) / 2;

 

            if (arr[mid] == target)

                return mid;

            if (arr[mid] < target)

                left = mid + 1;

            else

                right = mid - 1;

        }

 

        return -1;

    }

}

98. Find the Largest Contiguous Sum Subarray (Intermediate)

Write a program to find the largest sum of any contiguous subarray in a given array (Kadane's Algorithm).

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };

        int maxSum = LargestContiguousSubarraySum(arr);

        Console.WriteLine($"The largest sum of contiguous subarray is: {maxSum}");

    }

 

    static int LargestContiguousSubarraySum(int[] arr)

    {

        int maxSum = arr[0];

        int currentSum = arr[0];

 

        for (int i = 1; i < arr.Length; i++)

        {

            currentSum = Math.Max(arr[i], currentSum + arr[i]);

            maxSum = Math.Max(maxSum, currentSum);

        }

 

        return maxSum;

    }

}

99. Merge Intervals (Advanced)

Write a program to merge overlapping intervals in a list of intervals.

using System;

using System.Linq;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        var intervals = new List<Tuple<int, int>>()

        {

            Tuple.Create(1, 3),

            Tuple.Create(2, 4),

            Tuple.Create(5, 7),

            Tuple.Create(6, 8)

        };

 

        var mergedIntervals = MergeIntervals(intervals);

        Console.WriteLine("Merged Intervals: ");

        foreach (var interval in mergedIntervals)

        {

            Console.WriteLine($"[{interval.Item1}, {interval.Item2}]");

        }

    }

 

    static List<Tuple<int, int>> MergeIntervals(List<Tuple<int, int>> intervals)

    {

        if (intervals.Count == 0)

            return intervals;

 

        var sortedIntervals = intervals.OrderBy(interval => interval.Item1).ToList();

        var result = new List<Tuple<int, int>> { sortedIntervals[0] };

 

        for (int i = 1; i < sortedIntervals.Count; i++)

        {

            var lastInterval = result.Last();

        var currentInterval = sortedIntervals[i];

 

        if (lastInterval.Item2 >= currentInterval.Item1) // Overlapping

        {

            result[result.Count - 1] = Tuple.Create(lastInterval.Item1, Math.Max(lastInterval.Item2, currentInterval.Item2));

        }

        else

        {

            result.Add(currentInterval);

        }

    }

 

    return result;

}

}

 

### 100. **Rotate an Image (Matrix) (Advanced)**

Write a program to rotate an `n x n` matrix (2D array) 90 degrees clockwise.

 

```csharp

using System;

 

class Program

{

    static void Main()

    {

        int[,] matrix = {

            { 1, 2, 3 },

            { 4, 5, 6 },

            { 7, 8, 9 }

        };

 

        RotateImage(matrix);

 

        Console.WriteLine("Rotated Matrix:");

        for (int i = 0; i < matrix.GetLength(0); i++)

        {

            for (int j = 0; j < matrix.GetLength(1); j++)

            {

                Console.Write(matrix[i, j] + " ");

            }

            Console.WriteLine();

        }

    }

 

    static void RotateImage(int[,] matrix)

    {

        int n = matrix.GetLength(0);

 

        // Transpose the matrix

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

        {

            for (int j = i + 1; j < n; j++)

            {

                int temp = matrix[i, j];

                matrix[i, j] = matrix[j, i];

                matrix[j, i] = temp;

            }

        }

 

        // Reverse each row

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

        {

            Array.Reverse(matrix, i * n, n);

        }

    }

}

 

 

101. Two Sum (Beginner)

Given an array of integers, return the indices of the two numbers that add up to a specific target.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        int[] nums = { 2, 7, 11, 15 };

        int target = 9;

        var result = TwoSum(nums, target);

        Console.WriteLine($"Indices: {result[0]}, {result[1]}");

    }

 

    static int[] TwoSum(int[] nums, int target)

    {

        Dictionary<int, int> numDict = new Dictionary<int, int>();

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

        {

            int complement = target - nums[i];

            if (numDict.ContainsKey(complement))

            {

                return new int[] { numDict[complement], i };

            }

            numDict[nums[i]] = i;

        }

        return new int[] { -1, -1 }; // If no solution

    }

}

102. Maximum Subarray (Kadane’s Algorithm) (Intermediate)

Find the contiguous subarray within a one-dimensional array of numbers which has the largest sum.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };

        int maxSum = MaximumSubarray(arr);

        Console.WriteLine($"Maximum subarray sum: {maxSum}");

    }

 

    static int MaximumSubarray(int[] arr)

    {

        int currentSum = arr[0];

        int maxSum = arr[0];

 

        for (int i = 1; i < arr.Length; i++)

        {

            currentSum = Math.Max(arr[i], currentSum + arr[i]);

            maxSum = Math.Max(maxSum, currentSum);

        }

 

        return maxSum;

    }

}

103. Valid Parentheses (Beginner)

Given a string containing just the characters '(', ')', {, '}', [ and ], determine if the input string is valid. An input string is valid if the brackets are closed in the correct order.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        string s = "{[]}";

        bool isValid = IsValid(s);

        Console.WriteLine(isValid ? "Valid" : "Invalid");

    }

 

    static bool IsValid(string s)

    {

        Stack<char> stack = new Stack<char>();

 

        foreach (char c in s)

        {

            if (c == '(' || c == '{' || c == '[')

                stack.Push(c);

            else if (c == ')' && stack.Count > 0 && stack.Peek() == '(')

                stack.Pop();

            else if (c == '}' && stack.Count > 0 && stack.Peek() == '{')

                stack.Pop();

            else if (c == ']' && stack.Count > 0 && stack.Peek() == '[')

                stack.Pop();

            else

                return false;

        }

 

        return stack.Count == 0;

    }

}

104. Find the Duplicates in an Array (Intermediate)

Write a program to find all elements that appear more than once in an array.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        int[] nums = { 4, 3, 2, 7, 8, 2, 3, 1 };

        var duplicates = FindDuplicates(nums);

        Console.WriteLine("Duplicates: " + string.Join(", ", duplicates));

    }

 

    static List<int> FindDuplicates(int[] nums)

    {

        List<int> duplicates = new List<int>();

        HashSet<int> seen = new HashSet<int>();

 

        foreach (int num in nums)

        {

            if (seen.Contains(num))

                duplicates.Add(num);

            else

                seen.Add(num);

        }

 

        return duplicates;

    }

}

105. Merge Sorted Arrays (Intermediate)

Given two sorted arrays, merge them into a single sorted array.

using System;

 

class Program

{

    static void Main()

    {

        int[] arr1 = { 1, 3, 5, 7 };

        int[] arr2 = { 2, 4, 6, 8 };

        int[] merged = MergeArrays(arr1, arr2);

        Console.WriteLine("Merged Array: " + string.Join(", ", merged));

    }

 

    static int[] MergeArrays(int[] arr1, int[] arr2)

    {

        int[] result = new int[arr1.Length + arr2.Length];

        int i = 0, j = 0, k = 0;

 

        while (i < arr1.Length && j < arr2.Length)

        {

            if (arr1[i] < arr2[j])

                result[k++] = arr1[i++];

            else

                result[k++] = arr2[j++];

        }

 

        while (i < arr1.Length)

            result[k++] = arr1[i++];

       

        while (j < arr2.Length)

            result[k++] = arr2[j++];

       

        return result;

    }

}

106. Longest Common Prefix (Beginner)

Write a program to find the longest common prefix string amongst an array of strings.

using System;

 

class Program

{

    static void Main()

    {

        string[] strs = { "flower", "flow", "flight" };

        string prefix = LongestCommonPrefix(strs);

        Console.WriteLine("Longest common prefix: " + prefix);

    }

 

    static string LongestCommonPrefix(string[] strs)

    {

        if (strs.Length == 0)

            return "";

 

        string prefix = strs[0];

 

        foreach (string str in strs)

        {

            while (str.IndexOf(prefix) != 0)

            {

                prefix = prefix.Substring(0, prefix.Length - 1);

                if (prefix == "")

                    return "";

            }

        }

 

        return prefix;

    }

}

107. Find the Duplicate Number (Intermediate)

Given an array containing n + 1 integers where each integer is between 1 and n, find the duplicate number.

using System;

 

class Program

{

    static void Main()

    {

        int[] nums = { 1, 3, 4, 2, 2 };

        int duplicate = FindDuplicate(nums);

        Console.WriteLine($"Duplicate number: {duplicate}");

    }

 

    static int FindDuplicate(int[] nums)

    {

        int slow = nums[0];

        int fast = nums[0];

 

        // Phase 1: Find intersection point of two runners.

        do

        {

            slow = nums[slow];

            fast = nums[nums[fast]];

        } while (slow != fast);

 

        // Phase 2: Find the entrance to the cycle.

        slow = nums[0];

        while (slow != fast)

        {

            slow = nums[slow];

            fast = nums[fast];

        }

 

        return slow;

    }

}

108. Count Primes (Intermediate)

Write a program to count the number of prime numbers less than a non-negative number n.

using System;

 

class Program

{

    static void Main()

    {

        int n = 10;

        int count = CountPrimes(n);

        Console.WriteLine($"Number of primes less than {n}: {count}");

    }

 

    static int CountPrimes(int n)

    {

        if (n <= 2)

            return 0;

 

        bool[] isPrime = new bool[n];

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

            isPrime[i] = true;

 

        for (int i = 2; i * i < n; i++)

        {

            if (isPrime[i])

            {

                for (int j = i * i; j < n; j += i)

                    isPrime[j] = false;

            }

        }

 

        int count = 0;

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

            if (isPrime[i])

                count++;

 

        return count;

    }

}

109. Implement a Queue Using Stacks (Advanced)

Write a program to implement a queue using two stacks.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        MyQueue queue = new MyQueue();

        queue.Push(1);

        queue.Push(2);

        Console.WriteLine(queue.Pop()); // returns 1

        Console.WriteLine(queue.Peek()); // returns 2

        Console.WriteLine(queue.Empty()); // returns false

    }

 

    class MyQueue

    {

        private Stack<int> stack1 = new Stack<int>();

        private Stack<int> stack2 = new Stack<int>();

 

        public void Push(int x)

        {

            stack1.Push(x);

        }

 

        public int Pop()

        {

            if (stack2.Count == 0)

            {

                while (stack1.Count > 0)

                    stack2.Push(stack1.Pop());

            }

            return stack2.Pop();

        }

 

        public int Peek()

        {

            if (stack2.Count == 0)

            {

                while (stack1.Count > 0)

                    stack2.Push(stack1.Pop());

            }

            return stack2.Peek();

        }

 

        public bool Empty()

        {

            return stack1.Count == 0 && stack2.Count == 0;

        }

    }

}

110. Palindrome Linked List (Advanced)

Given a singly linked list, determine if it is a palindrome.

using System;

 

class Program

{

    class ListNode

    {

        public int val;

        public ListNode next;

        public ListNode(int val = 0, ListNode next = null)

        {

            this.val = val;

            this.next = next;

        }

    }

 

    static void Main()

    {

        ListNode head = new ListNode(1, new ListNode(2, new ListNode(2, new ListNode(1))));

        bool isPalindrome = IsPalindrome(head);

        Console.WriteLine(isPalindrome ? "Palindrome" : "Not Palindrome");

    }

 

    static bool IsPalindrome(ListNode head)

    {

        if (head == null) return true;

 

        // Find the middle of the list

        ListNode slow = head, fast = head;

        while (fast != null && fast.next != null)

        {

            slow = slow.next;

            fast = fast.next.next;

        }

 

        // Reverse the second half

        ListNode prev = null;

        while (slow != null)

        {

            ListNode next = slow.next;

            slow.next = prev;

            prev = slow;

            slow = next;

        }

 

        // Check if the first half and the reversed second half are the same

        while (prev != null)

        {

            if (head.val != prev.val)

                return false;

 

            head = head.next;

            prev = prev.next;

        }

 

        return true;

    }

}

 

 

111. Find the Intersection of Two Arrays (Beginner)

Given two arrays, write a function to return their intersection (i.e., common elements).

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        int[] nums1 = { 1, 2, 2, 1 };

        int[] nums2 = { 2, 2 };

        var intersection = Intersection(nums1, nums2);

        Console.WriteLine("Intersection: " + string.Join(", ", intersection));

    }

 

    static int[] Intersection(int[] nums1, int[] nums2)

    {

        HashSet<int> set1 = new HashSet<int>(nums1);

        HashSet<int> result = new HashSet<int>();

 

        foreach (int num in nums2)

        {

            if (set1.Contains(num))

            {

                result.Add(num);

            }

        }

 

        return new List<int>(result).ToArray();

    }

}

112. Find the Missing Number (Intermediate)

Given an array containing n distinct numbers taken from the range 1 to n + 1, find the one that is missing.

using System;

 

class Program

{

    static void Main()

    {

        int[] nums = { 3, 7, 1, 2, 8, 4, 5 };

        int missing = FindMissingNumber(nums);

        Console.WriteLine("Missing Number: " + missing);

    }

 

    static int FindMissingNumber(int[] nums)

    {

        int n = nums.Length + 1;

        int expectedSum = n * (n + 1) / 2;

        int actualSum = 0;

 

        foreach (int num in nums)

        {

            actualSum += num;

        }

 

        return expectedSum - actualSum;

    }

}

113. Maximal Square (Advanced)

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

using System;

 

class Program

{

    static void Main()

    {

        char[,] matrix = {

            { '1', '0', '1', '0', '0' },

            { '1', '0', '1', '1', '1' },

            { '1', '1', '1', '1', '1' },

            { '1', '0', '0', '1', '0' }

        };

        int maxSquareArea = MaximalSquare(matrix);

        Console.WriteLine("Maximal Square Area: " + maxSquareArea);

    }

 

    static int MaximalSquare(char[,] matrix)

    {

        int m = matrix.GetLength(0);

        int n = matrix.GetLength(1);

        int[,] dp = new int[m + 1, n + 1];

        int maxSideLength = 0;

 

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

        {

            for (int j = 1; j <= n; j++)

            {

                if (matrix[i - 1, j - 1] == '1')

                {

                    dp[i, j] = Math.Min(Math.Min(dp[i - 1, j], dp[i, j - 1]), dp[i - 1, j - 1]) + 1;

                    maxSideLength = Math.Max(maxSideLength, dp[i, j]);

                }

            }

        }

 

        return maxSideLength * maxSideLength;

    }

}

114. Count and Say (Intermediate)

The count-and-say sequence is a sequence of digit strings where each term is derived from the previous term by describing the count of each digit group. Write a program to generate the nth term of the sequence.

using System;

 

class Program

{

    static void Main()

    {

        int n = 4;

        string result = CountAndSay(n);

        Console.WriteLine("Count and Say (n=4): " + result);

    }

 

    static string CountAndSay(int n)

    {

        string result = "1";

 

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

        {

            StringBuilder current = new StringBuilder();

            char currentChar = result[0];

            int count = 1;

 

            for (int j = 1; j < result.Length; j++)

            {

                if (result[j] == currentChar)

                    count++;

                else

                {

                    current.Append(count).Append(currentChar);

                    currentChar = result[j];

                    count = 1;

                }

            }

 

            current.Append(count).Append(currentChar);

            result = current.ToString();

        }

 

        return result;

    }

}

115. Subarray Sum Equals K (Intermediate)

Given an array of integers and an integer k, return the total number of continuous subarrays whose sum equals k.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        int[] nums = { 1, 1, 1 };

        int k = 2;

        int count = SubarraySum(nums, k);

        Console.WriteLine("Subarray sum equals " + k + ": " + count);

    }

 

    static int SubarraySum(int[] nums, int k)

    {

        int count = 0;

        int sum = 0;

        Dictionary<int, int> sumDict = new Dictionary<int, int> { { 0, 1 } };

 

        foreach (int num in nums)

        {

            sum += num;

            if (sumDict.ContainsKey(sum - k))

                count += sumDict[sum - k];

 

            if (!sumDict.ContainsKey(sum))

                sumDict[sum] = 0;

 

            sumDict[sum]++;

        }

 

        return count;

    }

}

116. Spiral Matrix (Intermediate)

Given an m x n matrix, return all elements of the matrix in spiral order.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        int[,] matrix = {

            { 1, 2, 3 },

            { 4, 5, 6 },

            { 7, 8, 9 }

        };

 

        var spiralOrder = SpiralOrder(matrix);

        Console.WriteLine("Spiral Order: " + string.Join(", ", spiralOrder));

    }

 

    static List<int> SpiralOrder(int[,] matrix)

    {

        List<int> result = new List<int>();

        int top = 0, bottom = matrix.GetLength(0) - 1;

        int left = 0, right = matrix.GetLength(1) - 1;

 

        while (top <= bottom && left <= right)

        {

            // Traverse top row

            for (int i = left; i <= right; i++)

                result.Add(matrix[top, i]);

            top++;

 

            // Traverse right column

            for (int i = top; i <= bottom; i++)

                result.Add(matrix[i, right]);

            right--;

 

            // Traverse bottom row

            if (top <= bottom)

            {

                for (int i = right; i >= left; i--)

                    result.Add(matrix[bottom, i]);

                bottom--;

            }

 

            // Traverse left column

            if (left <= right)

            {

                for (int i = bottom; i >= top; i--)

                    result.Add(matrix[i, left]);

                left++;

            }

        }

 

        return result;

    }

}

117. Power of Four (Beginner)

Given an integer, write a program to determine if it is a power of four.

using System;

 

class Program

{

    static void Main()

    {

        int num = 16;

        bool isPowerOfFour = IsPowerOfFour(num);

        Console.WriteLine(isPowerOfFour ? "Power of Four" : "Not Power of Four");

    }

 

    static bool IsPowerOfFour(int num)

    {

        return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0;

    }

}

118. Roman to Integer (Beginner)

Write a program to convert a Roman numeral to an integer.

using System;

 

class Program

{

    static void Main()

    {

        string s = "IX";

        int result = RomanToInt(s);

        Console.WriteLine($"Roman numeral {s} to integer: {result}");

    }

 

    static int RomanToInt(string s)

    {

        int result = 0;

        Dictionary<char, int> romanValues = new Dictionary<char, int>

        {

            { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 },

            { 'C', 100 }, { 'D', 500 }, { 'M', 1000 }

        };

 

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

        {

            if (i + 1 < s.Length && romanValues[s[i]] < romanValues[s[i + 1]])

            {

                result -= romanValues[s[i]];

            }

            else

            {

                result += romanValues[s[i]];

            }

        }

 

        return result;

    }

}

119. Letter Combinations of a Phone Number (Advanced)

Given a string containing digits from 2 to 9, return all possible letter combinations that the number could represent.

using System;

using System.Collections.Generic;

 

class Program

{

    static void Main()

    {

        string digits = "23";

        var combinations = LetterCombinations(digits);

        Console.WriteLine("Combinations: " + string.Join(", ", combinations));

    }

 

    static List<string> LetterCombinations(string digits)

    {

        List<string> result = new List<string>();

        if (string.IsNullOrEmpty(digits))

            return result;

 

        string[] phoneMap = {

            "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"

        };

 

        Backtrack(digits, 0, "", result, phoneMap);

        return result;

    }

 

    static void Backtrack(string digits, int index, string current, List<string> result, string[] phoneMap)

    {

        if (index == digits.Length)

        {

            result.Add(current);

            return;

        }

 

        string letters = phoneMap[digits[index] - '0'];

        foreach (char letter in letters)

        {

            Backtrack(digits, index + 1, current + letter, result, phoneMap);

        }

    }

}

120. Kth Largest Element in an Array (Intermediate)

Find the kth largest element in an unsorted array.

using System;

using System.Linq;

 

class Program

{

    static void Main()

    {

        int[] nums = { 3, 2, 1, 5, 6, 4 };

        int k = 2;

        int kthLargest = FindKthLargest(nums, k);

        Console.WriteLine($"The {k}th largest element is {kthLargest}");

    }

 

    static int FindKthLargest(int[] nums, int k)

    {

        return nums.OrderByDescending(n => n).ElementAt(k - 1);

    }

}

 


Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced