While loop in C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

While loop in C++

Can anyone please explain me why this Code Just asks one time the User for an input? #include <iostream> using namespace std; int main() { int x, sum; int y = 2; int i = 1; while (i <= 5){ cout << "Give x a number\n"; cin >> x; sum = y +x; cout << sum << endl; i++; } return 0; } Output: Give x a number 3 Give x a number 3 ....

28th Jul 2021, 5:21 PM
Abdullah Yusuf
Abdullah Yusuf - avatar
2 Answers
+ 5
It's because you're doing it from the Code Playground. Due to security concerns and restrictions, since it's being executed from their server, you're only able to give all input up front before it's sent to their server. If you tried to do it locally from your machine or server, it'd work as you expect it to and would prompt you at each iteration of the loop. :::INPUT::: 1 2 3 4 5 ::::OUTPUT::::: Give x a number 3 Give x a number 4 Give x a number 5 Give x a number 6 Give x a number 7
28th Jul 2021, 6:06 PM
Jakko Jak
Jakko Jak - avatar
+ 3
If you trying to run this code in sololearn playground then try to split multiple inputs in different lines for eg. Input: 3 4 5 2 1 This will give you desired output you must split multiple inputs on different line in sl playground respective to cin And as you only putting input as '3', x = 3 is set for rest of inputs as well
28th Jul 2021, 6:04 PM
Shunon
Shunon - avatar