A simple problem with a while loop.

closed account (Ly59GNh0)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

int main ()
{
    int v1, sum = 0, end = 0;
    while (end = 0) 
    {
          std::cout << "Enter a negative or positive number (enter 0 to exit)" << std::endl;
          std::cin >> v1;
          if (v1 = 0) 
          {
                 ++end;
          } 
          else 
          {
               if (v1 < 0) ++sum;
          }
    }
    std::cout << sum << " of the numbers you entered were negative." << std::endl;
    std::cin >> v1;
    return 0;
}


This code seems straightforward enough but it doesn't work and I can't seem to figure out why.
It seems to me that I declare that the integrer end is "0" and in the very next statement I tell the program that as long as end is "0" the while loop whould continue.
But the program simply skips the while loop altogether, only initiating it if I cange its parameters to something else (like end <= 0).
If I do that, however, there seems to be no way of getting out of the loop.

So what gives? Any help is greatly appreciated.
= is assignment
== is comparison

1
2
3
4
5
6
while (end = 0)  // bad
while (end == 0) // good


if (v1 = 0)  // bad
if (v1 == 0) // good 
closed account (Ly59GNh0)
I've tried isolationg the problem a bit more, and the issue seems to be, strangely enough with using "0" as a definite value.

I can get the program to work as it should if I change

while (end = 0)

to

while (end <= 0)

and

1
2
3
4
          if (v1 = 0) 
          {
                 ++end;
          } 


to

1
2
3
4
          if (v1 = 1) 
          {
                 ++end;
          } 


But that has the rather serious side-effect of having to use 1 (or some other number) as the "exit number")
closed account (Ly59GNh0)
Oh, thanks a bunch. I remember reading that a long while back on this page, but the book I'm using now hasn't covered that yet.
I thought I was losing my grip of reality there for a second. :)
Topic archived. No new replies allowed.