You could do this in multiple ways - one is to keep counter of initialized values:
arr[0] = 5;
arr[1] = 10;
arr[2] = 15;
arr[3] = 20;
n = 4;
This only works if you will fill array sequentially.
Other way is to initialize array with some value which semantically can't be elements of the array:
int arr[32] = {-1};
After that, you can check if the current element contains value different than -1
.
The sample loop could be implemented like this:
for(i = 0; i < 32 && arr[i] != -1; i++)
{
// do things
}
Also, as @Jongware pointed out in the comment - if you don't mind spending O(n) of extra space - you could have additional flag array:
int fill[32] = {0};
arr[0] = 5; fill[0] = 1;
arr[1] = 10; fill[1] = 1;
arr[2] = 15; fill[2] = 1;
arr[3] = 20; fill[3] = 1;
You could save some space using bitsets, if that is important for you.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…