ed ga
ed ga

Reputation: 1

Counting digits of a number in a certain interval

I have to make a c++ program which calculates if the number within the interval [m=1000;n=1100] has an even number of digits.

But using this program that I wrote, I get an endless loop.

int digits(int m, int n)
{
    int i, count_digits = 0;

    for(i = m; i < n; i++)
    {
        while(i != 0)
        {
            i = i/10;
            count_digits++;
        }
    }
    if(k%2 == 0) return count_digits;
}

Upvotes: 0

Views: 90

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

Within the loop

for(i = m; i < n; i++)
{
    while(i != 0)
    {
        i = i/10;
        count_digits++;
    }
}

you are changing the variable i.

Introduce one more local variable

for(i = m; i < n; i++)
{
    int value = i;
    while(value != 0)
    {
        value /= 10;
        count_digits++;
    }
}

It seems you also need to reinitialize the variable count_digits in each iteration of the loop.

for(i = m; i < n; i++)
{
    int value = i;
    count_digits = 0;
    while(value != 0)
    {
        value /= 10;
        count_digits++;
    }
}

Pay attention to that your loop is executed in the range of values [m, n-1] instead of the range [m, n] as you wrote in your question.

Also it is unclear where the variable k used in this statement

if(k%2 == 0) return count_digits;

is declared.

I can guess that you need something like the following

#include <iostream>

int main() 
{
    const int M = 1000;
    const int N = 1100;
    const int Base = 10;

    for ( int i = M; i <= N; i++ )
    {
        int value = i;
        size_t count_digits = 0;

        do 
        { 
            if ( value % Base != 0 ) ++count_digits; 

        } while ( value /= Base );

        if ( count_digits % 2 == 0 ) std::cout << i << ' ';
    }

    std::cout << '\n';

    return 0;
}

The program output is

1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1020 1030 1040 1050 1060 1070 1080 1090 1100

In any case you can consider the program as a base for your program.

Upvotes: 1

Related Questions