Write a C++ program to prompt a user for a positive integer and print the number of even and odd digits (0 is even). Sample run:
Enter a positive integer: -4580
Invalid.
Enter a positive integer: 12146
2 odd digits
3 even digits
Code:
#include <iostream>
using namespace std;
int main() {
cout<<"Enter a positive integer:";
int r=0,even=0,odd=0;
cin>>r;
while(r<0){
cout<<"Invalid"<<endl;
cout<<"Enter a positive integer:";
cin>>r;
}
while(r>0){
int c=r%10;
if(c%2==0)even++;
else if(c%2==1)odd++;
r=r/10;
}
cout<<odd<<" odd digits"<<endl;
cout<<even<<" even digits"<<endl;
}
Output:
Enter a positive integer:-4580
Invalid
Enter a positive integer:12146
2 odd digits
3 even digits
Get Answers For Free
Most questions answered within 1 hours.