Monday, May 24, 2010

In C++ how do you add up integers that a user inputs?

for example


int num;


cin%26gt;%26gt;num;


//USER INPUTS


88


76


67


45


what do you do to get the total.

In C++ how do you add up integers that a user inputs?
main()


{int num=0;


int sum=0;


do


{


cout%26lt;%26lt;"enter numbers greater than 0 to sum up" ;


cin%26gt;%26gt;num;


sum+=num;


}


while(num%26gt;0);


cout%26lt;%26lt;"sum="%26lt;%26lt;sum;


}
Reply:#include%26lt;iostream%26gt;





int main(){





int num = 0;





while(num != -1){


int input = 0;





std::cin %26gt;%26gt; input;





num += input;


};





std::cout %26lt;%26lt; num %26lt;%26lt; '\n';


return 0;


};








that will input numbers until the user enters the sentinel value -1, num needs to be declared outside the loop so its scope is correct


No comments:

Post a Comment