Say I have an integer array called abc[100]. abc only has values in the first 5 "slots". How can I write a for loop for this where the loop goes up until the last value in abc that isnt empty?
int abc[100] = {1, 2, 3, 4, 5};
In C++ arrays, there is no concept of an array element being "empty".
That idea simply doesn't exist. Erase it from your mind.
Each array element always exists.
In C & C++, when part of an array is explicitly initialized, and part is not explicitly initialized, the part that you didn't specify defaults to zero.
So, you effectively wrote:
int abc[100] = {1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0....};
If you want, you can treat value 0
as a marker for values that aren't set.
int i;
for(i=0; abc[i] != 0; ++i)
{
cout << "[" <<i<< "] : " << abc[i] <<endl;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments