Hi! I am an beginner c++ programmer. Today I was writing some small program that gets a number and tell you how many digits it has. First of all, I defined a function for raising a number to a definite power. I wrote this:
1 2 3 4 5 6 7 8 9 10 11 12 13
int power(int x, int y)
{
int i;
int result = 1;
while (i < y)
{
result *= x;
i++;
}
return result;
}
I know now what was wrong with it. In the line three I hadn't set a value for i. So adding one to it and comparing it to y was absurd. But it worked! So I didn't noticed my mistake and keeped on:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main ()
{
int a;
int b;
int i=-1;
cin >> a;
while (b != 0)
{
i++;
b = a / power (10,i);
}
cout << i;
return 0;
}
When I executed this and gave it a number greater than 9, it would go in a vicious circle. After a lot of struggling with its code I noticed that mentioned mistake and corrected it(By giving it the initial value of 0) and the code worked! But I can not get it. Why is that? Why despite my mistake the function worked, but when I decided to use it in a loop, it went screwed?
I am not a native speaker, so pardon any probable grammatical mistake. Thanks a lot.