Hi
I am testing myself by making a simple program that reverses the contents of an array. It works for some values but the last value of the array is not correct.
Can you take a look over my code to point out where its going wrong?
the original array is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
the output of my program is:
1, 4247750
2, 19
3, 18
4, 17
5, 16
6, 15
7, 14
8, 13
9, 12
10, 11
11, 10
12, 9
13, 8
14, 7
15, 6
16, 5
17, 4
18, 3
19, 2
4247750, 1
4247648, 4247750, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
And finally my code:
#include <iostream>
#include <fstream>
using namespace std;
void reverse_array(int array[]);
void alt_reverse_array(int array[]);
int main()
{
int array1[20];
ifstream infile;
infile.open("numbers.txt");
if (!infile)
{
cout << "Failed to open file";
return 0;
}
for (int i = 0; i < 19; i++)
{
infile >> array1[i];
}
reverse_array(array1);
alt_reverse_array(array1);
return 0;
}
void reverse_array(int array[])
{
int reverse_array[20];
int count = 0;
for (int i = 19; i >= 0; i--)
{
reverse_array[count] = array[i];
count++;
}
for ( int i = 0; i <= 19; i++)
{
cout << array[i] << ", " << reverse_array[i] << endl;
}
cout << "\n\n";
}
void alt_reverse_array(int array[])
{
int a = 0;
int b= 20;
int temp = 0;
for (int i = 0; i < 19; i++)
{
temp = array[a];
array[a] = array[b];
array[b] = temp;
a++;
b--;
}
for (int j = 0; j < 19; j++)
{
cout << array[j] << ", ";
}
}