• Register
3,890 points
11 5 1
Welcome to Kodlogs, programming questions and answer website.

In this tutorial, we are going to explore different methods of finding the length of an integer in C++. Although, there are many methods available to perform this task we will explore some of them.

Using For loop:

Let's start with finding the length of a Number in C++ by using the for loop which is only suitable for positive numbers;

#include<iostream>

using namespace std;

int main()

{

int num;

int i;

cout<<"Please enter a number to find its length"<<endl;

cin>>num;

for(;num>0; i++)

{

num=num/10;

}

cout<<"the length of the number is = "<<i<<endl;

system("pause");

}

By using functions:

Now we will explore this by using the Functions, Functions are more suitable because we can use that component again and again effectively and efficiently.

#include<iostream>

using namespace std;

int length(int,int&);

int main()

{

int n;

int p;

cout<<"Please enter a number to find its length"<<endl;

cin>>n;

length(n,p);

cout<<"the length of the number is = "<<p<<endl;

system("pause");

}


int length(int num, int &i)

{

i=0;

do

{

num=num/10;

i++;

}

while(num>0);


}

Note:

To perform this task with negative integers, the users must have to use Math.abs(number) to convert a negative number into a positive number for using any of the methods.

3,890 points
11 5 1