i'm a beginner programmer and was trying out this array based program,
it aint working the way i want it to work; could someone help me and tell me what is wrong with this code??
it is really shabby, sorry bout that.
#include <iostream>
#include<conio.h>
#include<stdlib.h>
usingnamespace std;
int main()
{
char x;
int in;
int a[50],flag=-1,i,j,ele;int opt,pos;
cout<<"enter sixe of an annry";
cin>>j;
cout<<"\nenter array vars\n";
for(i=0;i<j;i++)
cin>>a[i];
cout<<"enter search element";
cin>>ele;
for (i=0;i<j;i++)
if(a[i]==ele)
flag=i;
if (flag==-1)
cout<<"element not found";
else
cout<<"found at pos"<<flag+1;
getch();
system("cls");
cout<<"do you want to insert an element into this array?\ny/n";
cin>>x;
if (x=='y')
{
cout<<"ENTER INSERTION ELEMENT";
cin>>in;
cout<<"\n 1.at position\n2.at the begenning\n3.at the end\nenter your option\n";
cin>>opt;
switch(opt)
{
case 1:
{cout<<"enter position";
cin>>pos;
for(i=j;i>pos;i++)
a[i]=a[i+1];
j++;
a[pos]=in;
break;}
case 2:
{for (i=j;i>0;i++)
a[i]=a[i+1];
j++;
a[0]=in;
break;}
case 3:
{a[j]=in;
j++;
break;
}
}
}
else
cout<<"have a good day";
cout<<"new array is";
for (i=0;i<j;i++)
cout<<a[i];
return 0;
}
but I see this issue right off:
case 1:
{cout<<"enter position";
cin>>pos;
for(i=j;i>pos;i++)
a[i]=a[i+1];
j++;
apparently, j means size, though its hard to tell from the terrible variable name.
pos is where the user said to put it. presumably, this is <= the last position, though you don't enforce anything.
so if j is 5 and pos is 2... i increments forever, and it goes out of bounds, right?
what you probably wanted to say was start at the end of the array (j?) and move that to j+1, then decrement once, and move (j-1) to j, and then j-2 to j-1, ... back until pos is open and put the new guy there.