Array searching

I know that this is going to seem easy compared to some of the other stuff that I've asked...

but how do you search through a 2D array using a while for the main loop and using a for-loop for the nested loops?

thanks
1
2
3
4
5
6
7
8
9
10
11
12
13
while (1)
{
  for(i=0; i<firstLimit;++i)
  {
      for(j=0; j<secondLimit;++j)
      {
         if (array[i][j] == whatIAmLookingFor)
         {
            break;
          }
       }
 break; // Never found it. Better break otherwise I'll be in this while loop forever. Why is it in a while loop?
}


Last edited on
again, stupid moment here: but those look like for-loops with if instead of for

perhaps I should explain what I'm trying to do.

I have a 2x4 array with predefined values, that I have to display by columns in one function and then by rows in another.
By row

1
2
3
4
5
6
7
8
for (i=0; i<numberRows; ++i)
  {
    for (j=0; j<numberColumns; ++j)
      {
          cout << array[i][j];
       }
     cout << endl;
}


By column

1
2
3
4
5
6
7
8
for (j=0; j<numberColumns; ++j)
  {
    for (i=0; i<numberRows; ++i)
    {
       cout << array[i][j];
     }
     cout << endl;
}

Thanks, Moschops, that's what I initially turned in, but the professor returned it to me saying that I needed to use a while loop as the main loop and only use the for loop inside of the while.

EDIT: just saw your edit above, thanks. I don't know why its in a while, seems stupid to me as well
Last edited on
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
finished = 0;
while (!finished)
{

// by row
for (i=0; i<numberRows; ++i)
  {
    for (j=0; j<numberColumns; ++j)
      {
          cout << array[i][j];
       }
     cout << endl;
}

// by column
for (j=0; j<numberColumns; ++j)
  {
    for (i=0; i<numberRows; ++i)
    {
       cout << array[i][j];
     }
     cout << endl;
}

finished = 1;
}



Alternatively, given that a for loop is juts a while loop with some bits put into one line:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
i = 0;
while (i<numberRows)
  {
    for (j=0; j<numberColumns; ++j)
      {
          cout << array[i][j];
       }
     cout << endl;
     ++i;
}


// by column
j = 0;
while (j<numberRows)
  {
    for (i=0; i<numberRows; ++i)
    {
       cout << array[i][j];
     }
     cout << endl;
      ++j;
}

Last edited on
Moschops, you're awesome.

I don't know why we're doing it this way, but thanks for your help.
Last edited on
Moschops, you're awesome.


I just don't hear that enough :p
Topic archived. No new replies allowed.