In: Computer Science
Write a C++ program that keeps asking user to enter a positive integer number until a sentinel value (999) is entered.
Then for each positive number entered by the user, find out how many digits it consists. (Hint: divide a number by 10 will remove one digit from the number. You can count how many divisions it needs to bring the number to 0.)
An example of executing such a program is shown below. Note that the user input is in italic font.
Enter 999 to end this program. Please enter a positive integer number: 1984 There are 4 digits in the number you just entered. Enter 999 to end this program. Please enter a positive integer number: -98 It must be a positive value. Please enter a positive integer number: -8 It must be a positive value. Please enter a positive integer number: 0 It must be a positive value. Please enter a positive integer number: 6856298 There are 7 digits in the number you just entered. Enter 999 to end this program. Please enter a positive integer number: -9 It must be a positive value. Please enter a positive integer number: 999 Bye!
In this program, you can safely assume that user will always enter the integer values for input.
C++ code:
#include <iostream>
using namespace std;
int main()
{
//initializing nuumber and count
int num,count;
//asking to enter 999 to end program
cout<<"Enter 999 to end this
program."<<endl;
//asking for positive integer
cout<<"Please enter a positive integer
number: ";
//accepting it
cin>>num;
//looping till user enter 999
while(num!=999){
//checking if the number
is less than or equal to 0
if(num<=0)
//printing it must be positive value
cout<<"It must be a positive value."<<endl;
else{
//initializing count as 0
count=0;
//looping till number is 0
while(num!=0){
//incrementing count
count++;
//dividing number by 10
num/=10;
}
//printing number of digits
cout<<"There are "<<count<<" digits in the number
you just entered."<<endl;
//asking to enter 999 to end program
cout<<"\nEnter 999 to end this program."<<endl;
}
//asking for positive
integer
cout<<"Please
enter a positive integer number: ";
//accepting it
cin>>num;
}
//printing Bye
cout<<"Bye!"<<endl;
return 0;
}
Screenshot:
Input and Output: