The code written below gives the output 3 when values entered each time is 1.
i want know why doesn't it add up to 5 and why is the output 3.
Please explain me .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
int main()
{
int x=0,y,z;
while(x<5){
cin>>y;
z=z+y;
x++;
}
cout<<z;
}
To expand on TN's answer, when you create the int value z it has a random value. Could be anything.
In C++, when you create a variable, if you want it to be set to some value (for example, zero) you have to do that yourself.
There are a few circumstances where you don't, but for someone at your level, just remember; if you want a variable to start with a value (such as zero), you have to set it yourself.
This is an example of undefined behavior. It means the C++ language standard doesn't make any guarantees about what could happen. z could be initialized to -2, like in your case, but on some other computer it might be initialized to 100, -4 or whatever you can think off.
It isn't even guaranteed that your program will run when you try to use the uninitialized variable. The compiler is allowed to do anything, like erase your hard drive, invite a clown or let demons come flying out of your nose (look up nasal demons, it's another name for undefined behavior).