Easy C++ Question

Status
Not open for further replies.

waynejkruse10

Fully Optimized
Messages
3,782
Im sure this is very simple. I would like to loop something in C++.

eg.

Repeat
my code
Until x=50

so, i want to repeat my code until x = 50.

I dont want to use a while loop

Wayne
 
for(x=0;x=50;x++)
{
insert code here
};<----dont remember if that needs a semi or not but put one just in case
 
Wait, change the x=50 to x<=50, sorry about that it has been awhile since I have coded.
 
Does x ever have an initial value in your code? Or does it always start at 0?

Something more closely approximating your code would look like:

do
{
// Your code
x++;
} (while x<50);

Som that variation runs the code *then* checks the size of x. The effect of this is creating a loop that you can always guarantee will run at least once.

x++ => Increment X by 1, shorthand for x = x + 1;
 
chog said:
Wait, change the x=50 to x<=50, sorry about that it has been awhile since I have coded.

for(x=0;x<50;x++) is correct.

x<=50 would mean that it runs 51 times, since you are starting at 0.
x<50 runs 50 times.
 
If you want something to run forever then use:

Code:
While(true)  //when is "true" never true?
{
   //code to do forever
   //I'd suggest testing for a key to stop
}

Want to do it in a for loop?
Code:
for(i=1; i<0; i=1)
{
   //put code here
   //suggest testing for input to exit loop
}

Its not as elegant as While(true) but it should work.
 
@jinexile
Make sure to use a lowercase "while". It depends upon your compiler, but it is usually case sensitive. "true" will also have to be defined as 1, but this is also dependent upon your compiler. Devcpp recognizes true as 1 whereas Turbo C++ will return "true" as undefined. You can just set its type as int and define it as 1. To avoid that, you can simple just use while( 1 ).
 
Status
Not open for further replies.
Back
Top Bottom