0

Noob question while loop

Hi everyone. I have a task from a course I'm taking. The task is to write a code that add numbers that the user inputs. If the user tries to input 0, the program must end. I'm trying to figure it out how does it work and running out of ideas at this point. Any critics will be appreciated :) #include <iostream> using namespace std; int number;int another; int sum; int main() { cout<<"Input number: "<<endl; cin>>number; while(number !=0) { cout<<"Input another one: "<<endl; cin>>another; sum = number+another; cout<<sum<<endl; cout<<"Input another one: "<<endl; cin>>another; cout<<sum+another<<endl; } return 0; }

29th Dec 2016, 8:44 PM
Mateusz Banaszak
Mateusz Banaszak - avatar
4 Réponses
+ 2
(global variable should be avoided) int main(){ int val,sum=0; do{ cin>>val; sum+=val; }while(val); return 0; }
29th Dec 2016, 9:24 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
#include <iostream> using namespace std; int main() { int x=1; //this is just initial value int sum=0; while(x!=0) { cout<<"enter number"<<endl; cin>>x; sum=sum+x; } cout<<sum; return 0; } is this what you need?
29th Dec 2016, 10:40 PM
Leonida17st
Leonida17st - avatar
+ 1
Thank you very much ! :)
30th Dec 2016, 8:48 AM
Mateusz Banaszak
Mateusz Banaszak - avatar
+ 1
your welcome :)
30th Dec 2016, 12:11 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar