GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing codescracker.com — C++ Program to Count the Total Digits in a Number
C++ Program to Count the Total Digits in a NumberThis article provides some programs in C++ that count the total number of digits available in a number entered by the user at run-time of the program. This article deals with:
For example, if the user enters a number like 13204, the output will be 5. because there are 5 digits available in the given number. Using the while loop, count the total digits in a numberThe question is: write a C++ program that receives a number from the user and counts and prints the total number of digits available in that given number. Here is the answer to this question: #include<iostream> using namespace std; int main() { int num, tot=0; cout<<"Enter the Number: "; cin>>num; while(num>0) { tot++; num = num/10; } cout<<"\nTotal Digits = "<<tot; cout<<endl; return 0; } Here is the initial output produced by the above C++ program on counting the total number of digits available in a given number by the user at run-time: Now enter a number, say 43024, as input and press the ENTER key to see the output as shown in the snapshot given below: The following is the dry run of the above program with user input 43024:
Count Digits in a Number using the for LoopThis program does the same job as the previous program. The only difference is its approach. That is, unlike the previous program, this one is written in a for loop rather than a while loop. #include<iostream> using namespace std; int main() { int num, tot; cout<<"Enter the Number: "; cin>>num; for(tot=0; num>0; tot++) num = num/10; cout<<"\nTotal Digits = "<<tot; cout<<endl; return 0; } This program produces the same output as the previous program. Using a Function, Count the Digits in a NumberThis is the last program on counting the total number of digits available in a number entered by the user using a user-defined function like shown in the program given below: #include<iostream> using namespace std; int myfun(int); int main() { int num, tot; cout<<"Enter the Number: "; cin>>num; tot = myfun(num); cout<<"\nTotal Digits = "<<tot; cout<<endl; return 0; } int myfun(int n) { int t; for(t=0; n>0; t++) n /= 10; return t; } « Previous Program Next Program » Practice Quizzes
Test your programming and computer science knowledge with interactive MCQs and topic-based quizzes. Popular Topics
Explore the most popular programming and computer science tutorials on CodesCracker. |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |