The Program in C# Program to Delete Element at Desired position From Array is given below:
using System;
namespace DeleteArrayElement
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Codeauri Family, enter the number of elements in the array: ");
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
Console.WriteLine("Enter the elements of the array: ");
for (int i = 0; i < n; i++)
{
arr[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Enter the position of the element to be deleted: ");
int position = int.Parse(Console.ReadLine());
if (position <= 0 || position > n)
{
Console.WriteLine("Invalid position!");
}
else
{
int[] newArray = new int[n - 1];
int j = 0;
for (int i = 0; i < n; i++)
{
if (i == position - 1)
{
continue;
}
newArray[j] = arr[i];
j++;
}
Console.WriteLine("Okay, the updated array after deleting the element is: ");
foreach (int item in newArray)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
}
}
}
Output:
Hello Codeauri Family, enter the number of elements in the array:
4
Enter the elements of the array:
1413
789
456
42
Enter the position of the element to be deleted:
3
Okay, the updated array after deleting the element is:
1413 789 42
Pro-Tips💡
Here are the steps by steps execution of above program:
- The program starts by printing a message to the console to ask the user to enter the number of elements in the array.
- The user inputs the number of elements in the array and the program stores this value in the ‘n’ variable.
- The program then creates an array ‘arr’ of size ‘n’ and asks the user to enter the elements of the array.
- The user inputs the elements of the array, and the program stores these values in the ‘arr’ array.
- The program then asks the user to enter the position of the element to be deleted.
- The user inputs the position of the element to be deleted and the program stores this value in the ‘position’ variable.
- The program then checks if the position entered by the user is valid or not. If the position is less than or equal to 0 or greater than ‘n’, the program prints an “Invalid position!” message to the console.
- If the position is valid, the program creates a new array ‘newArray’ of size ‘n-1’ and copies all elements of the ‘arr’ array except the element at the ‘position-1’ index to the newArray.
- The program then prints the updated array ‘newArray’ after deleting the element to the console.
- The program ends with a newline character.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.