The fundamental problem with your code is that you are using an undefined memory location, lists[30], because you declared an array with 30 elements, but address the ordinal 31st position of the array. Both C and C++ start indexing arrays from zero (0), so the actual last valid position in the array is 30-1 = 29, thus lists[30] is an invalid memory location.
Because you declared one additional variable, a, on the stack (the same memory location where lists[30] is placed), and your compiler placed that variable in memory adjacent to the array, list[30], when you assign a value to the variable a, you are also changing the value that you are addressing using the (invalid) memory location lists[30] (this is dependent upon where your compiler choose to place variables when declared, so this program may run differently on different architectures).
#include <iostream>
using namespace std;
int main()
{
This line defines an array of 30 int with valid indices 0..29
int lists[30];
Want your program to work? change the number 30 above to 31
int lists[30+1];
Or, you could at least make the variable a work by placing another variable on the stack between lists[30] and a,
int filler;
This line addresses an invalid location, index 30, which is a location on the 'stack', adjacent to list[29], and assigns a value to that memory location
lists[30] = 30;
lists[0] = 31;
What value do you think list[2] contains?
This line addresses an invalid location, index 30, and this time references the memory at that location
cout << lists[30];
cout << "\n";
cout << lists[0];
Yet again, lists[30] is invalid, same problem as before. Since int a is allocated on the stack, lists
for(int a = 0; a < lists[30]+lists[0]; a++)
{
cout << "\n";
You have not yet assigned a value to lists[2], what do you think the value is?
cout << lists[2];
}
}
The same problem with array indexing would occur in any language that is zero-indexed and does not check array bounds.