Umm Negative, Great....

When i run my code, i want it to stop at 0 or lower (if it some how glitches) but it seems to go negative...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int main ()
{
	int age;
    int hello;
cout << "Now tell me how old are you?" << endl;
	 cin >> age;
cout << "Calculating..." ;
hello = age * 6;
while (hello>0)
{
	--age;
    cout << age << endl;
}
cout << "done :)";
return 0;
}
Hello is assigned to the value of age times six... once. As the loop runs, age gets lower and lower, and keeps going to negative-whatever, because your loop does not manipulate hello ever again.
Ya give an update expression inside the loop body like this
1
2
3
4
5
6
7
while (hello>0)
{
       --hello;  // update expression
	--age;
    cout << age << endl;
}

nb::If your intention was to print the age in backwards also make sure to change line 14 to...

hello=age;

(this will correct the -ve value problem)
Cheers,
CyberDude
Last edited on
Topic archived. No new replies allowed.