You have two different variables, a local variable and a global variable, but as you have given both of them the same name, you don't see that difference. Let me show you in a clearer way what you have programmed:
#include <iostream>
using namespace std;
int global_a[100],n;
void citire(int n)
{
int local_a[100];
for(int i = 0 ; i < n ; i ++) { // the for loop
cin >> local_a[i]; // entering the numbers for each
}
cout << local_a[5] << endl; // returns the right number
}
int main()
{
cout << "n= "; cin >> n; // how many numbers should the vector have.
citire(n); // me calling the function
cout << global_a[5]; // returns 0
}
Now, you tell me, where did you store any variable in the array global_a
?
In order to avoid this, you might do the following:
#include <iostream>
using namespace std;
int global_a[100],n;
void citire(int n)
{
// int a[100]; don't declare a local variable, so while referring to "a",
// the global variable will be used:
for(int i = 0 ; i < n ; i ++) { // the for loop
cin >> global_a[i]; // entering the numbers for each
}
cout << global_a[5] << endl; // returns the right number
}
int main()
{
cout << "n= "; cin >> n; // how many numbers should the vector have.
citire(n); // me calling the function
cout << global_a[5]; // returns 0
}
For your information, the prefixes "local_" and "global_" are just there for clarification purposes. In the last example, you might just write "a" instead of "global_a", the result will be the same.