Write a complete C++ program asking the user to enter numbers one by one. User enters only whole numbers 0 and 10. Once the user enters 0, then the program should print sum of only odd numbers entered by user prior to 0. A valid scenario given below:
Enter a number: 5
Enter a number: 3
Enter a number: 2
Enter a number: 3
Enter a number: 8
Enter a number: 0
Sum of the odd numbers you entered is 11.
// C++ program to asking the user to enter numbers one by one and calculating the sum of all odd numbers entered by the user
#include <iostream>
using namespace std;
int main()
{
int sumOdd = 0;
int num;
// input of number
cout<<"Enter a number : ";
cin>>num;
// loop that continues till user enters 0
while(num != 0)
{
// check if num is odd, add num to sumOdd
if(num%2 != 0)
sumOdd += num;
// input of number
cout<<"Enter a number : ";
cin>>num;
}
// display the sum of all odd numbers entered by the user
cout<<"Sum of the odd numbers you entered is "<<sumOdd<<endl;
return 0;
}
//end of program
Output:
Get Answers For Free
Most questions answered within 1 hours.