array in c

how to use array in c if we are not aware of no. of entries but we know the maximun limit of no. of entries.
Eg. we want to enter 5 entries(no. of entries are user dependent i.e. here 6,7 or any no.) through array and array is defined as array[20] ?

Hi. The simplest method is to keep track of the total number of the total number of entries in some variable n. So say you declare your array as array[20 ] and there are n entries, then you can use this variable to keep track of whatever operations you want to perform. Say for printing the elements of array do : for( i=0 ; i<n ; i++).Hopefully this is what you were expecting

Here is a link on arrays:

Also, just declare the array of size equal to the maximum limit of no. of entries.

if max. no. of entries= 100

Declare as int array[102]; (Always make the size 1 or 2 greater than the max size)

I hope this helps!

If you still have any problem, comment below!

1 Like

thanks for your answer. But the thing I was asking is that the no of entries are user dependent and the maximum limit is pre-defined. Like we use NULL or \0 in string.

thanks for ur answer. But the prob i m facing is that no. of entries are user dependent i.e. he may enter any no of entries that lie in the range of maximun limit like if maximum limit is 10, he may enter any no of entries like 1 or 2 or 3 …

Also please help how to use variable in array like array[x] where x is a variable.

Hi. As you are asking for defining variable sized arrays. The basic thing is that you can define the arrays considering the max limit that is possible(So what, if all the elements of the array are not used up). But in case you want to use variable sized array the basic thing is allocating the array using malloc(in C language) and then using it. Link to the tutorial is given below :

Using malloc dynamically allocates the array and then you can use it. If you want to use the array in a static form then what you can do is as follows :

int n;
int A[n];// Allocate the array in static manner

In that case declare the array dynamically. Using malloc(), calloc() in C or the new operator in C++.

Here is the link for C.

Similarly you can do dynamic memory allocation in C++.

I Hope that this answers your question.

For basics of arrays, I would suggest that you refer a book on programming in C. This would help, as there are many basic questions in a book that clear the concept.