Support Forums
Why doesn't this loop work? - Printable Version

+- Support Forums (https://www.supportforums.net)
+-- Forum: Categories (https://www.supportforums.net/forumdisplay.php?fid=87)
+--- Forum: Coding Support Forums (https://www.supportforums.net/forumdisplay.php?fid=18)
+---- Forum: Programming with C++ (https://www.supportforums.net/forumdisplay.php?fid=20)
+---- Thread: Why doesn't this loop work? (/showthread.php?tid=2797)



Why doesn't this loop work? - nevets04 - 11-10-2009

Code:
#include <iostream>
using namespace std;int main(){int x=1;while(x<=99){x=x+1;cout<<x<< endl;return 0;}}

The output is 2, why isn't it:
2
3
4
5
6
7
8
9
10
etc...


RE: Why doesn't this loop work? - Gaijin - 11-11-2009

Because you return the function within the while loop....

Your code
Code:
return 0;}}
Right code
Code:
}return 0;}



RE: Why doesn't this loop work? - Etheryte - 11-11-2009

Using return will stop the program in it's track, no matter what operation it's currently undergoing. For example, you can use return 1 for error checking.


RE: Why doesn't this loop work? - MrD. - 11-11-2009

(11-10-2009, 11:45 PM)nevets04 Wrote:
Code:
#include <iostream>
using namespace std;int main(){int x=1;while(x<=99){x=x+1;cout<<x<< endl;return 0;}}

Please tell me you don't really lay your code out like that?
Code:
#include <iostream>
using namespace std;

int main()
{
    int x=1;
    while(x<=99)
    {
        x=x+1;
        cout<<x<< endl;
        return 0;
    }
}
Makes it much clearer why it is going wrong (because return is inside the loop). Also you might want to look into a for loop (and pre/post increment operators).

Code:
#include <iostream>
using namespace std;

int main()
{
    for(int x = 1; x <= 99; ++x)
        cout << x << endl;
    return 0;
}



RE: Why doesn't this loop work? - nevets04 - 11-11-2009

(11-11-2009, 07:14 AM)MrD. Wrote: Please tell me you don't really lay your code out like that?
Code:
#include <iostream>
using namespace std;

int main()
{
    int x=1;
    while(x<=99)
    {
        x=x+1;
        cout<<x<< endl;
        return 0;
    }
}
Makes it much clearer why it is going wrong (because return is inside the loop). Also you might want to look into a for loop (and pre/post increment operators).

Code:
#include <iostream>
using namespace std;

int main()
{
    for(int x = 1; x <= 99; ++x)
        cout << x << endl;
    return 0;
}

I do that for shorter programs


RE: Why doesn't this loop work? - Sagittarius - 12-11-2009

so so simple...

your return 0; will return to OS ... not return to loop