In: Computer Science
Write a complete C++ program that prompts the user for and takes as input, numbers until the user types in a negative number. the program should add all of the numbers together. Then if the result is less than 20 the program should multiply the result by 3, otherwise subtract 2 from the result. Finally, the program should printout the result.
CODE IN C++ :
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter a number: ";
cin >> num;
int result = 0;
while(num >= 0) // While number is non-negative
{
result += num; // add the number
cout << "Enter a number: ";
cin >> num;
}
if(result < 20) // if result is less than 20, multipky by
3
{
result = result*3;
}
else // else subtract 2
{
result = result-2;
}
cout << "The result is: " << result <<
endl;
return 0;
}
OUTPUT SNIPPET :
1+2+3 = 6 < 20, RESULT IS MULTIPLIED BY 3 WHICH BECOMES 6*3 = 18
11+13+15 = 39 WHICH IS GREATER THAN 20, RESULT BECOMES 39-2 =
37
Hope this resolves your doubt. Please give an upvote if you liked
my solution. Thank you :)