shifting elements in an array

Hi everyone,
I know this is a common question, but I've gone through all of the related posts that I could find, and none of it seems to solve my problem. I'm supposed to insert a given number in a given location and then shift all elements to the right. So far I've just managed to replace the old number with the new number (getting rid of the old number). I don't want to lose any numbers, just shift to the right.

Here's what I've got:

Here are the function calls in main
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 int aList[ARRAY_CAP] = {};
	int size = 0;
	int val = 0;

	print(aList, size);
	insert(0, 10, aList, size);
	print(aList,size);
	insert(1, 20, aList, size);
	print(aList, size);
	insert(0, 4, aList, size);
	print(aList, size);
	insert(1, 40, aList, size);
	print(aList, size);
	insert(2, 25, aList, size);
	print(aList, size);


Here is my function for inserting:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
bool insert(int position, int val, int intList[], int& size)
{
	int temp = 0;
        int i = 0;

	
	intList[position] = val;
	
        for (int i = 0; i < ARRAY_CAP; i++)	
	{
	    temp = intList[i];
	    intList[i] = intList[i + 1];
	    intList[i + 1] = temp;
	}
        size++;
  
	return true;
}


expected output:
[]
[10]
[10 20]
[4 40 10 20]
[4 40 25 10 20]

Thanks in advance for any help!

begin01
Your insert function. The first thing you're doing is write over intList[position]. So you've already lost whatever number was there.

Do the shifting FIRST, and then write the new number into place.


1
2
3
  temp = intList[i];
  intList[i] = intList[i + 1];
  intList[i + 1] = temp;

This appears to be a SWAP function. It makes no sense. To shift the numbers to the right, start at the end and work your way backwards. Something like:

1
2
3
4
for (int i = end; i > position; --i)
{
  intList[i] = intList[i-1];
}


Something like that. Test it and see if there are off-by-one errors in it. There could well be.

Last edited on
Hello begin01,

Some tips for the future:

When posting code it is usually best to post the whole code that can be compiled and run. This way no one has to guess at what you might have done.

If you are compiling to the C++11 standards the "=" is not necessary as in:
1
2
3
int aList[ARRAY_CAP]{};
int size{};
int val{};

The empty {} will initialize the variables to (0) zero and the array to all (0) zeros. It does save a little typing and makes it much easier IMO.

Your variable names are OK except for "size". It makes me ask size of what. Not that important just an observation. As a thought "sizeUsed" might be a better choice. Still it is your choice.

Andy
Andy,
I worried that if I posted the whole thing that it would be too much code and people wouldn't want to wade through it. (although I suppose in this case it's really not that much code) In the future I will post the whole thing.

The size variable is to keep track of the size of the array. Honestly, the variable names were given to me by my teacher and I'm not supposed to change them.

Repeater, I will try your suggestions and see what I get. I had a feeling I should be starting at the end and working backward, but I found a bunch of examples that did it similarly to how I tried to do it, so I though my hunch was wrong.

Thanks for the help!
Ok, here's the rest of the code, and changes that I made based on Repeater's suggestions.

main
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
#include <iostream>
#include "list.h"

using namespace std;

int main()
{
	int aList[ARRAY_CAP] = {};
	int size = 0;
	int val = 0;

	print(aList, size);
	insert(0, 10, aList, size);
	print(aList,size);
	insert(1, 20, aList, size);
	print(aList, size);
	insert(0, 4, aList, size);
	print(aList, size);
	insert(1, 40, aList, size);
	print(aList, size);
	insert(2, 25, aList, size);
	print(aList, size);
        
        return 0;
}

insert function
1
2
3
4
5
6
7
8
9
10
11
bool insert(int position, int val, int intList[], int& size)
{
        for (int i = 0; i > position; i--)
        {
                intList[i] = intList[i - 1];  //changed this
        }
        intList[position] = val;     //moved this to after the loop
        size++;

        return true;
}


