Error is:
for(int i = n; i >=2; i--)
You have to start from n-1
since array index starts from 0. Correct way to do should be
for(int i = n -1; i >=1; --i)
array index out of bound error if you start from n
. It is highly likely that pseudocode in your book (for convenience purpose) use array index from 1 to n
, but in real program with C++, we should start from 0 to n-1
instead.