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...
Because you return the function within the while loop....
Your code
Right code
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.
(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;
}
(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
so so simple...
your return 0; will return to OS ... not return to loop