Lucas Toledo
Lucas Toledo

Reputation: 43

Using while / do-while loops for array element setting

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++;
}

Upvotes: 3

Views: 913

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

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

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

Done.

Upvotes: 2

sebenalern
sebenalern

Reputation: 2561

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
}

Upvotes: 3

Related Questions