Arrays are one of the first data structures every C# developer needs to master, and they show up constantly in real-world code: from simple lists of values to full 2D matrices.
This collection of 30 C# array exercises covers everything from basic declaration and traversal to classic algorithms like binary search, bubble sort, and Kadane’s algorithm.
Each exercise includes a Practice Problem, Purpose, Hint, and a full Solution with Explanation, so you build real intuition instead of just memorizing syntax.
Also, See: C# Exercises with 22 topic-wise sets and 620+ practice questions.
What You’ll Practice
- Fundamentals: Declaring, initializing, and traversing arrays.
- Manipulation: Insertion, deletion, rotation, and duplicate removal.
- Algorithms: Linear/binary search, bubble sort, and the two-sum problem.
- 2D Arrays: Matrix printing, addition, multiplication, and transposition.
+ Table Of Contents (30 Exercises)
Table of contents
- Exercise 1: Declare and Print
- Exercise 2: User Input Array
- Exercise 3: Reverse Print
- Exercise 4: Sum & Average
- Exercise 5: Array Copy
- Exercise 6: Find Maximum & Minimum
- Exercise 7: Linear Search
- Exercise 8: Count Occurrences
- Exercise 9: Even and Odd Separation
- Exercise 10: Find Second Largest
- Exercise 11: Remove Duplicates
- Exercise 12: Merge and Sort
- Exercise 13: Left Rotate
- Exercise 14: Rotate by N Positions
- Exercise 15: Insert an Element
- Exercise 16: Delete an Element
- Exercise 17: Frequency Count
- Exercise 18: Find the Mode
- Exercise 19: Missing Number
- Exercise 20: Check Subarray
- Exercise 21: Matrix Grid Print
- Exercise 22: Matrix Addition
- Exercise 23: Matrix Multiplication
- Exercise 24: Diagonal Sum
- Exercise 25: Transpose a Matrix
- Exercise 26: Bubble Sort Implementation
- Exercise 27: Binary Search
- Exercise 28: Two Sum Problem
- Exercise 29: Max Subarray Sum (Kadane’s Algorithm)
- Exercise 30: Jagged Array Total
Exercise 1: Declare and Print
Practice Problem: Create an array of 5 integers, initialize it with values, and print each value to the console.
Purpose: This exercise helps you practice the most basic array operations: declaring an array, initializing it with values, and iterating over it to display its contents.
Given Input: numbers = [10, 20, 30, 40, 50]
Expected Output:
10 20 30 40 50
▼ Hint
- Declare the array with
int[] numbers = { 10, 20, 30, 40, 50 };. - Use a
foreachloop to visit each element without needing to track an index. - Print each value inside the loop body using
Console.WriteLine().
▼ Solution & Explanation
Explanation:
int[] numbers = { 10, 20, 30, 40, 50 };: Declares an array and initializes it with five integer values in one step.foreach (int number in numbers): Iterates through every element in the array, assigning each value tonumberin turn.Console.WriteLine(number);: Prints the current element on its own line.
Exercise 2: User Input Array
Practice Problem: Prompt the user to enter the size of an array, take that many integer inputs to fill it, and display the final array.
Purpose: This exercise helps you practice creating an array whose size is determined at runtime, rather than being fixed in the code, and filling it using repeated console input.
Given Input: Size = 3, values 5, 10, 15
Expected Output: Array: 5, 10, 15
▼ Hint
- Read the array size first and convert it to an
intusingint.Parse(). - Use
new int[size]to create an array of that exact length. - Use a
forloop to prompt for and store each value, thenstring.Join()to print them all on one line.
▼ Solution & Explanation
Explanation:
int[] numbers = new int[size];: Creates an array sized exactly to match the value entered by the user.numbers[i] = int.Parse(Console.ReadLine());: Reads a value from the user and stores it at the current index during each loop iteration.string.Join(", ", numbers): Combines all array elements into a single comma-separated string for display.
Exercise 3: Reverse Print
Practice Problem: Write a program that reads n numbers into an array and prints them in reverse order.
Purpose: This exercise helps you practice reading a dynamically sized array and looping through it backwards using its index.
Given Input: n = 4, values 1, 2, 3, 4
Expected Output:
4 3 2 1
▼ Hint
- Read
nfirst, then create an array of that size and fill it in a loop. - Start a second loop at
numbers.Length - 1and count down to0. - Print each element using its index inside the reverse loop.
▼ Solution & Explanation
Explanation:
int[] numbers = new int[n];: Creates an array sized to hold exactlynvalues.for (int i = numbers.Length - 1; i >= 0; i--): Loops backwards from the last index down to the first.numbers[i]: Accesses the element at the current index, printing the array in reverse order.
Exercise 4: Sum & Average
Practice Problem: Calculate and display the sum and average of all elements in a double array.
Purpose: This exercise helps you practice accumulating a total from an array and then deriving a second statistic, the average, from that total.
Given Input: numbers = [10.5, 20.3, 5.2, 8.0]
Expected Output:
Sum = 44 Average = 11
▼ Hint
- Initialize a
double sum = 0;before the loop. - Use a
foreachloop to add each array element tosum. - Divide
sumbynumbers.Lengthto calculate the average.
▼ Solution & Explanation
Explanation:
sum += number;: Adds the current array element to the running total on each pass through the loop.sum / numbers.Length: Divides the total by the number of elements to compute the average.
Exercise 5: Array Copy
Practice Problem: Write a method to copy the elements of one integer array into another array of the same size.
Purpose: This exercise helps you practice writing a reusable method that operates on array parameters, reinforcing that arrays are passed by reference in C#.
Given Input: original = [1, 2, 3, 4, 5]
Expected Output: Copied Array: 1, 2, 3, 4, 5
▼ Hint
- Write a method that accepts two
int[]parameters: a source and a destination. - Loop through the source array by index, assigning each value to the same index in the destination array.
- In
Main, create the destination array with the same length as the source before calling the method.
▼ Solution & Explanation
Explanation:
static void CopyArray(int[] source, int[] destination): Defines a reusable method that transfers values from one array into another, element by element.destination[i] = source[i];: Copies the value at each index from the source array into the matching index of the destination array.int[] copy = new int[original.Length];: Creates the destination array with the same length as the source before the copy begins.
Exercise 6: Find Maximum & Minimum
Practice Problem: Find the largest and smallest element in an integer array without using built-in LINQ methods (like .Max()).
Purpose: This exercise helps you practice tracking running values manually as you iterate through an array, reinforcing the logic that built-in methods like .Max() perform internally.
Given Input: numbers = [23, 7, 45, 12, 89, 34]
Expected Output:
Maximum = 89 Minimum = 7
▼ Hint
- Start by assuming the first element is both the maximum and the minimum.
- As you loop through the rest of the array, update
maxwhenever you find a larger value. - Update
minwhenever you find a smaller value.
▼ Solution & Explanation
Explanation:
int max = numbers[0]; int min = numbers[0];: Initializes both trackers using the first element as a starting point.if (number > max): Updatesmaxwhenever a larger value is found while looping.if (number < min): Updatesminwhenever a smaller value is found while looping.
Exercise 7: Linear Search
Practice Problem: Ask the user for a number, search for it in an array, and return the index where it is found (or a message if it doesn’t exist).
Purpose: This exercise helps you practice implementing a linear search, checking each element in order until a match is found or the array is exhausted.
Given Input: numbers = [4, 8, 15, 16, 23, 42], user enters 23
Expected Output: 23 found at index 4
▼ Hint
- Read the user’s input with
Console.ReadLine()and convert it to anintusingint.Parse(). - Loop through the array with a regular
forloop so you have access to the index. - When a match is found, store the index and stop searching with
break.
▼ Solution & Explanation
Explanation:
int index = -1;: Starts with a sentinel value that indicates the number has not been found yet.if (numbers[i] == target): Compares each element with the target value, and if it matches, records the index and exits the loop withbreak.if (index != -1): Checks whether a match was actually found before printing the success message.
Exercise 8: Count Occurrences
Practice Problem: Write a program to count the total number of times a specific element appears in an array.
Purpose: This exercise helps you practice using a counter variable alongside a loop to tally how often a condition is met across an entire array.
Given Input: numbers = [2, 5, 2, 8, 2, 9, 5], target = 2
Expected Output: 2 appears 3 times in the array.
▼ Hint
- Initialize a
count = 0;before the loop. - Use a
foreachloop to check every element against the target value. - Increase
countby 1 every time a match is found.
▼ Solution & Explanation
Explanation:
int count = 0;: Initializes the counter before the loop starts.if (number == target): Checks whether the current array element matches the value being counted.count++;: Increases the counter by 1 each time a match is found.
Exercise 9: Even and Odd Separation
Practice Problem: Take an array of integers and separate them into two distinct arrays: one for even numbers and one for odd numbers.
Purpose: This exercise helps you practice a two-pass approach to array processing: counting matches first to size a new array correctly, then filling it in a second pass.
Given Input: numbers = [12, 7, 18, 3, 9, 24, 5]
Expected Output:
Even Numbers: 12, 18, 24 Odd Numbers: 7, 3, 9, 5
▼ Hint
- Make a first pass through the array just to count how many even and odd numbers there are.
- Use those counts to create two arrays of the exact right size.
- Make a second pass to fill each array, tracking a separate index for each one as you go.
▼ Solution & Explanation
Explanation:
- First loop: Counts how many even and odd numbers are in the array, without storing them yet.
int[] evenNumbers = new int[evenCount];: Creates an array sized to hold exactly the number of even values found.- Second loop: Places each number into the correct array, using a separate index counter for evens and odds so each value lands in the next open slot.
Exercise 10: Find Second Largest
Practice Problem: Write a program to find the second largest element in an array without sorting it first.
Purpose: This exercise helps you practice tracking two running values at once while looping through an array, a step up in complexity from a simple maximum search.
Given Input: numbers = [12, 45, 2, 41, 31, 10, 8, 6, 4]
Expected Output: Second Largest = 41
▼ Hint
- Track two variables,
largestandsecondLargest, initialized to a very small value likeint.MinValue. - If a number is greater than
largest, move the currentlargestintosecondLargestbefore updatinglargest. - If a number falls between
secondLargestandlargest, update onlysecondLargest.
▼ Solution & Explanation
Explanation:
if (number > largest): When a new overall largest value is found, the previouslargestis shifted down intosecondLargestbeforelargestis updated.else if (number > secondLargest && number < largest): Handles values that are not the biggest overall but are still bigger than the current second-largest.int.MinValue: Used as a safe starting point so that any real number in the array will be greater than the initial values.
Exercise 11: Remove Duplicates
Practice Problem: Write a program to remove all duplicate elements from an array, resulting in an array of unique values.
Purpose: This exercise helps you practice checking whether a value has already been collected before adding it, a common step in data cleaning tasks.
Given Input: numbers = [1, 2, 2, 3, 4, 4, 5, 1]
Expected Output: Unique Numbers: 1, 2, 3, 4, 5
▼ Hint
- Create a temporary array the same size as the original to hold unique values as they are found.
- For each number, scan the portion of the temporary array filled so far to check if it is already present.
- If it is not found, add it and increase a counter; once done, copy only the filled portion into a final, correctly sized array.
▼ Solution & Explanation
Explanation:
int[] temp = new int[numbers.Length];: Creates a working array large enough to hold every element in the worst case where none are duplicates.- Inner
forloop: Checks only the portion oftempfilled so far to see if the current number has already been recorded. Array.Copy(temp, uniqueNumbers, uniqueCount);: Copies just the filled portion oftempinto a new array sized exactly to the number of unique values found.
Exercise 12: Merge and Sort
Practice Problem: Merge two unsorted arrays of different sizes into a third array, then sort the final array in ascending order.
Purpose: This exercise helps you practice combining two arrays into a single new array and using a built-in sorting method to order the result.
Given Input: array1 = [5, 3, 8], array2 = [9, 1, 4, 2]
Expected Output: Merged and Sorted: 1, 2, 3, 4, 5, 8, 9
▼ Hint
- Create a merged array with a length equal to the sum of both array lengths.
- Use
Array.Copy()twice to place each source array into the correct section of the merged array. - Call
Array.Sort()on the merged array to put it in ascending order.
▼ Solution & Explanation
Explanation:
Array.Copy(array1, 0, merged, 0, array1.Length);: Copies all ofarray1into the start ofmerged.Array.Copy(array2, 0, merged, array1.Length, array2.Length);: Copies all ofarray2intomerged, starting right after wherearray1‘s values ended.Array.Sort(merged);: Sorts the combined array in place, arranging all elements in ascending order.
Exercise 13: Left Rotate
Practice Problem: Rotate an array to the left by one position (e.g., [1, 2, 3] becomes [2, 3, 1]).
Purpose: This exercise helps you practice shifting array elements while preserving the value that gets pushed off the front, a foundational step toward more general rotation logic.
Given Input: numbers = [1, 2, 3, 4, 5]
Expected Output: Rotated: 2, 3, 4, 5, 1
▼ Hint
- Save the first element in a temporary variable before it gets overwritten.
- Loop through the array, shifting each element one position to the left.
- Place the saved first element into the last position after the shifting loop finishes.
▼ Solution & Explanation
Explanation:
int first = numbers[0];: Saves the first element so it is not lost once it gets overwritten.numbers[i] = numbers[i + 1];: Shifts every element one position to the left by copying the next value into the current position.numbers[numbers.Length - 1] = first;: Places the originally saved first element into the now-empty last position.
Exercise 14: Rotate by N Positions
Practice Problem: Write a method that rotates an array to the right by k steps, where k is a user-defined integer.
Purpose: This exercise helps you practice a more general rotation formula using the modulus operator, avoiding the need to loop one step at a time.
Given Input: numbers = [1, 2, 3, 4, 5], k = 2
Expected Output: Rotated: 4, 5, 1, 2, 3
▼ Hint
- Create a new array of the same length to hold the rotated result.
- For each element at index
i, its new position is(i + k) % numbers.Length. - The modulus operator wraps indexes that go past the end of the array back around to the beginning.
▼ Solution & Explanation
Explanation:
static int[] RotateRight(int[] numbers, int k): Defines a reusable method that takes the array and the rotation amount, returning a new rotated array.rotated[(i + k) % numbers.Length] = numbers[i];: Calculates each element’s new position using the modulus operator, so positions that would go past the end wrap back to the start.
Exercise 15: Insert an Element
Practice Problem: Insert a new value at a specific index in an array, shifting the subsequent elements to the right.
Purpose: This exercise helps you practice building a new, larger array while carefully preserving the original element order around the insertion point.
Given Input: numbers = [10, 20, 30, 40], insert 25 at index 2
Expected Output: Result: 10, 20, 25, 30, 40
▼ Hint
- Create a new array with one more slot than the original.
- Copy the elements before the insertion index directly across.
- Place the new value at the insertion index, then copy the remaining original elements one position further to the right.
▼ Solution & Explanation
Explanation:
- First loop: Copies all elements before the insertion index straight across into the new array, unchanged.
result[insertIndex] = newValue;: Places the new value at the requested position in the new array.- Second loop: Copies the remaining original elements into the new array, shifted one position to the right to make room for the inserted value.
Exercise 16: Delete an Element
Practice Problem: Delete an element at a desired position from an array and shift the remaining elements to fill the gap.
Purpose: This exercise helps you practice building a new, smaller array by skipping the removed element and shifting the elements that follow it.
Given Input: numbers = [10, 20, 30, 40, 50], delete the element at index 2
Expected Output: Result: 10, 20, 40, 50
▼ Hint
- Create a new array with one fewer slot than the original.
- Copy the elements before the deletion index directly across.
- Copy the elements after the deletion index into the new array, shifted one position to the left to close the gap.
▼ Solution & Explanation
Explanation:
- First loop: Copies all elements before the deletion index straight across into the new, smaller array.
- Second loop: Copies the elements after the deletion index into the new array, shifted one position to the left so the removed element leaves no gap.
Exercise 17: Frequency Count
Practice Problem: Count the frequency of each element in an array and display the results (e.g., “Element 5 appears 3 times”).
Purpose: This exercise helps you practice using nested loops together with a tracking array, so each unique value is only reported once even if it repeats multiple times.
Given Input: numbers = [5, 3, 5, 2, 3, 5, 8]
Expected Output:
Element 5 appears 3 times Element 3 appears 2 times Element 2 appears 1 times Element 8 appears 1 times
▼ Hint
- Use a
bool[] countedarray the same size asnumbersto track which indexes have already been reported. - For each index not yet counted, use a nested loop to find and count every matching value later in the array.
- Mark each matching index as counted so it is not reported again later.
▼ Solution & Explanation
Explanation:
if (counted[i]) continue;: Skips an index if it was already counted as a duplicate of an earlier element.- Inner
forloop: Searches the rest of the array for matches, incrementingcountand marking each match as counted. Console.WriteLine($"Element {numbers[i]} appears {count} times");: Reports the final tally for that value exactly once.
Exercise 18: Find the Mode
Practice Problem: Find the element that appears most frequently in an array.
Purpose: This exercise helps you practice extending a frequency-counting approach to track the single most common value while scanning the array.
Given Input: numbers = [4, 8, 4, 2, 8, 4, 9]
Expected Output: Mode = 4 (appears 3 times)
▼ Hint
- For each element, use a nested loop to count how many times it appears in the whole array.
- Keep track of the highest count seen so far, along with the value that produced it.
- Update the tracked mode and its count only when a higher frequency is found.
▼ Solution & Explanation
Explanation:
- Inner
forloop: Counts how many times the current element appears anywhere in the array. if (count > maxCount): Updates the tracked mode only when a new highest frequency is found, so ties keep the first value encountered.
Exercise 19: Missing Number
Practice Problem: Given an array containing n-1 unique integers in the range of 1 to n, find the one missing number.
Purpose: This exercise helps you practice a mathematical shortcut, using the formula for the sum of consecutive integers instead of manually searching for the gap.
Given Input: n = 6, numbers = [1, 2, 4, 5, 6]
Expected Output: Missing Number = 3
▼ Hint
- The sum of all integers from
1toncan be calculated directly withn * (n + 1) / 2, without looping. - Add up the actual values in the array to get the actual sum.
- The missing number is simply the expected sum minus the actual sum.
▼ Solution & Explanation
Explanation:
n * (n + 1) / 2: Calculates what the sum of every integer from 1 tonwould be if none were missing.actualSum += number;: Adds up the values that are actually present in the array.expectedSum - actualSum: The difference between the two sums reveals exactly which number is missing.
Exercise 20: Check Subarray
Practice Problem: Write a program to check if one array is a subset of another array.
Purpose: This exercise helps you practice using nested loops to verify that every element of one array can be found somewhere in another, regardless of order.
Given Input: mainArray = [1, 2, 3, 4, 5, 6], subsetArray = [2, 4, 6]
Expected Output: The second array is a subset of the first array.
▼ Hint
- For each element in
subsetArray, searchmainArrayto see if that value exists anywhere in it. - If any element from
subsetArraycannot be found, the check fails immediately. - Use a
boolflag that starts astrueand is only set tofalseif a missing element is found.
▼ Solution & Explanation
Explanation:
- Inner
foreachloop: SearchesmainArrayfor the currentsubsetArrayelement, settingfoundtotrueif it turns up. if (!found) { isSubset = false; break; }: As soon as one element cannot be located, the overall check fails and the search stops early.
Exercise 21: Matrix Grid Print
Practice Problem: Declare a 3×3 2D array (matrix), fill it with numbers, and display it as a properly formatted grid.
Purpose: This exercise helps you practice declaring and iterating over a 2D array using nested loops, along with formatting output so it visually resembles a grid.
Given Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Expected Output:
1 2 3 4 5 6 7 8 9
▼ Hint
- Declare the matrix with
int[,] matrix = new int[3, 3] { ... };, using commas to separate rows. - Use two nested
forloops, one for rows and one for columns, to visit every cell. - Use a format specifier like
{value,4}inside string interpolation to right-align each number for a clean grid look, and print a new line after each row.
▼ Solution & Explanation
Explanation:
int[,] matrix = new int[3, 3] { ... };: Declares a two-dimensional array with 3 rows and 3 columns, initialized with values.- Nested
forloops: The outer loop moves through each row while the inner loop moves through each column within that row. {matrix[row, col],4}: Accesses the value at the given row and column, right-aligning it within 4 characters for a tidy grid layout.
Exercise 22: Matrix Addition
Practice Problem: Read two 2D matrices of the same dimensions and calculate their sum.
Purpose: This exercise helps you practice performing element-wise operations across two matrices using matching row and column indexes.
Given Input: matrixA = [[1, 2], [3, 4]], matrixB = [[5, 6], [7, 8]]
Expected Output:
6 8 10 12
▼ Hint
- Create a result matrix with the same dimensions as the two input matrices.
- Use nested loops to visit every cell, adding the corresponding values from
matrixAandmatrixB. - Store each sum in the same row and column position in the result matrix.
▼ Solution & Explanation
Explanation:
result[row, col] = matrixA[row, col] + matrixB[row, col];: Adds the values from both matrices at the same position and stores the total in the result matrix.- Second set of nested loops: Iterates over the completed result matrix purely to print it in grid form.
Exercise 23: Matrix Multiplication
Practice Problem: Implement matrix multiplication for two compatible 2D arrays.
Purpose: This exercise helps you practice a three-level nested loop, where each result cell is calculated as the sum of products across a shared dimension.
Given Input: matrixA = [[1, 2], [3, 4]], matrixB = [[5, 6], [7, 8]]
Expected Output:
19 22 43 50
▼ Hint
- Each cell in the result is the sum of
matrixA[row, k] * matrixB[k, col]for every validk. - You will need three nested loops: one for the row, one for the column, and one for the shared dimension used in the summation.
- Initialize each result cell to
0before accumulating the products into it.
▼ Solution & Explanation
Explanation:
- Innermost
forloop: Sums the products of matching elements from a row ofmatrixAand a column ofmatrixB. result[row, col] = sum;: Stores the completed dot product as a single value in the result matrix.
Exercise 24: Diagonal Sum
Practice Problem: Calculate the sum of the primary (main) and secondary diagonals of a square matrix.
Purpose: This exercise helps you practice recognizing index patterns within a 2D array, since both diagonals can be reached with a single loop and the right index formula.
Given Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Expected Output:
Primary Diagonal Sum = 15 Secondary Diagonal Sum = 15
▼ Hint
- The primary diagonal always uses matching row and column indexes:
matrix[i, i]. - The secondary diagonal uses
matrix[i, size - 1 - i], wheresizeis the number of rows or columns. - A single loop from
0tosize - 1can accumulate both sums at once.
▼ Solution & Explanation
Explanation:
matrix.GetLength(0): Returns the number of rows in the matrix, used here as the size of the square matrix.matrix[i, i]: Accesses the primary diagonal, where the row and column index are always equal.matrix[i, size - 1 - i]: Accesses the secondary diagonal, where the column index decreases as the row index increases.
Exercise 25: Transpose a Matrix
Practice Problem: Write a program to find and display the transpose of a given 2D matrix (swap rows with columns).
Purpose: This exercise helps you practice building a new matrix with swapped dimensions, reinforcing how row and column indexes relate to each other.
Given Input: matrix = [[1, 2, 3], [4, 5, 6]] (2 rows, 3 columns)
Expected Output:
1 4 2 5 3 6
▼ Hint
- The transposed matrix will have its row and column counts swapped compared to the original.
- Use
GetLength(0)andGetLength(1)to read the original matrix’s row and column counts. - When copying values, assign
transposed[col, row] = matrix[row, col];to flip each position.
▼ Solution & Explanation
Explanation:
int[,] transposed = new int[cols, rows];: Creates the new matrix with its dimensions swapped compared to the original.transposed[col, row] = matrix[row, col];: Places each original value into its mirrored position, effectively swapping rows and columns.
Exercise 26: Bubble Sort Implementation
Practice Problem: Sort an array of integers in ascending order by manually implementing the Bubble Sort algorithm.
Purpose: This exercise helps you practice implementing a classic sorting algorithm from scratch, repeatedly swapping adjacent out-of-order elements until the array is sorted.
Given Input: numbers = [5, 2, 9, 1, 5, 6]
Expected Output: Sorted: 1, 2, 5, 5, 6, 9
▼ Hint
- Use a nested loop: the outer loop controls how many passes are made, and the inner loop compares neighboring elements.
- If two neighboring elements are out of order, swap them using a temporary variable.
- Each full pass moves the next-largest unsorted value into its correct place at the end of the array.
▼ Solution & Explanation
Explanation:
- Outer loop: Repeats the sorting pass enough times to guarantee every element ends up in its correct position.
if (numbers[j] > numbers[j + 1]): Compares two neighboring elements to see if they are out of order.int temp = numbers[j]; ...: Swaps the two elements using a temporary variable when they are found to be in the wrong order.
Exercise 27: Binary Search
Practice Problem: Implement the Binary Search algorithm to find an element in a pre-sorted array.
Purpose: This exercise helps you practice a much faster search technique than linear search, repeatedly narrowing the search range in half instead of checking every element.
Given Input: sortedNumbers = [2, 5, 8, 12, 16, 23, 38, 45, 56, 72, 91], target = 23
Expected Output: 23 found at index 5
▼ Hint
- Track a
lowandhighboundary, starting at the first and last valid indexes. - On each pass, check the middle element; if it’s too small, move
lowup, and if it’s too large, movehighdown. - Binary Search only works correctly on an array that is already sorted.
▼ Solution & Explanation
Explanation:
int mid = (low + high) / 2;: Calculates the middle index of the current search range.else if (sortedNumbers[mid] < target) low = mid + 1;: If the middle value is too small, the search range is narrowed to the upper half.else high = mid - 1;: If the middle value is too large, the search range is narrowed to the lower half.
Exercise 28: Two Sum Problem
Practice Problem: Given an array of integers and a target sum, find the indices of the two numbers that add up to that target.
Purpose: This exercise helps you practice checking every possible pair of elements using nested loops, a classic beginner approach to this well-known problem.
Given Input: numbers = [2, 7, 11, 15], target = 9
Expected Output: Indices: 0, 1
▼ Hint
- Use an outer loop to fix the first number, and an inner loop starting right after it to check every possible second number.
- Check whether the two numbers at the current pair of indexes add up to the target.
- Once a matching pair is found, print both indexes and stop searching.
▼ Solution & Explanation
Explanation:
- Outer loop: Fixes the first number in the pair being tested.
- Inner loop starting at
i + 1: Checks every later number in the array against the fixed first number, avoiding checking the same pair twice. if (numbers[i] + numbers[j] == target): Confirms whether the current pair adds up to the target value.
Exercise 29: Max Subarray Sum (Kadane’s Algorithm)
Practice Problem: Find the contiguous subarray within a one-dimensional numerical array which has the largest sum.
Purpose: This exercise helps you practice Kadane’s Algorithm, an efficient technique that finds the maximum subarray sum in a single pass through the array.
Given Input: numbers = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Expected Output: Maximum Subarray Sum = 6
▼ Hint
- Track two values as you loop: the best sum ending exactly at the current position, and the best sum found anywhere so far.
- At each element, decide whether to extend the current subarray or start a fresh one, whichever produces a larger sum.
- Update the overall best sum whenever the current running sum exceeds it.
▼ Solution & Explanation
Explanation:
Math.Max(numbers[i], maxEndingHere + numbers[i]): Decides whether it’s better to start a new subarray at the current element or extend the previous one.Math.Max(maxSoFar, maxEndingHere): Keeps track of the best sum found across the entire array so far, even if the current running sum later drops.
Exercise 30: Jagged Array Total
Practice Problem: Create a jagged array (an array of arrays) with varying row lengths, populate it, and calculate the total sum of all elements across all rows.
Purpose: This exercise helps you practice working with a jagged array, where each row can have a different length, unlike a rectangular 2D array.
Given Input: row 0 = [1, 2, 3], row 1 = [4, 5], row 2 = [6, 7, 8, 9]
Expected Output: Total Sum = 45
▼ Hint
- Declare the outer array with
int[][] jaggedArray = new int[3][];, then assign each row its own array separately. - Use a nested
foreachloop: the outer loop visits each row, and the inner loop visits each value within that row. - Since rows can have different lengths, avoid assuming they are all the same size.
▼ Solution & Explanation
Explanation:
int[][] jaggedArray = new int[3][];: Creates an outer array of 3 rows, where each row is itself a separate array that can be any length.jaggedArray[0] = new int[] { 1, 2, 3 };: Assigns a specific array to the first row, independent of the sizes of the other rows.- Nested
foreachloop: The outer loop iterates over each row array, and the inner loop iterates over the values within that row, accumulating everything intototal.

Leave a Reply