Delete an element from given position from array using C# program

Given an array, we have to delete an element from it.
[Last updated : March 19, 2023]

Deleting an element from an array

Given array of integers and we have to delete (remove) an element from given position.

To delete element from array: first we will traverse array to given position and then we will shift each element one position back.

The final array will not contain that element and array size will be decreased by 1.

Example

For example we have list of integers:

10 12 15 8 17 23

Now we delete element from 3rd position then list will like this:
10 12 8 17 23

C# program to delete an element from an array

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1 {
  class Program {
    static void Main() {
      int i = 0;
      int pos = 0;
      int[] arr = new int[10];

      //Read numbers into array
      Console.WriteLine("Enter numbers : ");
      for (i = 0; i < 5; i++) {
        Console.Write("Element[" + (i + 1) + "]: ");
        arr[i] = int.Parse(Console.ReadLine());
      }

      Console.Write("Enter position to delete item : ");
      pos = int.Parse(Console.ReadLine());

      //Perform shift opearation
      for (i = pos - 1; i < 5; i++) {
        arr[i] = arr[i + 1];
      }

      //print array after deletion
      Console.WriteLine("Array elements after deletion : ");
      for (i = 0; i < 4; i++) {
        Console.WriteLine("Element[" + (i + 1) + "]: " + arr[i]);
      }

      Console.WriteLine();
    }
  }
}

Output

Enter numbers :
Element[1]: 10
Element[2]: 20
Element[3]: 30
Element[4]: 40
Element[5]: 50
Enter position to delete item : 2
Array elements after deletion :
Element[1]: 10
Element[2]: 30
Element[3]: 40
Element[4]: 50

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.