I made the changes, and now my output is:
1
2
3
4
5
6
7
8
9
10
11
[ ]

[ 10 ]

[ 10 20 ]

[ 4 20 0 ]

[ 4 40 0 0 ]

[ 4 40 25 0 0 ]


desired output:
1
2
3
4
5
6
7
8
9
10
11
[ ]

[10]

[10 20]

[4 10 20]

[4 40 10 20]

[4 40 25 10 20]


So it looks like the 4 replaces the 10 instead of pushing it to the right. Then 40 replaces 20 instead of pushing 10 and 20 to the right. And so on.

Any thoughts? I know this is probably very simple for most of you, but it is not yet simple for me. I really appreciate your patience with me.

begin01


Last edited on
> for (int i = 0; i > position; i--)
Look again at the loop repeater wrote.
Figured it out! I changed i = 0 to i = size and now it's working right. Thanks everyone!
Hello begin01,

I understand not being able to change the variable names. I was think of more in the future, but also for this program if possible.

You may not have covered anything like this, but I was think in the "insert" function you could start with something like this:
1
2
3
4
5
6
if (size >= ARRAY_CAP)
{
    std::cout << "\n    Array is full!  Unable to add that number.\n";

    return false;
}

I have not tried this yet, but it is a check to make sure that you have enough room to shift everything to the right with out loosing the last number or writing to something past the end of the array.

Andy
this seems to produce the desired output

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

#include <iostream>
//#include "list.h"

using namespace std;
bool insert(int position, int val, int intList[], int size)
{
	if (intList[position] != NULL)
	{
		for (int i = size; i > position; i--)
		{
			if (intList[i - 1] != NULL)
			{
				intList[i] = intList[i - 1]; 

				   
			}
		}
	

	}
intList[position] = val;
		 
	return true;
}
void print(int list[], int size)
{
	for (int i = 0; i < size; i++)
	{
		if (list[i] != NULL)
			cout << list[i]<<' ';
	}
	cout << endl;
}

int main()
{
	const int ARRAY_CAP = 10;
	int aList[ARRAY_CAP] = {};
	int size = 10;
	int val = 0;

	print(aList, size);
	insert(0, 10, aList, size);
	print(aList, size);
	insert(1, 20, aList, size);
	print(aList, size);
	insert(0, 4, aList, size);
	print(aList, size);
	insert(1, 40, aList, size);
	print(aList, size);
	insert(2, 25, aList, size);
	print(aList, size);

	return 0;
}

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
#include <iostream>
using namespace std;

const int ARRAY_CAP = 10;

//============================================================================================

bool insert( int position, int val, int intList[], int& size)
{
   if ( size >= ARRAY_CAP - 1 ) return false;         // No room to insert more
   if ( position > size       ) return false;         // Going to leave gaps
   
   size++;                                            // New size; last element will be size-1
   for ( int i = size - 1; i > position; i-- ) intList[i] = intList[i-1];
   intList[position] = val;                           // Insert once there is room
   
   return true;
}

//============================================================================================

void print( int list[], int size )
{
   cout << "[ ";
   for ( int i = 0; i < size; i++ ) cout << list[i] << ' ';
   cout << "]\n";
}

//============================================================================================

int main()
{
   int aList[ARRAY_CAP] = {};
   int size = 0;

   print(aList, size);
   if ( insert(0, 10, aList, size) ) print( aList, size );
   if ( insert(1, 20, aList, size) ) print( aList, size );
   if ( insert(0,  4, aList, size) ) print( aList, size );
   if ( insert(1, 40, aList, size) ) print( aList, size );
   if ( insert(2, 25, aList, size) ) print( aList, size );
}


[ ]
[ 10 ]
[ 10 20 ]
[ 4 10 20 ]
[ 4 40 10 20 ]
[ 4 40 25 10 20 ]
Topic archived. No new replies allowed.