LearnFrenzy
Sign in Take a free test

Input/Output with cin and cout · Predict the Output · Question 13

while (cin >> x) stops at the first non-number Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 13 Back to Exercise

What is the output of the following C++ program when the input is 5 10 15 x 20?

main.cpp
#include <iostream>

int main() {
    int x, sum = 0, n = 0;
    while (std::cin >> x) {
        sum += x;
        ++n;
    }
    std::cout << n << ' ' << sum << '\n';
    return 0;
}
  • A 3 30 Correct
  • B 4 50
  • C 5 50
  • D 3 50
Correct Answer: Option A

Reading x into an int fails, which ends the loop; 20 is never read.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links