Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why doesn't this loop work?
#1
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...
Reply
#2
Because you return the function within the while loop....

Your code
Code:
return 0;}}
Right code
Code:
}return 0;}
Reply
#3
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.
Reply
#4
(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;
}
[Image: sig.php]
The little boat gently drifted across the pond exactly the way a bowling ball wouldn't.
Reply
#5
(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
Reply
#6
so so simple...

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

[Image: ubuntu_5.11.jpg]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  For loop problem GeneralOJB 9 1,441 12-17-2009, 03:47 PM
Last Post: GeneralOJB

Forum Jump:


Users browsing this thread: 1 Guest(s)