[go: up one dir, main page]

0% found this document useful (0 votes)
6 views2 pages

Array Program

The document is a C++ program that allows users to manipulate an array by inserting and deleting elements at the beginning, end, or a specified position. It prompts the user for the size of the array and the elements to be added or removed, handling invalid positions accordingly. Finally, it displays the modified array after all operations are completed.

Uploaded by

preci.7812
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)
6 views2 pages

Array Program

The document is a C++ program that allows users to manipulate an array by inserting and deleting elements at the beginning, end, or a specified position. It prompts the user for the size of the array and the elements to be added or removed, handling invalid positions accordingly. Finally, it displays the modified array after all operations are completed.

Uploaded by

preci.7812
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/ 2

#include <iostream>

using namespace std;

int main() {
int arr[100], size, i, element, pos;

// Initial array input


cout << "Enter size of array: ";
cin >> size;

cout << "Enter " << size << " elements:\n";


for (i = 0; i < size; i++)
cin >> arr[i];

// Insert at beginning
cout << "Enter element to insert at beginning: ";
cin >> element;
for (i = size; i > 0; i--)
arr[i] = arr[i - 1];
arr[0] = element;
size++;

// Insert at end
cout << "Enter element to insert at end: ";
cin >> element;
arr[size] = element;
size++;

// Insert at given position


cout << "Enter element to insert and position (0-based): ";
cin >> element >> pos;
if (pos < 0 || pos > size) {
cout << "Invalid position for insertion!\n";
} else {
for (i = size; i > pos; i--)
arr[i] = arr[i - 1];
arr[pos] = element;
size++;
}

// Delete from beginning


for (i = 0; i < size - 1; i++)
arr[i] = arr[i + 1];
size--;

// Delete from end


size--;

// Delete from given position


cout << "Enter position to delete (0-based): ";
cin >> pos;
if (pos < 0 || pos >= size) {
cout << "Invalid position for deletion!\n";
} else {
for (i = pos; i < size - 1; i++)
arr[i] = arr[i + 1];
size--;
}
// Display final array
cout << "Final array: ";
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;

return 0;
}

You might also like