Last element of an array is appearing different result in diff compilers

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;

int main() {

int n;
int a[n];
int numberOfSwaps = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
numberOfSwaps++;
}
}
}
for (int i = 0; i < n; i++) {
cout << a[i];
}

cout << "Array is sorted in " << numberOfSwaps <<" "<<"swaps"<<"\n";
cout << "First Element: " << a[0]<<"\n";
cout << "Last Element: " << a[n-1]<<"\n"; // This a[n-1] is acting weird with respect to compilers. any ideas why?

/* Enter your code here. Read input from STDIN. Print output to STDOUT
*/
return 0;
}
Last edited on
Edit your post and put your code in code tags.

This part is obviously wrong:

1
2
int n;
int a[n];   // what is the value of n when this statement is encountered? 

It looks like you meant:

1
2
3
int n;
cin >> n;
int a[n];

But even that is problematic since standard C++ doesn't have variable-length arrays. Instead, use a vector:

1
2
3
int n;
cin >> n;
vector<int> a(n);

Yes, I understood where I went wrong

int n;
cin >> n;
int a[n];

This is the right way for my task.
thankyou
This is the right way for my task.

As long as you know that it isn't C++.
> Last element of an array is appearing different result in diff compilers

...

> This is the right way for my task.
You're still going to get different results on different compilers, but you just don't know it yet.

Topic archived. No new replies allowed.