grt.dan
grt.dan

Reputation: 3

C++ need to figure out why this for loop doesn't work

I need to find the number of digits that each number from 1 to 40 has. Looks like it should be simple using for and while loops, but I can't get it to work.

I have tried to do this with "cin>>a;", entering the value of "a" from the keyboard and the while loop worked perfectly for any number I've entered, but when I try to do it with a for loop, it doesn't work, so the problem must be there.

int main()
    {
        int a; //initially found number
        int digits=0; //number of digits number "a" has
        int temp; // temporary number "a"

    for(a=1;a<=40;a++) // takes a number, starting from 1
    {
        temp=a;

        while(temp!=0) //finds number of digits the number "a" has
        {
            temp=temp/10;
            digits++;
        }
        cout<<digits<<endl; //prints number of digits each found number "a" has
    }

    return 0;
    }

What I should get, is: 1 for every number from 1 to 9, then 2 for every number from 10 to 99 and so on. What I get right now is 1 2 3 4 5 6 7 8 9 11 13 15 17 19, etc. (only showing uneven numbers going further) I would really appreciate any help.

Upvotes: -1

Views: 35

Answers (1)

Iman Kianrostami
Iman Kianrostami

Reputation: 502

You are not reseting digits value. You should add the line digits = 0 at the start of each iteration.

int main()
{
    int a; //initially found number
    int digits=0; //number of digits number "a" has
    int temp; // temporary number "a"

    for(a=1;a<=40;a++) // takes a number, starting from 1
    {
        digits=0;
        temp=a;

        while(temp!=0) //finds number of digits the number "a" has
        {
            temp=temp/10;
            digits++;
        }
        cout<<digits<<endl; //prints number of digits each found number "a" has
    }

    return 0;
}

Upvotes: 1

Related Questions