### Finding Errors

Original:
https://i.imgur.com/h1wZgHa.png

Objective:
sum all entered int values that are greater than 5

This is what I came up with:
 123456789101112 #include using namespace std; int main() { int x, sum; while (x < 10) { cin >> x; if (x > 5) sum == sum +x; } cout << "" << sum <

No matter what I input, nothing shows up on the output.
What errors did I miss/overlook?
Last edited on
Few issues.
 In function 'int main()': 9:17: warning: statement has no effect [-Wunused-value] 6:14: warning: 'x' is used uninitialized in this function [-Wuninitialized] 11:19: warning: 'sum' is used uninitialized in this function [-Wuninitialized]

(1) you must initialize a variable, it is not automatically 0.
 12 int x = 0; int sum = 0;

(2) == tests for equality
= is the assignment operator.

Change line 9 to sum = sum + x;

(You actually somehow managed to do the opposite of what almost every new programmer gets confused on. Usually people accidentally put = where they ought to put ==. I'm actually impressed.)

Anyway, here's what your program would look like fixed. Try to study it to learn.

 1234567891011121314 #include using namespace std; int main() { int x = 0; int sum = 0; while (x < 10) { cin >> x; if (x > 5) sum = sum + x; } cout << sum << endl; }

example:
 4 5 6 7 8 9 10 40 <-- sum = 6 + 7 + 8 + 9 + 10

Your program is a bit ambiguous, though. Nowhere does it say it should stop summing after summing including the first number 10 or greater. Or is your intention to run the a loop exactly 10 times?
Last edited on
If I needed to modify this program to sum up the integers of the input, (ex. {1,2,3,-3,2,1} )
would I use an array or string to hold these values?
If you needed to hold the values, you would use an array of type int, or in modern C++, usually an std::vector<int>.

 1234567891011121314151617181920 #include #include int main() { std::vector arr; const int num_inputs = 10; for (int i = 0; i < num_inputs ; i++) { int n; std::cin >> n; arr.push_back(n); } int sum = 0; for (size_t i = 0; i < arr.size(); i++) sum = sum + arr[i]; std::cout << sum << std::endl; }
Last edited on
Topic archived. No new replies allowed.