I'm trying to make this program which gets an element from user and inserts it into the made array by user (array must be sorted) But it doesn't work properly
for example: a[4]
a[0]=1
a[1]=3
a[2]=5
a[3]=7
then i insert>> 6
but then it goes like this
a[0]=1
a[1]=3
a[2]=5
a[3]=6
a[4]=3866936
the array is able to have upto 100 elements
:|
it's a practice from a book
#include<iostream>
#include<windows.h>
using namespace std;
void insert(int[], int&, int);
int main()
{
const int maxsize = 100;
int a[maxsize];
cout << "build ur array\n"; Sleep(650);
cout << "Enter the number of elements:";
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cout << "a[" << i << "]=";
cin >> a[i];
}
int k;
cout << "Enter a new element:";
cin >> k;
n++;
insert(a, n, k);
for (int i = 0; i < n; i++)
cout << "a[" << i << "]=" << a[i] << endl;
system("pause");
}
void insert(int a[], int& n, int x)
{
for (int i = n - 1; a[i]>x; i--)
a[i] = a[i + 1];
for (int i = n; i <= n; i--)
{
if (x >= a[i])
{
a[i + 1] = x;
break;
}
}
std::vector<int> v; v.push_back(6);and let the standard library worry about annoying pointer fiddling.insert(the location you want is where the first loop stopped - you don't need to search again).