-1

If I have an array like a[100] and I start from 1 or 0. When I declare int a[100], how long is my array?

It always starts counting from 0? If yes it will be an array with 101 spaces.

#include <iostream>

using namespace std;

int main()
{
    float time[20]; //
    int a, first = 20, y, x;
    for (x = 1; x < 21; x++) {
        cout << "Enter the time of the person number " << x << " : ";
        cin >> time[x];
    }
    for (y = 1; y < 20; y++) {
        if (time[y] < first) {
            first = time[y];
            a = y;
        }
    }
    getchar();
    cout << "The person " << a << " was the faster.";
    cout << time[1];
    getchar();
    return 0;
}

Here it starts from 1.

And if I change it will start from 0.

for (x=0;x<21;x++)

for (y=0;y<20;y++)

And why is much better to start from 0?

Marek R
  • 32,568
  • 6
  • 55
  • 140
Ana Niorba
  • 29
  • 5
  • 1
    This should have been taught in just about any decent (or even bad) book, tutorial or class. If you missed it, then please go back to your book, tutorial or class (and your notes) and refresh and reread. – Some programmer dude Oct 22 '19 at 14:51
  • 3
    Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Oct 22 '19 at 14:52
  • ***And why is much better to start from 0 ?*** This is a language requirement. The first item is 0 units from the start of the array. – drescherjm Oct 22 '19 at 15:04
  • "why is much better to start from 0" - Because that's the first element of an array in C++. Why is it like that? It makes some situations with pointer arithmetic simpler. – Jesper Juhl Oct 22 '19 at 15:07
  • 1
    Related: [https://stackoverflow.com/questions/7320686/why-does-the-indexing-start-with-zero-in-c](https://stackoverflow.com/questions/7320686/why-does-the-indexing-start-with-zero-in-c) – drescherjm Oct 22 '19 at 15:09
  • You do know you are allowed to do research? (Or does your internet access limit you) Consider trying Google (as well as SO). For Google, perhaps try "why array index start from 0" – 2785528 Oct 22 '19 at 19:39

3 Answers3

5

C++ uses 0-indexing, so, for int a[20]; valid indexes are 0, .., 19.

a[20] does out of bound access, leading to UB.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
4

"When I declare int a[100] , how long is my array"

It is 100 elements in size. The valid indices are a[0] through a[99] (both inclusive). Index a[100] is past the end of the array (out of bounds).

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
1

In c++ arrays always start from 0 index and the number you passed in the brackets is the size of array. If you write, int A[10] ... It means you can store 10 element in the array, but the indexing begins from 0 and goes up to 9.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70