Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If dim specifies the quantity of data in an array, wouldn't using dim – 1 potentially cause me to lose an element?

I’m currently working on manipulating arrays in C, and I’m a bit confused about why dim – 1 is commonly used in array-related operations. If dim specifies the quantity of data in an array, wouldn’t using dim – 1 potentially cause me to lose an element?

For example, in the context of the Bubble Sort algorithm, it is common to use:
for (int i = 0; i < dim - 1; i++).
Is there a specific reason for this convention?
Do I lose an element by initializing the index at 1 or setting it to dim – 1?

I tried without this convention, and it seemed to work the same, but it’s marked as incorrect.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are right. Usual loops that do or check something for each element of a size dim array are usually programmed as for (int i = 0; i < dim; i++) which gets you one iteration each and values for i suitable to address each array element. (Of course 0-based, i.e. starting with index 0.)

But many algorithms, notable the bubble sort which you are mentioning, look at each possible pair of neighboring elements. I.e. you look at each i and at i+1 as index, through the whole array. But doing that you need to stop BEFORE the last usually available i (being dim-1), because you cannot use dim -1 +1 for the other part of the last pair. So the last pair is dim-2 and dim-1.
A loop that will allow you in each iteration to access i and i+1 and end up using dim-2 and dim-1 is

for (int i = 0; i < dim - 1; i++)

So that is why.

(This is very close to comment by President James K. Polk, but I think turning a comment into an answer is OK and that I substantially extend it. Also I typed before realising the presence of that comment, but that is probably less of an excuse… 🙂 )

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading