Created
July 15, 2017 15:26
-
-
Save the-cybersapien/45087dd01803a7f441b7e18d60dfe017 to your computer and use it in GitHub Desktop.
Gist containing the code to add an element to an array.
Basic code, only for a display.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
class array1 { | |
public: | |
void a1() { | |
int n, i; | |
int no, pos; | |
// Get the original number of elements in the array | |
cout << "Enter no. of Elements of array: " << endl; | |
cin >> n; | |
// Once you have the number of elements, | |
// keep in mind that the array needs to have 1 more space for the new element | |
int arr[n + 1]; | |
cout << "Enter the elements" << endl; | |
for (i = 0; i < n; ++i) { | |
cin >> arr[i]; | |
} | |
// Once elements enter ho gye, get the number to add | |
// and the position to add it at | |
cout << "Enter the number to add: " << endl; | |
cin >> no; | |
cout << "Enter the position to add it to: " << endl; | |
cin >> pos; | |
// Now shift the elements to the next position | |
// for the elements AFTER the position choosed. | |
for (i = n; i >= pos; i--) { | |
arr[i + 1] = arr[i]; | |
} | |
// Once this shift is done, put the new element at pos | |
arr[pos] = no; | |
cout << "The array elements are " << endl; | |
// n + 1 because total elements are original n and an extra element. | |
for (i = 0; i < n + 1; ++i) { | |
cout << arr[i] << " "; | |
} | |
} | |
}; | |
int main() { | |
array1 ob; | |
ob.a1(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment