intlen in c++
#include <iostream>
using namespace std;
int intlen(int num) {
int length = 0;
while (num != 0) {
num /= 10;
length++;
}
return length;
}
int main() {
int number = 3579;
int length = intlen(number);
cout << "The length of " << number << " is: " << length << endl;
return 0;
}
Include Libraries: The code includes the iostream library to enable input and output operations in C++.
Namespace: The
using namespace std;
line allows using elements from the standard C++ library without explicitly qualifying them withstd::
.Function intlen: Defines a function named
intlen
that takes an integernum
as a parameter and returns an integer value. This function is meant to calculate the length of the integer by counting the number of digits it contains.Variable Declaration: Inside
intlen
, an integer variablelength
is declared and initialized to 0. This variable will store the length of the integer.While Loop: A
while
loop is used to iterate untilnum
becomes 0. Inside the loop,num
is divided by 10, effectively removing the last digit, andlength
is incremented by 1.Return Length: After the loop, the function returns the calculated length of the integer.
Main Function: The
main
function begins the program's execution.Variable Initialization: An integer variable
number
is declared and initialized to 3579.Calculating Length: The
intlen
function is called withnumber
as an argument, and the returned value is stored in thelength
variable.Output: The program outputs the original number and its length using
cout
. Theendl
is used to move the output to the next line after displaying the information.Return 0: Finally, the
main
function returns 0, indicating successful program execution to the operating system.