Search code examples
arrayscfor-loopintprintf

How to print a large incompletely filled array only till last entered int (in C)?


I'm using int er[3001]. I'll be taking user input, but it is unlikely that entire array size will be used.

In a char array / string, one would simply set a for loop testing arr[i] != \0. How is this effect achieved for an int array ?

I'm assuming using the same exact condition won't work?


Solution

  • I'm assuming using the same exact condition wont work ?

    You're right in this, there's no default sentinel value for marking the end of integer array. You need to either:

    • Keep track of the # of elements entered successfully
    • Initialize the array with an invalid value (let's say, -1, when all expected inputs are non-negative) and get to the first invalid value location after the input.
    • Use a user-defined sentinel value in the input itself to mark the end of the input.