I am doing a program for tic-tac-toe and i have a line with
for ( count = 1; count < 10 && winner == 0; count++ );
I referred to other programs and came up with this.
And I'm not very sure of what the entire line means. I have searched up online but I dont understand the meaning of initialization statement ( count = 1 ) and the test expression. And also want to clarify, count++ means increase count right?
Let's have a look at the structure of a for loop:
for ( init-statement; condition; iteration_expression) statement;
From cppreference, a for loop does the following:
Executes init-statement once, then executes statement and iteration_expression repeatedly, until the value of condition becomes false. The test takes place before each iteration.
For your case:
init statement: at the beginning count is initialized to 1
condition: check if count is less than 10 and you don't have a winner yet
iteration_expression: cout++ increases count by 1
statement: you haven't provided that, but it will be executed until the condition is false.
Syntax of for loop is
for(initialization; condition; increment/decrement){
statement;
}
initialization:
Before we start looping, we will initialize the variable to certain value.
In this case, you are initializing 'count' variable to 1
Condition:
In condition part, To stop the loop at certain point you have to provide some conditions.
In this case, condition is 'count<10 && winner==0'. Note that, you are using And(&&) operation so, loop will stop only after both of the conditions are satisfied.
increment/decrement:
Based on the problem, you can choose to increment or decrement the loop variable('count'). In this case, count++ means you are incrementing the count by 1 after each iteration.
for (initialize;condition;increment/decrement)
for loop means
you initialize the variable
you apply a condition to stop the for loop
you execute a single time the loop body (if the condition satisfied)
then you increase or decrease the value of that variable and go to step 2
Related
This question already has answers here:
What is the "-->" operator in C++?
(29 answers)
Closed 6 years ago.
int i;
for(i = n; i --> 0;)
and
for(i = n; i > 0; --i)
They are producing different results.
As for the first one, i is decremented before the loop body is executed. The second one decrements i after the loop body is executed.
The difference is the step in which i is actually decremented, which affects the values of i seen inside the loop body.
The second traditional version decrements i after the loop body is executed, and before the condition is checked again. Thus i reaches 0 after the loop body is executed for i == 1. The condition is checked again and after the loop i is 0.
The first version decrements i before the loop body is executed, as part of the condition being checked. Here the loop body runs the first time with i == n - 1 and the last time with i == 0. Then i is decremented and its previous value compared against 0. The loop exits and i is -1 after it.
In the traditional version, the loop body always sees the same value against which the conditional part was checked.
When I compile and run the code below with either counter++ or ++counter substituted for x, the output is identical; in both cases, numbers 1 - 10:
for (int counter = 1; counter < 11; x)
{
std::cout << counter << endl;
}
Originally I thought ++counter would increment by 1 and then return the new value before for boolean expression in the loop header was evaluated. i.e when starting with counter = 1 and using ++counter, counter would have a value of 2 in the boolean expression. This appears to not be the case, as both outputs are identical rather than the ++counter version having one less iteration, like I expected.
Reading around, it appears ++counter and counter++ increment counter by 1 at either the start or end of the loop body respectively. In which case is this not, at least conceptually, an identical action? Because the end and the start of the loop are the same thing once the loop has past the first iteration.
The only time I can see this making a difference is in the first iteration, where std::cout << counter << endl;should output 1 to the console if counter++ is used (because 1 is added to counter at the end of the loop). Whilst std::cout << counter << endl; should output 2 to the console if ++counter is used (because 1 is added to counter at the start of the loop).
In addition to the question above, could you please precisely explain the order in which the three actions are evaluated in the for loop header, and explain exactly where the iterations occur when using i++ and ++i.
Many thanks!
There is no difference. In older compilers, ++counter was faster because it did not create a temporary variable but all modern compilers can optimize that out. For heavy objects with custom (non-inlined) increment operators, ++counter can still be more efficient.
As for when evaluation takes place:
for (initialization; condition; increment/decrement)
code;
is evaluated as
{
initialization;
while (condition)
{
code;
increment/decrement;
}
}
The C++ for-loop may be roughly considered as syntactic sugar for the following (using your example):
int counter = 1;
while (counter < 11)
{
std::cout << counter << endl;
x;
}
So, the initialization statement is executed first, the condition expression is executed before each iteration, and the increment statement is executed at the end of each iteration.
We can see here that using post-increment or pre-increment operators makes no difference to the loop logic, though there may be other differences (post-increment actually requires keeping a copy of the old value of the variable as that is the value of the expression, which has some associated costs, see Preincrement faster than postincrement in C++ - true? If yes, why is it?).
counter++ makes a copy increase counter and returns the value
++counter increases counter and returns counter.
In loop
for(initialization;condition;increment/decrement)
{body;}
increment/decrement is the last line of the loop. So it will start the loop again when increment/decrement returns a value. So post-increment or pre-increment will not affect here. See this
What is the difference between pre-increment and post-increment in the cycle (for/while)?
for (; cnt--; dp += sz)
{
pair_sanitize_struct(rec_id, ctx->api_mode, dp, FALSE);
}
Could some one explain how this for loop works? It belongs to a cpp file.
I dont understand the condition in the for loop and how it is being checked. (The function is being invoked)
The general form of for statement looks like this:
for (init-statement; condition; expression)
statement
init-statement is used to initialize or assign a starting value that is modified over the course of the loop. condition serves as the loop control. As long as condition evaluates as true, statement is executed. expression is evaluated for each iteration only if condition is true
Back to your code:
for (; cnt--; dp += sz)
init-statement here is a null statement that does nothing. condition is cnt-- which evaluates its value as cnt then decrements 1. If cnt is non-zero, condition is true, if cnt is zero, condition is false.
The condition is being interpreted as a true or false scenario.
If it's 0, then it will be false, else true.
This is equivalent to the following code -
for(; cnt-->0; dp += sz);
Because as long as a value is not equal to 0, it is considered to be true.
Remember that normal integers can be used as boolean values as well, where zero is false and everything non-zero is true.
This means that the loop will continue until cnt is zero, and then the loop will end. However that's not the whole story, since the post-decrement operator is used the value of cnt after the loop have ended will be -1.
It is similar to
while(cnt--)
{
pair_sanitize_struct(rec_id, ctx->api_mode, dp, FALSE);
dp += sz;
}
hope this is helpful.
So syntax for for loop is
for (<initialization(optional)>; <condition(Optional)>; <increment(Optional)>)
{
...
}
Say for cnt is 2 your loop works as follows,
for(; cnt--; dp+=size)
{
...
}
Execution flow is,
1. initialization statement will be executed once. Since you dont have one nothing will be executed
2. Next condition statement will be executed. In your case cnt-- which result in cnt value is considered as condition result. So, if cnt is 2 then value 2 is considered as condition result. Hence all non-zero are considered as TRUE and zero is considered as FALSE. After evaluating to TRUE it decrements cnt by 1
3. Once the condition results in TRUE then it executes the statement part say, pair_sanitize_struct(rec_id, ctx->api_mode, dp, FALSE);
4. At the last it executes the increment statement of for loop,in you case it is dp-=size;
5. It executes from 2 till condition evaluated to ZERO ie FALSE it comes out of loop.
In c++, the value for a condition being true or false is determined by being non 0 (true) or 0 (false).
The above loop would continue iterating as long as cnt is NOT 0. It will terminate when cnt becomes 0.
UPDATE:
To clear an important point here, it is the value 0 that terminates the loop. If for some reason, cnt already starts with a negative value, the loop will never terminate
I'm writing an algorithm and I have a do-while loop in it. I want to be in that loop until either the GAP is small enough or number of iterations is higher than 1000. But it passes 100 iterations and doesn't stop. Here is the code:
int iteration=1;
double UB=0;
double LB=0;
double GAP=1;
do
{...
GAP=abs((UB-LB)/LB);
iteration++;
}while(GAP>=0.05 || iteration<=1000);
You probably want && instead of ||. You want to iterate until either of those expressions is false, therefore you want to iterate while both of them are true.
You missed the logic a bit ;)
If you want the loop to end if (conditionA or conditionB), then it means that you want to continue the loop if (conditionA AND conditionB).
In other words, you should have
while(GAP>=0.05 && iteration<=1000)
You need to change the '||' to '&&'
In C/C++, what does the following mean?
for(;;){
...
}
It's an infinite loop, equivalent to while(true). When no termination condition is provided, the condition defaults to false (i.e., the loop will not terminate).
In C and C++ (and quite a few other languages as well), the for loop has three sections:
a pre-loop section, which executes before the loop starts;
an iteration condition section which, while true, will execute the body of the loop; and
a post-iteration section which is executed after each iteration of the loop body.
For example:
for (i = 1, accum = 0; i <= 10; i++)
accum += i;
will add up the numbers from 1 to 10 inclusive.
It's roughly equivalent to the following:
i = 1;
accum = 0;
while (i <= 10) {
accum += i;
i++;
}
However, nothing requires that the sections in a for statement actually contain anything and, if the iteration condition is missing, it's assumed to be true.
So the for(;;) loop basically just means:
don't do any loop setup;
loop forever (breaks, returns and so forth notwithstanding); and
don't do any post-iteration processing.
In other words, it's an infinite loop.
Loop until some break, exit, throw etc. statement inside the loop executes. Basically, you can think of a for loop as consisting of:
for (setup; test; advance)
...
If the "test" is empty it's considered to be true, and the loop keeps running. Empty "setup" and "advance" simply do nothing.
An infinite loop which continues until there is a break, exit, or goto statement.
Even if this answer suggests that both constructs are equivalent, there's a subtle difference between both for(;;) and while(1) (which both create infinite loops) in the C language (and possibly compiler-dependent).
Some compilers (Windriver DIABData for instance) complain about "condition is always true" when using while(1).
Changing to for(;;) allows to get rid of the warning, probably because the latter expression is semantically stronger to create an infinite loop on purpose, and there is no "always true" condition at all (plus it's shorter to write).
On the other hand, the C++ language doesn't make a difference about both constructs as Adrian stated in comments:
The C++ standard states that a missing condition makes the implied while clause equivalent to while(true) and for ( for-init-statement condition opt ; expression opt ) statement is equivalent to { for-init-statement while ( condition ) { statement expression ; } }