Question in integer var

Why if I did not assign zero for integer variables it may return wrong negative value?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 #include<iostream>
#include<cmath>
using namespace std;
int main()
{
 int n,i;
 cout<<"please enter number"<<endl;
 cin>>n;
 cout<<"factorial of \t<<n<<"="<<endl;
 int z;
 int x=0;
 for(i=n-1; i>0;i--)
 {
 z=n*i;
 cout<<n<<"*"<<i<<"="<<z<<endl;
 x=x+z;  // I must give x zero in the declaration. Why?
 }
 cout<<"total is"<<x<<endl;
} 
Are you talking about line 11?

If you have int x;, it will not automatically given a proper value. It is not implicitly 0. It is undefined behavior to use a variable that isn't initialized.

Think of it another way: If you have A = <undetermined value> + B;, then what is the value of A? An undetermined value plus another value is still an undetermined value.
Last edited on
On top of the above, a second issue:

factorial grows very fast.
int, being 32 bits, is only 31 bits when signed. that is 2.1 billion. 12 is the largest you can compute before it overflows. When a signed number overflows, it turns negative, due to how 2's complement works; look that up if you do not understand what is happening.

put factorial down until the above makes sense. just play with an integer:
1
2
3
4
5
6
7
8
#include<iostream>
using std::cout;
int main()
{
char c = 127;
c += 1;
cout << (int)c << '\n'; //what do you get?! why?!
}



the above is what your problem probably is .... assuming your factorial is correct and you put in something too big to handle.

Last edited on
That code wouldn't compute a factorial irrespective of whether x and/or z is initialised.
Ganado (3649) thank you for reply

your rule means i have to assign value to any var before using it in equation ?
does this rule apply to all types?

thanks for your help.
best regards
Yes, assign values to built-in types like ints before using them.
> cout<<"factorial of \t<<n<<"="<<endl;
The wacky colour scheme that's in the 2nd half of your code suggests you're missing a " somewhere.

Is this your real code, or something you paraphrased together to ask a question?
Topic archived. No new replies allowed.