492,444 views
1 vote
1 vote
Read integers from input and store each integer into a vector until 0 is read. Do not store 0 into the vector. Then, output the values in the vector that are not equal to the last value in the vector, each on a new line.

Ex: If the input is -90 -10 22 -10 0, the output is:

-90
22
#include
#include
using namespace std;

int main() {

/* Your code goes here */

return 0;
}

User Ditto
by
2.7k points

2 Answers

17 votes
17 votes

Final answer:

To solve this problem, you need to read integers from input and store them in a vector until 0 is encountered. Then, output the values in the vector that are not equal to the last value in the vector.

Step-by-step explanation:

To solve this problem, you will need to use a loop to repeatedly read integers from the input and store them in a vector until a 0 is encountered. However, you should not store the 0 itself in the vector. Once the loop ends, you can iterate over the vector and output each value that is not equal to the last value in the vector.

C++ code:

#include <iostream>

#include <vector>

using namespace std;

int main() {

int num;

vector<int> numbers;

cin >> num;

while (num != 0) {

numbers.push_back(num);

cin >> num;

}

int lastValue = numbers.back();

for (int i = 0; i < numbers.size(); i++) {

if (numbers[i] != lastValue) {

cout << numbers[i] << endl;

}

}

return 0;

}

User Gussoh
by
2.9k points
15 votes
15 votes

Final answer:

The question pertains to C++ programming where integers are read into a vector until a 0 is encountered. The integers, except the last value and 0, are then output each on a new line. The provided code demonstrates how to achieve this task.

Step-by-step explanation:

The subject of the question is based on C++ programming, specifically focusing on vector manipulation and input/output operations. The grade level of the question suggests that it is suitable for College, particularly for students in introductory programming courses. Here is a solution that reads integers from the user input, stores them into a vector, and outputs the values that are not equal to the last value, excluding the value 0, which serves as a sentinel for the input termination.

#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers;
int input;
// Read integers until 0 is read
while (cin >> input && input != 0) {
numbers.push_back(input);
}

// Check if vector is not empty and proceed
if (!numbers.empty()) {
int lastValue = numbers[numbers.size() - 1];
// Output values not equal to the last value
for (int i = 0; i < numbers.size() - 1; ++i) {
if (numbers[i] != lastValue) {
cout << numbers[i] << '\\';
}
}
}
return 0;
}

User Mangesh Daundkar
by
3.1k points