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++;
}
3
  • No you're not :) But for the first loop, why int? You can't redeclare datum[i]. Commented May 21, 2016 at 14:25
  • Initialize them to zero with int datum[N] = {0}; would be better practice generally. Commented May 21, 2016 at 14:27
  • @ScottStainton: int datum[N] = {} makes more logical sense in C++. Commented May 21, 2016 at 14:38

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Done.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.