Add an element to an array at a particular location

Here is my attempt:
1
2
3
4
5
6
7
8
9
10
11
int add(int e , int size , int a[] , int loc){
    int flag = -1 ;
    if(loc < size){
        flag = 0 ;
        for(int i=size; i<=(loc-1);i--){
            a[i]=a[i-1]; // moving elements forwards to create space for element
        }
        a[loc-1]= e;
    }
    return flag ;
}


However in my attempt I lose the element at location .
for example:
If I want to add an element 4 at location 2 in the array :
Original Array : 1 3 4 5 9
Expected ans : 1 2 3 4 5 9
Answer that I get : 1 2 4 5 9 * "where * is equal to any number"
I lose the element 3 and this is not the correct answer .

I am entering the location starting from 1 and then I adjust the calculations in the function given above. This function is a part of another program. If you need that to find the error , please tell me . Thanks
What is 'size' defined as exactly ?
Nevertheless, a[] is presumably writing out of bounds. If you did this earlier:

a[] = {1, 3, 4, 5, 9};
Where is there room for the '2' ?
After a[] is initialized its size cannot be changed.

The way to do this is:
1- with vectors which can be resized dynamically or,
2- by passing in a second array b[newsize] which is the size that u want ur new array to be and copy each element 1 by 1 from a[] into b[] until ur loop hits the 'loc' element which u can then insert into b[] and then continue adding the rest of the elements from a[]
3- if u know beforehand how big a[] will be, u could (***) size it as such at initialization and add extra 'dummy' zeros to the end like this: a[] = {1, 3, 4, 5, 9, 0} Then u can use ur sorting algorithm with ur example which will remove that extra zero to make the desired output.

Also, ur for loop for(int i=size; i<=(loc-1);i--) never occurs. U want i>=(loc-1) instead
Last edited on
What if loc is >= size?
What if loc is > than the size of the array?
While the condition is met, the loop is executed.
Also, if you defined your array to be of n elements then it cannot hold n+1 elements.
Well , the silly mistake in for loop changed the situation.
Here's the complete code for the program however , it still shows some errors in the sort() function.

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include<iostream>
#include<cstdlib>
using namespace std ;

int search(int e,int size, int a[]){
    int loc = -1 ;
    for(int i=0 ; i<size; i++){
        if(a[i]== e){
            loc=i;
            break;
        }
    }
    return loc ;
}

int del(int e,int size, int a[]){
    int loc = search(e,size,a);
    if(loc != -1){
        for(int i=loc ; i<size ; i++){
            a[i]=a[i+1];
        }
        size = size - 1;
    }
    return loc ;
}

int add(int e , int size , int a[] , int loc){
    int flag = -1 ;
    if(loc < size){
        flag = 0 ;
        for(int i=size; i>=(loc-1);i--){
            a[i]=a[i-1];
        }
        a[loc-1]= e;
    }
    return flag ;
}

void sort(int size , int a[]){
    for(int pass=1; pass <= size-1; pass++){
      for(int j=0;j <= (size-pass)-1; j++){
        if(a[j] > a[j+1]){
             int temp ;
             temp = a[j];
             a[j] = a[j+1];
             a[j+1] = temp ;
            }
        }
    }
    cout<<"\nSorted Array";
    for(int k=0;k<size;k++){
        cout<<" "<<a[k];
    }
}

int main () {
    const int size = 10 ;
    int arr[size] = {134,32,45,23,-1,0,37,23,17,10};
    int loc = -1 ;
    int e , de ,ans ;
    cout<<"\t\t\t\tARRAY OPERATIONS";
    while(true){
    cout<<"\n\n1. Traversal.";
    cout<<"\n2. Search.";
    cout<<"\n3. Deletion";
    cout<<"\n4. Addition.";
    cout<<"\n5. Sort.";
    cout<<"\n6. Exit.";
    cout<<"\nWhich operation would you like to carry ";
    cin>>ans;
    switch(ans){
        case 1 :
        cout << "\nTraversal:\n";
        for(int i=0 ; i<10; i++){
            cout<<" "<<arr[i];
        }
        break;

        case 2 :
            cout << "\n\nEnter the element to search ";
            cin >> e;
            if((loc=search(e,size,arr))!= -1) {
                cout<<"\nThe location of the element is "<< (loc+1);
            }else {
                cout<<"\nElement not found !!";
            }
        break;

        case 3 :
            cout <<"\n\nEnter the element to delete";
            cin >> de ;
            if(del(de,size,arr)!= -1 ){
                cout << "\nElement deleted successfully !!";
                cout << "\nNew Array: ";
                for(int i=0 ; i<(size-1);i++){
                cout<<" "<<arr[i];
            }
            }else {
                cout << "Element not found !!";
            }
        break;

        case 4 :
            cout<<"\nEnter any element at a particular location(ele loc)";
            cin>>e>>loc;
            if(add(e,size,arr,loc)!= -1 ){
                cout<<"\nElement added successfully!!";
                cout<<"\nNew Array:";
                for(int i=0;i<(size+1);i++){
                    cout<<" "<<arr[i];
                }
            }else {
                cout<<"Element could not be added !!";
            }
        break;

        case 5 :
            sort(size,arr);
        break;

        case 6:
            exit(0);
            break;
        default:
        cout<<"Invalid argument. Exiting program...";
    }
   }
return 0 ;
}

The errors have been resolved. If any other suggestions are there , you are welcome ..thanks
Last edited on
in ur 'sort' function int temp ; should be declared outside of those loops...

what exactly is the issue with sort ?
Last edited on
The issue has been resolved . Initially it used to copy the garbage value from the end of the array as well ie a[size]. So I just changed the loop from (size-pass) to (size-pass)-1. Now it doesn't compare the last value with the value at
a[size] ie a[size-1] > a[size]. That solved my problem.
btw thanks for replying ..
np :D
yes, sorting subsets of an array while staying in bounds of that array can be a pain in the **array** !!!
Topic archived. No new replies allowed.