forked from portfoliocourses/cplusplus-example-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcount_integer_digits.cpp
More file actions
64 lines (54 loc) · 1.69 KB
/
count_integer_digits.cpp
File metadata and controls
64 lines (54 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*******************************************************************************
*
* Program: Count The Number Of Digits In An Integer Number
*
* Description: Program to count the number of digits in an integer number using
* C++.
*
* YouTube Lesson: https://www.youtube.com/watch?v=w8A3GW9ILc4
*
* Author: Kevin Browne @ https://portfoliocourses.com
*
*******************************************************************************/
#include <iostream>
using namespace std;
int count_digits(int number);
int main()
{
// Test the function out with the number 5365 which has 4 digits
cout << "The number of digits in 5365: ";
cout << count_digits(5365) << endl;
return 0;
}
// We can count the number of digits in a number by continually dividing the
// starting number and resulting quotients by 10 until the number is 0:
//
// 5365 / 10 = 536
// 536 / 10 = 53
// 53 / 10 = 5
// 5 / 10 = 0
//
// The number of division operations required to reach 0 is the number of
// digits in the number. In the "special case" that the original number
// is already 0 we can say it has 1 digit.
// Returns the number of digits in the int number
int count_digits(int number)
{
// In the 'special case' the number is 0 to begin with we just return 1 as
// 0 has 1 digit
if (number == 0)
{
return 1;
}
// The variable digits stores the running count of digits in the number,
// we continually divide the number by 10 until it is equal to zero and
// count the number of divisions (i.e. the number of digits in the
// number) by incrementing digits, which we then return.
int digits = 0;
while (number != 0)
{
number = number / 10;
digits++;
}
return digits;
}