Arrays
Arrays
Certainly! Arrays in C# are a fundamental data structure used to store a fixed-size sequence of elements of the same
type. They provide a way to work with multiple values efficiently. Here's a detailed explanation along with example
programs.
An array is a collection of variables of the same DATA type that are stored in contiguous memory locations. In C#,
arrays are zero-based, meaning the index of the first element is 0.
You declare an array by specifying the type of elements it will hold, followed by square brackets. For example:
```csharp
int[] numbers;
```
This declaration tells the compiler that `numbers` will be an array of integers, but it does not allocate memory yet.
To initialize an array, you use the `new` keyword and specify the number of elements the array will hold:
```csharp
numbers = new int[5];
```
This creates an array with 5 elements, all initialized to the default value for integers (0).
```csharp
int[] numbers = new int[5]; // all elements initialized to 0
```
```csharp
int[] numbers = { 1, 2, 3, 4, 5 };
```
```csharp
int[] numbers = { 1, 2, 3, 4, 5 };
Console.WriteLine(numbers[0]); // Output: 1
Console.WriteLine(numbers[1]); // Output: 2
```
```csharp
int[] numbers = { 1, 2, 3, 4, 5 };
numbers[2] = 10;
Console.WriteLine(numbers[2]); // Output: 10
```
You can use a `for` loop or `foreach` loop to iterate over arrays:
```csharp
int[] numbers = { 1, 2, 3, 4, 5 };
```csharp
int[] numbers = { 1, 2, 3, 4, 5 };
```csharp
int[,] matrix = new int[3, 3];
```
```csharp
int[,] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
```csharp
Console.WriteLine(matrix[0, 0]); // Output: 1
Console.WriteLine(matrix[1, 1]); // Output: 5
```
```csharp
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();
}
```
Jagged arrays are arrays of arrays, where each sub-array can have a different length.
``` csharp
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4, 5 };
jaggedArray[2] = new int[] { 6 };
```
```csharp
for (int i = 0; i < jaggedArray.Length; i++)
{
for (int j = 0; j < jaggedArray[i].Length; j++)
{
ARRAYS
Console.Write(jaggedArray[i][j] + " ");
}
Console.WriteLine();
}
```
#### `Array.Length`
```csharp
int[] numbers = { 1, 2, 3, 4, 5 };
Console.WriteLine(numbers.Length); // Output: 5
```
#### `Array.Sort`
```csharp
int[] numbers = { 5, 3, 1, 4, 2 };
Array.Sort(numbers);
foreach (int number in numbers)
{
Console.Write(number + " ");
}
// Output: 1 2 3 4 5
```
#### `Array.Reverse`
```csharp
int[] numbers = { 1, 2, 3, 4, 5 };
Array.Reverse(numbers);
foreach (int number in numbers)
{
Console.Write(number + " ");
}
// Output: 5 4 3 2 1
```
#### `Array.Copy`
```csharp
int[] source = { 1, 2, 3, 4, 5 };
int[] destination = new int[3];
Array.Copy(source, 1, destination, 0, 3);
foreach (int number in destination)
ARRAYS
{
Console.Write(number + " ");
}
// Output: 2 3 4
```
### Conclusion
Arrays are a versatile and efficient way to manage collections of data in C#. Understanding how to declare, initialize,
access, and manipulate arrays is crucial for effective programming in C#. As you work with arrays, keep in mind their
fixed size and the fact that their elements are stored contiguously in memory, which impacts performance and memory
usage.
Each program covers various aspects of array usage, from basic operations to more advanced features like
multidimensional and jagged arrays.
```csharp
using System;
class Program
{
static void Main()
{
// Declaring and initializing an array
int[] numbers = { 10, 20, 30, 40, 50 };
```csharp
using System;
class Program
{
static void Main()
{
ARRAYS
int[] numbers = { 1, 2, 3, 4, 5 };
// Modifying elements
numbers[2] = 100;
```csharp
using System;
class Program
{
static void Main()
{
int[] numbers = { 5, 10, 15, 20, 25 };
```csharp
using System;
class Program
{
static void Main()
{
int[] numbers = { 7, 14, 21, 28 };
```csharp
using System;
class Program
{
static void Main()
{
// Declaring and initializing a 2D array
int[,] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
```csharp
using System;
class Program
{
static void Main()
{
// Declaring and initializing a jagged array
int[][] jaggedArray = {
new int[] { 1, 2, 3 },
new int[] { 4, 5 },
new int[] { 6, 7, 8, 9 }
};
```csharp
using System;
class Program
{
static void Main()
{
int[] numbers = { 3, 1, 4, 1, 5, 9, 2, 6, 5 };
```csharp
using System;
class Program
{
static void Main()
{
int[] source = { 10, 20, 30, 40, 50 };
ARRAYS
int[] destination = new int[3];
```csharp
using System;
class Program
{
static void Main()
{
int[] numbers = { 5, 1, 9, 7, 6, 3, 2 };
These programs should provide a good starting point for understanding how to work with arrays in C#. They cover a
ARRAYS
1. Find Pairs of Integers in an Array that Sum up to a Target
Explanation
To find pairs of integers in an array that sum up to a given target, we can use a hash set to track the numbers we have
seen so far. For each number, we check if its complement (target - number) exists in the set.
C# Code
csharp
using System;
using System.Collections.Generic;
class Program
{
public static void FindPairs(int[] arr, int target)
{
HashSet<int> seen = new HashSet<int>();
foreach (var num in arr)
{
int complement = target - num;
if (seen.Contains(complement))
{
Console.WriteLine($"Pair found: ({num}, {complement})");
}
seen.Add(num);
}
}
Steps:
1. Initialize a hash set to store seen numbers.
2. Iterate through each number in the array.
3. Calculate the complement of the current number.
4. If the complement is found in the set, print the pair.
5. Add the current number to the set.
ARRAYS
2. Remove Duplicates from a Sorted Array
Explanation
Since the array is sorted, duplicates will be adjacent. We can use a two-pointer technique to overwrite duplicates in
place.
C# Code
csharp
using System;
class Program
{
public static int RemoveDuplicates(int[] nums)
{
if (nums.Length == 0) return 0;
Steps:
1. Check if the array is empty.
2. Initialize a pointer j for unique elements.
3. Loop through the array starting from index 1.
4. If a new unique element is found, increment j and assign it.
5. Return j + 1 as the count of unique elements.
ARRAYS
3. Rotate an Array to the Right by a Given Number of Steps
Explanation
To rotate an array to the right by k steps efficiently, we can reverse sections of the array.
C# Code
csharp
using System;
class Program
{
public static void Rotate(int[] nums, int k)
{
k %= nums.Length; // Handle cases where k > length of array
Array.Reverse(nums);
Array.Reverse(nums, 0, k);
Array.Reverse(nums, k, nums.Length - k);
}
Steps:
1. Normalize k to be within bounds of the array length.
2. Reverse the entire array.
3. Reverse the first k elements.
4. Reverse the remaining elements.
C# Code
csharp
using System;
class Program
{
ARRAYS
public static int[] MergeArrays(int[] arr1, int[] arr2)
{
int[] merged = new int[arr1.Length + arr2.Length];
int i = 0, j = 0, k = 0;
return merged;
}
Steps:
1. Create an array to hold merged results.
2. Use pointers to traverse both arrays and compare elements.
3. Fill in the merged array with smaller elements until one array is exhausted.
4. Append any remaining elements from either array.
C# Code
csharp
using System;
class Program
{
public static int FindMissingNumber(int[] nums)
{
int n = nums.Length + 1;
int totalSum = n * (n + 1) / 2;
ARRAYS
int arraySum = 0;
Steps:
1. Calculate expected total sum using formula n(n+1)22n(n+1) .
2. Calculate actual sum from the given array.
3. The missing number is given by totalSum−arraySumtotalSum−arraySum .
C# Code
csharp
using System;
class Program
{
public static int MaxSubArray(int[] nums)
{
int maxCurrent = maxGlobal = nums[0];
return maxGlobal;
}
Steps:
1. Initialize current and global maximums with the first element.
2. Iterate through each element and update current maximum.
3. Update global maximum if current exceeds it.
C# Code
csharp
using System;
using System.Collections.Generic;
class Program
{
public static bool ContainsDuplicate(int[] nums)
{
HashSet<int> set = new HashSet<int>();
return false;
}
Steps:
1. Initialize a hash set to store numbers.
2. Iterate through each number and try adding it to the set.
3. If adding fails (the number already exists), return true for duplicates.
ARRAYS
8. Calculate the Product of Array Except Self
Explanation
This approach calculates products on both sides of each element without using division.
C# Code
csharp
using System;
class Program
{
public static int[] ProductExceptSelf(int[] nums)
{
int n = nums.Length;
int[] output = new int[n];
output[0] = 1;
int rightProduct = 1;
return output;
}
Steps:
1. Create an output array initialized to store products.
2. First pass: calculate products of all elements before each index.
3. Second pass: multiply by products of all elements after each index.
ARRAYS
9. Move Zeroes to the End of an Array
Explanation
We can move zeroes by maintaining a pointer for non-zero elements and shifting them forward.
C# Code
csharp
using System;
class Program
{
public static void MoveZeroes(int[] nums)
{
int lastNonZeroIndex = 0;
Steps:
1. Initialize a pointer for tracking non-zero positions.
2. Loop through the array and shift non-zero elements forward.
3. Fill remaining positions with zeroes after all non-zero elements have been moved.
class Program
{
public static int FindPeakElement(int[] nums)
{
for (int i=0; i<nums.Length; i++)
{
if ((i ==0 || nums[i-1]<nums[i]) &&
(i ==nums.Length-1 || nums[i]>nums[i+1]))
return i;
}
return -1; // In case no peak is found
}
Steps:
1. Loop through each element in the array.
2. Check if it is greater than its neighbors or at boundaries.
3. Return index if peak condition is satisfied.
These implementations cover all specified problems using C# programming language with clear explanations and
examples tailored for understanding and learning purposes.
Share
Rewrite