Need help with something.

I am practicing arrays, but then whenever I try to run this code, it shows up

Enter 10 numbers.
First array is 2686728
Process returned 0 (0x0)

Here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  #include <iostream>
using namespace std;

int main () {

    int i[10];
   cout<<"Enter 10 numbers.\n";
   for( int a = 1; a > 11; a++ ) {
      cout<<"Enter number: ";
      cin>>i[a];
   }
   cout<<"First array is "<<i[1];
   return 0;
}
You get a junk value like 2686728 because your array indices are never initialized or set.

This is fundamental: Array indices start at 0 and end at length-1.
So, in your case, valid array indices range from 0 to 9, inclusive.

Also, your for loop logic is wrong. a > 11 will never be true because you have a starting at 1.

Last, an "array" is the whole data structure. One unit of data of the array is called an array element.

Here's your fixed code. Study it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

int main () { 

    int i[10];
    cout << "Enter 10 numbers.\n";
    for (int a = 0; a < 10; a++) {
        cout << "Enter number: ";
        cin >> i[a];
    }
    cout << "First array element is " << i[0];
    return 0;
}


BTW: It's not a requirement, but variables like "i" are usually meant to be used as loop increments and not as names of arrays or other objects.

Better variables names:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

int main () { 

    int arr[10];
    cout << "Enter 10 numbers.\n";
    for (int i = 0; i < 10; i++) {
        cout << "Enter number: ";
        cin >> arr[i];
    }
    cout << "First array element is " << arr[0];
    return 0;
}
Last edited on
Thanks for the fast reply.
Topic archived. No new replies allowed.