0% found this document useful (0 votes)
29 views18 pages

Arrays

arrays

Uploaded by

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

Arrays

arrays

Uploaded by

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

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.

### 1. Introduction to Arrays

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.

#### Key Points:


- Arrays are of fixed size; their size cannot be changed after creation.
- Elements are accessed using an index.
- Arrays can store any type of data, including primitives, objects, and other arrays.

### 2. Declaring and Initializing Arrays

#### 2.1 Declaration

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.

#### 2.2 Initialization

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

#### 2.3 Declaration and Initialization in One Step

You can also declare and initialize an array in a single line:

```csharp
int[] numbers = new int[5]; // all elements initialized to 0
```

Alternatively, you can initialize the array with specific values:

```csharp
int[] numbers = { 1, 2, 3, 4, 5 };
```

### 3. Accessing Array Elements

Array elements are accessed using an index. Indexes start at 0.


ARRAYS

```csharp
int[] numbers = { 1, 2, 3, 4, 5 };
Console.WriteLine(numbers[0]); // Output: 1
Console.WriteLine(numbers[1]); // Output: 2
```

### 4. Modifying Array Elements

You can modify array elements by assigning new values to them:

```csharp
int[] numbers = { 1, 2, 3, 4, 5 };
numbers[2] = 10;
Console.WriteLine(numbers[2]); // Output: 10
```

### 5. Iterating Over Arrays

You can use a `for` loop or `foreach` loop to iterate over arrays:

#### Using a `for` Loop

```csharp
int[] numbers = { 1, 2, 3, 4, 5 };

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


{
Console.WriteLine(numbers[i]);
}
```

#### Using a `foreach` Loop

```csharp
int[] numbers = { 1, 2, 3, 4, 5 };

foreach (int number in numbers)


{
Console.WriteLine(number);
}
```

### 6. Multidimensional Arrays

C# supports multidimensional arrays, such as 2D arrays (matrices).

#### Declaring a 2D Array

```csharp
int[,] matrix = new int[3, 3];
```

This creates a 3x3 matrix.


ARRAYS

#### Initializing a 2D Array

```csharp

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

#### Accessing Elements in a 2D Array

```csharp
Console.WriteLine(matrix[0, 0]); // Output: 1
Console.WriteLine(matrix[1, 1]); // Output: 5
```

#### Iterating Over a 2D Array

```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();
}
```

### 7. Jagged Arrays

Jagged arrays are arrays of arrays, where each sub-array can have a different length.

#### Declaring and Initializing a Jagged Array

``` csharp
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4, 5 };
jaggedArray[2] = new int[] { 6 };
```

#### Accessing and Iterating Over a Jagged Array

```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();
}
```

### 8. Common Array Methods

#### `Array.Length`

Gets the number of elements in the array.

```csharp
int[] numbers = { 1, 2, 3, 4, 5 };
Console.WriteLine(numbers.Length); // Output: 5
```

#### `Array.Sort`

Sorts the elements of the array.

```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`

Reverses the order of the elements in the array.

```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`

Copies a range of elements from one array to another.

```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.

### 1. **Basic Array Operations**

#### Program 1: Array Declaration, Initialization, and Access

```csharp
using System;

class Program
{
static void Main()
{
// Declaring and initializing an array
int[] numbers = { 10, 20, 30, 40, 50 };

// Accessing array elements


Console.WriteLine("Array elements:");
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine($"Element at index {i}: {numbers[i]}");
}
}
}
```

#### Program 2: Modifying Array Elements

```csharp
using System;

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

// Modifying elements
numbers[2] = 100;

Console.WriteLine("Modified array elements:");


foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
```

### 2. **Array Iteration**

#### Program 3: Iterating with `for` Loop

```csharp
using System;

class Program
{
static void Main()
{
int[] numbers = { 5, 10, 15, 20, 25 };

Console.WriteLine("Using for loop:");


for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
}
}
```

#### Program 4: Iterating with `foreach` Loop

```csharp
using System;

class Program
{
static void Main()
{
int[] numbers = { 7, 14, 21, 28 };

Console.WriteLine("Using foreach loop:");


foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
ARRAYS
```

### 3. **Multidimensional Arrays**

#### Program 5: 2D Array Example

```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 }
};

Console.WriteLine("2D Array elements:");


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();
}
}
}
```

### 4. **Jagged Arrays**

#### Program 6: Jagged Array Example

```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 }
};

Console.WriteLine("Jagged Array elements:");


for (int i = 0; i < jaggedArray.Length; i++)
{
ARRAYS
for (int j = 0; j < jaggedArray[i].Length; j++)
{
Console.Write(jaggedArray[i][j] + " ");
}
Console.WriteLine();
}
}
}
```

### 5. **Array Methods**

#### Program 7: Using `Array.Sort` and `Array.Reverse`

```csharp
using System;

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

// Sorting the array


Array.Sort(numbers);
Console.WriteLine("Sorted array:");
foreach (int number in numbers)
{
Console.Write(number + " ");
}
Console.WriteLine();

// Reversing the array


Array.Reverse(numbers);
Console.WriteLine("Reversed array:");
foreach (int number in numbers)
{
Console.Write(number + " ");
}
Console.WriteLine();
}
}
```

