I'm trying to figure out on how to rotate arrays. I got information from a file and put it into an array. Now I'm trying to figure out how to rotate the array to the right. The file reads:
9
23 19
-3 7892 12
7 4000 0 44
The first number states how many numbers there are the rest of the numbers are part of the array. Any ideas? Help? Thanks!
#include <iostream>
#include <fstream>
#include <cstdlib>
usingnamespace std;
int main()
{
constint ARRAY_SIZE = 25;
int numbers[ARRAY_SIZE];
char fname[100];
ifstream inputFile;
int header;
int count = 0;
cout << "Please enter the name of the input file: ";
cin >> fname;
inputFile.open(fname);
if(!inputFile)
{
cout << "Input file not found" << endl;
exit(0);
}
inputFile >> header;
cout << "The amount of numbers in the file is " << header << endl;
while (count < ARRAY_SIZE && inputFile >> numbers[count])
count++;
inputFile.close();
cout << "The numbers are: ";
for (int index = 0; index < count; index++)
cout << numbers[index] << " ";
cout << endl;
cout << "The array elements rotated by one are:\n";
return 0;
}
The rotation can be accomplished by swapping array values and using a variable to temporarily store overwritten values. For the array int numbers[3] = {1, 2, 3, 4};
The rotation could work something like this:
1) swap 1 and 2. We have {2, 1, 3, 4}
2) swap 2 and 3. We have {3, 1, 2, 4}
3) swap 3 and 4. We have {4, 1, 2, 3}
Notice that all the swaps involve the first value of the array. I'll leave it to you to write the code.