Array sort problem

I've created a small array to hold integers as a small part of a program, array is a bag I can put integers into and out of (eventually). However when i compile and run it and enter number 32 as my target (bag[0] of my array it also changes bag[5] as well in my output of the array. Obviously it's coded wrong but I can't see where?
Still a beginner but I welcome any suggestions on a better ways to implement my "bag" as well. Here's my code
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
#include <iostream>
using namespace std;
#define SLOTS 6
int main()
{
  int target;
  int bag[SLOTS] = {32, 42, 8, 12, 23, 0};
  int n;

  cout << "Enter a target to be found: ";
  cin >> target;

  for(int cntr = 0; cntr < SLOTS; cntr++)
  {
    if(bag[cntr] == target)
    {
    cout << "Put in bag" << endl;
    target = cntr;
    bag[target] = 100;
    }
  }
  for ( n=0; n<SLOTS; n++)
  {
    cout << bag[n] << ", ";
  }
cout << endl;
system ("Pause");
return 0;
}
15
16
17
18
19
20
    if(bag[cntr] == target)
    {
    cout << "Put in bag" << endl;
    target = cntr; //why are you touching target?
    bag[target] = 100; //?
    }
In your example target will change to 0, that is the last number in the array.
well in this code segment

1
2
3
4
5
6
7
8
9
for(int cntr = 0; cntr < SLOTS; cntr++)
  {
    if(bag[cntr] == target)
    {
    cout << "Put in bag" << endl;
    target = cntr;
    bag[target] = 100;
    }
  }
im not sure why you change target, why not just do it like this

1
2
3
4
5
6
7
8
for(int cntr = 0; cntr < SLOTS; cntr++)
  {
    if(bag[cntr] == target)
    {
    cout << "Put in bag" << endl;
    bag[cntr] = 100;
    }
  }


that may not solve your problem but it was definitely iffy code. And also when you loop through the array to print, why not use a local variable inside of the for statement for n instead of declaring it at the top
Last edited on
Thanks for your prompt replies. The reson why I used target was that I only want the first item found in my sort to change to 100 (100 will later be an item code) if my bag was set to 0 for all empty slots then I will be sorting to find an empty slot and filling it with an item code, if i use cntr all slots recieve the new item code. n has now moved to a local variable (silly mistake). I've tried using a new variable instead of re-using target but I still get it filling other slots, so obviously I didn't quite understand this part of your answer, sorry!
Just needed to break out of the loop, thank you both, Leppie
Topic archived. No new replies allowed.