0

I have an array and a for loop. I want the for loop to stop depending on the number of elements the array has.

For example if I have an int array []={1,0,1,0,1} I want the loop to execute code 5 times. Similar to the function for strings .length() but for integers. An example with a simple code would be the best answer :)

like this pseudocode:

for(int b=0;b<array-length;b++)
  • 3
    `sizeof(array)/sizeof(*array)` will evaluate to the number of elements in the array. – George Dec 05 '16 at 11:01
  • 1
    ^^ Provided it's not decayed to a pointer of course. `std::array` or a range based for loop as in the answers are probably your best bet. – George Dec 05 '16 at 11:11

3 Answers3

1

Unless you need the index, the following works fine:

int ar[] = { 1, 2, 3, 4, 5 };
for (auto i : ar) {
    std::cout << i << std::endl;
}
Nim
  • 33,299
  • 2
  • 62
  • 101
1

Since the question is tagged with C++, I'll have to suggest std::vector as the best solution. (Also for the future)

Look into this: std::vector

So for you this'd be like the following:

std::vector<int> array {1,0,1,0,1};
for(int i = 0; i < array.size(); i++)
   ...

Or in the worst case an std::array if you don't want the features of a vector.

See also: std::array

SenselessCoder
  • 1,139
  • 12
  • 27
0

To find length of an array, use this code

int array[5];
std::cout << "Length of array = " << (sizeof(array)/sizeof(*array)) << std::endl;

So in your case, it will be for example:

int array[5];
for(int b=0; b < sizeof(array)/sizeof(*array); b++){
   std::cout << array[b] << std::endl;
}
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38