In: Computer Science
Can somebody explain me what this code does in a few or one sentence?
#include <iostream>
#include <vector>
using namespace std;
int main () {
const int NUM_ELEMENTS = 8;
vector<int> numbers(NUM_ELEMENTS);
int i = 0;
int tmpValue = 0;
cout << "Enter " << NUM_ELEMENTS
<< " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cout << "Enter Value#"
<< i+1 << ": ";
cin >> numbers.at(i);
}
for (i = 0; i < (NUM_ELEMENTS /2); ++i) {
tmpValue = numbers.at(i);
numbers.at(i) =
numbers.at(NUM_ELEMENTS - 1 - i);
numbers.at(NUM_ELEMENTS - 1 - i) =
tmpValue;
}
system ("pause");
return 0;
}
Thanks for the question, the program asks the user to enter 8 numbers and store them in the vector, then it reverses the number from left to right. So the 1st element is swapped with the 8th element, 2nd element position is swapped with the 7th element, 3rd with 6th, 4th with 5th
Here are the comments and the output screenshot to illustrate, I added few codes to print the before and after-effects.
====================================================================
#include <iostream>
#include <vector>
using namespace std;
int main () {
const int NUM_ELEMENTS = 8;
vector<int> numbers(NUM_ELEMENTS);
int i = 0;
int tmpValue = 0;
cout << "Enter " << NUM_ELEMENTS << "
integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cout << "Enter Value#" << i+1 << ": ";
cin >> numbers.at(i);
}
for (i = 0; i < NUM_ELEMENTS; ++i) {
cout << numbers.at(i)<< " ";
}
cout<<endl;
// the function reverses the number in the vector
// iterate till the middle element
for (i = 0; i < (NUM_ELEMENTS /2); ++i) {
// get the first number
tmpValue = numbers.at(i);
// get the last number and iterchange them
numbers.at(i) = numbers.at(NUM_ELEMENTS - 1 - i);
numbers.at(NUM_ELEMENTS - 1 - i) = tmpValue;
}
for (i = 0; i < NUM_ELEMENTS; ++i) {
cout << numbers.at(i)<< " ";
}
cout<<endl;
system ("pause");
return 0;
}
=================================================================
