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; }
4 Answers
+ 2
(global variable should be avoided)
int main(){
int val,sum=0;
do{
cin>>val;
sum+=val;
}while(val);
return 0;
}
+ 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?
+ 1
Thank you very much ! :)
+ 1
your welcome :)