Hello there, I am beginner in C++, coding for like day or two.
My friend, who insisted, that I should learn how to code, gave me an excercise: make a program with function, that checks, if given number is happy, or not.
I am too green, to be able to check my problem effectively in google, cause I don't really know what keywords I should use. Checked "function in loop c++" and some similars and didn't come to solution. It is probably some very basic mistake, but still - cannot find it ;/
Here is sampled code, that I talk about [in reality code is a little big bigger, cause there is also another function, that checks, if number is happy or not, but error occured even earlier].
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#include <iostream>
using namespace std;
int bitdown(int a) /*This is function "break it down", which calculates the sum of squared digits of a number, which is then required to check, if number is happy or not. It works properly, if copied into main function and cin>> any number within int range*/
int b, c=10, d, e=1, f=0, tab[f+1];
while(b!=0)
{
b=a/c; /*loop closes, after it gives 0, this ensures, that you can use number of any size you want*/
d=(a%c)/e; /*gives you digits of number*/
tab[f]=d; //puts these digits into table
f++;
c=c*10;
e=e*10;
}
a=0;
while(f>0)
{
a=a+tab[f-1]*tab[f-1]; //extract digits from table and make sum of squares
f--;
}
return a;
}
int main (int argc, char** argv){ /*main function, where I make test, if function bitdown works properly, if looped*/
int a, b;
cin >> a;
for (b=0;b<3;b++)
{
a=bitdown(a); // test occurs here
cout << a <<endl;
}
return 0;
}
|
The result I expect for 7 is:
49
97
130.
What I get is:
49
0
0.
I suspect there is some property of language itself, that I don't understand yet, cause when it comes to formal mistakes, like calibraces, comas and other - it seems allright.
Thanks for any help!