Please explain the output received.

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>

using namespace std;

int main()
{
    int x=0,y,z;
    while(x<5){
    cin>>y;
    z=z+y;
    x++;
    }
cout<<z;
}
I get 5 not 3. Initialize z to 0.
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.
Last edited on
thanx for ur rplies
and yes ik when i set int z=0 i get 5
But i just want to know if i don't set it to 0 then why is the answer coming out to be 3
Because it begins at -2.
And why so can you explain ?
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).
Thank you everyone and Shadowwolf for explaining me and giving me the answer to the question.
Topic archived. No new replies allowed.