Write a C++ program to delete an element from an array at specified position. Given an input array, Write a code to delete an element from a position input by a user.
To solve this problem, let's first understand what is the input parameter and what's our approach to solve this problem.
In this program, we take an input array and position of an element to delete.
C program to delete an element from an array
Reverse an Array using Recursion
In this program, we take an array and position of an element as an input. Then, we write a code to delete an element from an array. To delete an element at index i in array we have to shift all elements from index i+1(higher index) to i (previous index).
Output :
Enter the size of an array - 5
Enter the value in an array
2 4 6 1 2
Enter the position - 2
2 4 1 2
To solve this problem, let's first understand what is the input parameter and what's our approach to solve this problem.
In this program, we take an input array and position of an element to delete.
C program to delete an element from an array
Reverse an Array using Recursion
C++ Program to Delete an Element form an Array
In this program, we take an array and position of an element as an input. Then, we write a code to delete an element from an array. To delete an element at index i in array we have to shift all elements from index i+1(higher index) to i (previous index).
#include <iostream> using namespace std; int main() { int a[100], size, pos, i, count = 0; cout << "Enter the size of an array \n"; cin >> size; cout << "Enter the value in an array \n"; // Take an input array for (i = 0; i < size; i++) { cin >> a[i]; } //Input position where we delete an element cout << "Enter the position \n"; cin >> pos; //Shift element from i+1 to i for(i = pos-1; i < size; i++) { arr[i] = arr[i+1]; } // Reduce the size of an array size--; // Print an array after deleting an element for(i = 0; i < size; i++) { cout<<" "<<a[i]; } return 0; }
Output :
Enter the size of an array - 5
Enter the value in an array
2 4 6 1 2
Enter the position - 2
2 4 1 2
Programming questions on Strings
Programming questions on Recursion
Programming questions on Array
Programming questions on Linked List
No comments:
Post a Comment