C++ tutorial, C++ programs, C++ Exercises, C++ Example Programs

Saturday, March 24, 2018

C++ Program To Count Number of Digits in a Given Number

Q: Input an integer number. Find and show the COUNT of digits of given number.

      For example, if given number is 123 then answer will be Count of digits = 3
      because 123  consists of  3 digits.
C++ Program to count number of digits in a given number
C++ Program to count number of digits in a given number


The Actual C++ Code of Add Digits of a given number Program

/*
Program to input a number, then display count of its digits.
(c) Www.EasyCppProgramming.Blogspot.Com for Easyway C++ Programs
www.ComputerGap.com for perfect computer study notes
*/
#include<iostream.h>
#include<conio.h>

void main()

{

     int num, temp, count=0, r, q;

     clrscr();

     cout<<"Enter a number to Count its Digits=";

     cin>>num;

     temp = num;

     while ( temp>0 )

     {
       q = temp/10;

       count++;

       temp = q;

     }

     cout<<"\n The Count of digits of given number "<<num<<"  =  "<<count;

     getch();

     }

The Working of  C++ Code of count Digits of a given number Program

Each and Every Statement Explained

This program is of reverse number logic.

1. We will divide 123 by 10 and get quotient=12, r = 3
2. increment count by 1 so count =1

3. Now put q =12 into dividend number
4. so divide 12 by 10, quotient=1 and remainder r=2.
5. increment count by 1, so count =2
6. now put q=1 into dividend number

7. Now divide 1 by 10, quotient=0 and r=1.
8. increment to count by 1 so count=3
9. now put quotient=0 into dividend number called temp variable
10. so that while loop test condition while (temp>0) becomes false and loop terminates.

11. Therefore display the answer count of digits of number 123 = 3


C++ Program to count number of digits in a given number sample run output
C++ Program to count number of digits in a given number sample run output

/*
Program to input a number, then display count of its digits. with comments /documentation
(c) Www.EasyCppProgramming.Blogspot.Com
*/
#include<iostream.h>     // include header files
#include<conio.h>

void main()
{
     int num, temp, sum=0, r, q;
     clrscr();
     cout<<"Enter a number to count its Digits=";
     cin>>num;                 // input number
     temp = num;             // copy number into temp variable
     while ( temp>0 )      // loop while temp is greater than zero
     {
       q = temp/10;      // calculate quotient = temp number / 10, if num is 123 then q=12
     
       count++ ;  // starting from 0, increment to count = 1
                               
       temp = q;      // set next time dividend     temp=12
     }
     cout<<"\n The Count of digits of given number "<<num<<"  =  "<<count;     //count=3
     getch();
     }

Share:

0 comments:

Post a Comment

We Love To Hear From You!

EasyCPPprogramming.blogspotcom

Labels