Difficulty making a loop with arrays

Hi, everyone! I have to do a program for my compsci class involving arrays. Basically what happens is the user creates an array by inputting six numbers. Then the user inputs a query. If the query is one of the numbers in the array, the program will replace that number with a 0. An example output would be this:

Input number 1: 5
Input number 2: 62
Input number 3: 582
Input number 4: -2
Input number 5: 8
Input number 6: 24
Enter query number: 62
62 was in location 2.
The new array is: 5 0 582 -2 8 24

And that would continue on. The problem with my code is that it only continues the loop if the query is larger than the query before it. If I were to put 582 afterwards then it would work, but if I were to put -2 it wouldn't.

Also, when the array is output it doesn't print the numbers in a line. It makes a new line for each one. How can I fix this?

(I know the code isn't perfect or even probably good, but as long as it works I don't care.)

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
void replace (int array[], int sizeArray, int i, int query);

int main()
{
  int array[6], i=0, query;

  while (i<6)
  {
    cout << "Input number " << i+1 << ":\n";
    cin >> array[i]
    i++
  }

  cout << "Enter a query number: \n";
  cin >> query;

  findAndReplace(array, 6, 0, query);

return 0;
}

void findAndReplace (int array[], int sizeArray, int i, int query)
{
  for (i=0; i<sizeArray; i++)
  {
    if (query==array[i])
    {
      array[i]=0;
      cout << query << " was at location " << i+1 << ".\n";
      cout << "Your new array is: \n";

      for (int j=0; j<sizeArray; j++)
        cout << array[j] << endl;

    cout << "Enter a query number: \n";
    cin >> query;
    }
  }

  cout << "Query not in list! Goodbye!\n";
}
Your function findAndReplace should do exactly one thing and one thing only: search and replace. No printing. No asking for new values.

If you need to replace multiple values, then call the findAndReplace multiple times.


It makes a new line for each one.

Yes, on line 33 you do print a newline after each value. If you don't want a newline, then don't print the newline.
Last edited on
Thanks so much for your help, it's working now. Much appreciated!
Topic archived. No new replies allowed.