3

I'm having some trouble understanding how to use a while loop to get the same results as this for loop:

for (int i=0; i<N; i++){
    int datum[i] = 0;
}

Basically, to set all the elements in the array datum[N] to 0. Does the following code make sense in that regard, or am I missing something? thanks

int i = 0;
while (i < N){
    datum[i] = 0;
    i++;
}
John Roberts
  • 417
  • 3
  • 5

2 Answers2

3

These two code examples produce the same results.

int i = 0;
while (i < N)
{
     datum[i] = 0;
     i++;
}

for (int i=0; i<N; i++) 
{
   datum[i] = 0; // remove int because you will be redclaring datum
}
sebenalern
  • 2,425
  • 3
  • 23
  • 34
2

Don't use either of them. When you declare datum, do so like this:

std::vector<int> datum(N);

Done.

Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021