#### Program 8: Using `Array.Copy`

```csharp
using System;

class Program
{
static void Main()
{
int[] source = { 10, 20, 30, 40, 50 };
ARRAYS
int[] destination = new int[3];

// Copying elements from source to destination


Array.Copy(source, 1, destination, 0, 3);

Console.WriteLine("Destination array after copy:");


foreach (int number in destination)
{
Console.Write(number + " ");
}
Console.WriteLine();
}
}
```

### 6. **Finding Minimum and Maximum Values**

#### Program 9: Finding Min and Max Values in an Array

```csharp
using System;

class Program
{
static void Main()
{
int[] numbers = { 5, 1, 9, 7, 6, 3, 2 };

int min = numbers[0];


int max = numbers[0];

foreach (int number in numbers)


{
if (number < min)
min = number;
if (number > max)
max = number;
}

Console.WriteLine($"Minimum value: {min}");


Console.WriteLine($"Maximum value: {max}");
}
}
```

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);
}
}

static void Main()


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

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;

int j = 0; // Pointer for unique elements


for (int i = 1; i < nums.Length; i++)
{
if (nums[i] != nums[j])
{
j++;
nums[j] = nums[i];
}
}
return j + 1; // Return count of unique elements
}

static void Main()


{
int[] nums = { 1, 1, 2, 3, 3 };
int uniqueCount = RemoveDuplicates(nums);
Console.WriteLine($"Unique count: {uniqueCount}");
}
}

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);
}

static void Main()


{
int[] nums = { 1, 2, 3, 4, 5 };
Rotate(nums, 2);
Console.WriteLine(string.Join(", ", nums));
}
}

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.

4. Merge Two Sorted Arrays into a Single Sorted Array


Explanation
We can merge two sorted arrays using a three-pointer technique.

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;

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


{
if (arr1[i] < arr2[j])
merged[k++] = arr1[i++];
else
merged[k++] = arr2[j++];
}

while (i < arr1.Length) merged[k++] = arr1[i++];


while (j < arr2.Length) merged[k++] = arr2[j++];

return merged;
}

static void Main()


{
int[] arr1 = { 1, 3, 5 };
int[] arr2 = { 2, 4, 6 };
var result = MergeArrays(arr1, arr2);
Console.WriteLine(string.Join(", ", result));
}
}

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.

5. Find the Missing Number in an Array from 1 to N


Explanation
The missing number can be found by calculating the expected sum and subtracting the actual sum of elements.

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;

foreach (var num in nums)


arraySum += num;

return totalSum - arraySum;


}

static void Main()


{
int[] nums = { 3, 7, 1, 2, 8 }; // Missing number is 4
Console.WriteLine($"Missing number: {FindMissingNumber(nums)}");
}
}

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 .

6. Find the Contiguous Subarray with the Largest Sum


Explanation
Kadane's algorithm efficiently finds this maximum sum subarray in linear time.

C# Code
csharp
using System;

class Program
{
public static int MaxSubArray(int[] nums)
{
int maxCurrent = maxGlobal = nums[0];

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


{
maxCurrent = Math.Max(nums[i], maxCurrent + nums[i]);
if (maxCurrent > maxGlobal)
maxGlobal = maxCurrent;
}

return maxGlobal;
}

static void Main()


{
int[] nums = { -2, -3, 4, -1, -2, 1, 5, -3 };
Console.WriteLine($"Max subarray sum: {MaxSubArray(nums)}");
ARRAYS
}
}

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.

7. Check if an Array Contains Duplicates


Explanation
Using a hash set allows us to check for duplicates efficiently.

C# Code
csharp
using System;
using System.Collections.Generic;

class Program
{
public static bool ContainsDuplicate(int[] nums)
{
HashSet<int> set = new HashSet<int>();

foreach (var num in nums)


if (!set.Add(num)) return true;

return false;
}

static void Main()


{
int[] nums = { 1, 2, 3, 4 };
Console.WriteLine($"Contains duplicates: {ContainsDuplicate(nums)}");
}
}

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;

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


output[i] = output[i - 1] * nums[i - 1];

int rightProduct = 1;

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


{
output[i] *= rightProduct;
rightProduct *= nums[i];
}

return output;
}

static void Main()


{
int[] nums = {1,2,3,4};
var result = ProductExceptSelf(nums);
Console.WriteLine(string.Join(", ", result));
}
}

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;

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


{
if (nums[i] != 0)
{
nums[lastNonZeroIndex++] = nums[i];
}
}

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


{
nums[i] = 0;
}
}

static void Main()


{
int[] nums = {0,1,0,3,12};
MoveZeroes(nums);
Console.WriteLine(string.Join(", ", nums));
}
}

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.

10. Find a Peak Element in an Array


Explanation
A peak element is one that is greater than its neighbors; we can check this condition while iterating through the array.
ARRAYS
C# Code
csharp
using System;

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
}

static void Main()


{
int[] nums= {10 ,20 ,15 ,25 ,30};
Console.WriteLine($"Peak element index: {FindPeakElement(nums)}");
}
}

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

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy