switch and if

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include<conio.h>
#include<stdlib.h>
using namespace 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;

          }
Last edited on
well, it helps if you tell us what is broken.

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.
Last edited on
Topic archived. No new replies allowed.