In: Computer Science
Modify the program to double each number in the vector.
#include <iostream> #include <vector> using namespace std; int main() { const int N=8; vector<int> nums(N); // User numbers int i=0; // Loop index cout << "\nEnter " << N << " numbers...\n"; for (i = 0; i < N; ++i) { cout << i+1 << ": "; cin >> nums.at(i); } // Convert negatives to 0 for (i = 0; i < N; ++i) { if (nums.at(i) < 0) { nums.at(i) = 0; } } // Print numbers cout << "\nNew numbers: "; for (i = 0; i < N; ++i) { cout << " " << nums.at(i); } cout << "\n"; return 0; }
Hi. According to the question, program should be modified to double each number in vector . The given program already contains a loop that convers negative numbers to 0.
So, it is unclear whether to keep this loop or remove it.(Since it is asked to modify the code)
However, two versions of the code along with sample output is added here. So, any code can be chosen based on requirement.
In the first version of code, no existing code is removed.Additional code is added to double each number in vector.
In the second version of code, one for loop is removed(converting negative numbers to 0) and additional code is added to double each number in vector.
Code Version-1( no existing code is removed):
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int N=8;
vector<int> nums(N); // User numbers
int i=0; // Loop index
cout << "\nEnter " << N << " numbers...\n";
for (i = 0; i < N; ++i) {
cout << i+1 << ": ";
cin >> nums.at(i);
}
// Convert negatives to 0
for (i = 0; i < N; ++i) {
if (nums.at(i) < 0) {
nums.at(i) = 0;
}
}
// Double each number in the vector
for (i=0; i < N; ++i) {
int num=nums.at(i); //gets the value at index i and stores it in variable 'num'
nums.at(i)=num*2; //doubles the value of number at index i
}
// Print numbers
cout << "\nNew numbers: ";
for (i = 0; i < N; ++i) {
cout << " " << nums.at(i);
}
cout << "\n";
return 0;
}
Sample output:
Code Version-2(One for loop is removed):
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int N=8;
vector<int> nums(N); // User numbers
int i=0; // Loop index
cout << "\nEnter " << N << " numbers...\n";
for (i = 0; i < N; ++i) {
cout << i+1 << ": ";
cin >> nums.at(i);
}
// Double each number in the vector
for (i=0; i < N; ++i) {
int num=nums.at(i); //gets the value at index i and stores it in variable 'num'
nums.at(i)=num*2; //doubles the value of number at index i
}
// Print numbers
cout << "\nNew numbers: ";
for (i = 0; i < N; ++i) {
cout << " " << nums.at(i);
}
cout << "\n";
return 0;
}
Sample output: