tags:

views:

160

answers:

6

I know I must be missing something small but in a while statement how does the variable hold the data when it finishes the first pass and goes into the second pass.

+1  A: 

I'm not sure I understand your question. In C any data that's not overwritten is carried over into the next iteration of the loop, and imagine that C++ works much the same way.

Kyle Cronin
+2  A: 

I'm not clear exactly what you're asking, but variables will maintain their value for each iteration of a loop, as long as they're declared outside of the loop itself. For example:

int a = 0;

while(a < 10)
{
 int b = 0;

 cout << "a: " << a << " b: " << b << "\n";

 a++;
 b++;
}

In the above, the value output for b will always be 0, as it's declared inside the loop and is being reinitialized each time, whereas a will maintain its value and get incremented each iteration. If b were an object, rather than an int, its constructor and destructor would get called each iteration.

James Sutherland
A: 

{

int num1 = 0 ;
int num2 = 0;
int num3 = 0;

while (num1 < 10) 

{cout << "enter your first number:  ";
cin >> num1;

cout << "Enter your second number:  ";
cin >> num2;

num1 = num1 + num2 ; 

 cout << "Number 1 is now: " << num1 <<endl;

 cout << "Enter Number 3: " ;
 cin >> num3;

 num1 = num1 + num3;

 cout << "Number 1 is now: " << num1 << endl;
 num1++;
};

In this code. The Variable doesn't hold the data. I'm not sure what I'm doing wrong!

Andy_Small
+2  A: 

Is num1 the variable you're having trouble with? This line:

cin >> num1;

is setting num1 to the value input by the user. So the value calculated for it in the previous run through the loop is being overwritten each time by the new input.

James Sutherland
A: 

So the variable that I want the data hold shouldn't have a cin?

Andy_Small
+1  A: 

Do you understand how when you say "num1" you're referring to the same variable each time, and that each time you change num1 you replace the previous value?

DrPizza