compound condition in for loop - loops

What is the difference between the following two constructs? I am getting a different output for each:
for (int counter = 0; (counter < numberOfFolds) && counter != currentFold; counter++)
{
if (instances[counter] < minimum)
{
return (currentFoldHasAtleastMinimum && true);
}
}
AND
for (int counter = 0; (counter < numberOfFolds); counter++)
{
if (counter != currentFold)
{
if (instances[counter] < minimum)
{
return (currentFoldHasAtleastMinimum && true);
}
}
}
Essentially, the second block of code, simply breaks the compound condition in the for loop and takes it inside using an additional if statement (I may be missing something very fundamental here, and it may be really stupid, but I thought they were the same).
Please help. It appears that they are in fact not the same, and I cannot figure out why.

The first condition will end the loop as soon as either sub-condition becomes false (so counter >= numberIfFolds or counter == currentFold). The second loop will only terminate when counter >= numberOfFolds. It will, however, check if counter == currentFold and skip executing those statements if it is. The loop will continue, though.

In the first example, when counter is equal to currentFold the loop terminates.
In the second example, the loop will continue when that condition is met, and instead will only terminate when counter < numberOfFolds is false.

Related

What other ways can I write this loop?

I am still a beginner and I’m just wondering if my loop has any other ways I can write it for learning sake. Here is my loop:
int count = 0;
int index = 0;
while(index >= 0 && index < arr.length && count < 100){
index = arr[index];
count++;
}
you can use for loop for that mission, so you can write:
for (int count = 0, index = 0; index >= 0 && index < arr.length && count < 100 ;count++)
{
index = arr[index];
}
but notice that in your for loop, you are not updating the value of index, by which I mean that index is always 0 even in your original code
A great alternative in this case would be a for loop. As you'll notice while coding when using multiple conditions to a loop it is best to use a for loop because it will look much neater and for loops already require three conditions perfect for your case.
while ( condition && condition && condition)
vs
for ( condition ; condition ; condition)

Basic multiple conditions for loop not working

I'm currently learning C and I'm facing a problem that I can't solve.
It's really simple, I want the numbers from 1 to 20 printed but only if they're even (meaning the output would be 2, 4, 6,...). I know how to do this but the problem is that I want to do it in a way that I put two conditions in a for loop:
int main() { 
for (int i = 1; i<=20 && i%2 == 0 ; i++) {
printf("%d\n", i);
}
return 0;
}
It seems that the second condition isn't evaluated, moreover it causes the program not to print anything. How can I do it ?
The second condition is evaluated. It is because it is evaluated the loop does not iterate.
The initial value of i is equal to 1. So the sub-expression i%2 == 0 evaluates to false.
You could use an if statement within the loop like
for (int i = 1; i<=20; i++) {
if ( i % 2 == 0 ) printf("%d\n", i);
}
If you want to place the expression i % 2 == 0 in the condition of the loop then the loop can look for example the following way as it is shown in the demonstrative program
#include <stdio.h>
int main(void)
{
for ( int i = 1; ( i % 2 == 0 ? i : ++i ) <= 20; i++) {
printf("%d\n", i);
}
return 0;
}
The program output is
2
4
6
8
10
12
14
16
18
20
Both conditions are evaluated - that's why the loop never gets going, in fact. When for starts, it sets i to 1, and immediately does the loop termination check: 1<=20 && 1%2==0. This reduces to true && false and finally to false. So the for loop won't do anything else: the very first check fails.
Remember: a failure of the condition check in the for loop terminates the loop!
Instead, you need to write what you meant - it'll be more readable and will work, too! You said:
I want the numbers from 1 to 20 printed but only if they're even
That translates directly to C (the return is unnecessary):
#include <stdio.h>
int main() {
// for all numbers from 1 to 20
for (int i = 1; i<=20; i++) {
// print out only those that are even
if ((i%2) == 0) printf("%d\n", i);
}
}
You can try this out online!.
The loop stops as soon as the condition fails. Since i%2 == 0 fails for i = 1, the loop stops immediately.
You need to put the even check inside the loop, not in the for condition.
int main() { 
for (int i = 1; i<=20; i++) {
if (i % 2 == 0) {
printf("%d\n", i);
}
}
return 0;
}

How does 'for' work when all of its "parts" are 'i++'?

I've used Code::Blocks to find the result, and it gives me 2 at the end, where i + j = 1 + 1.
#include <stdio.h>
int main(void) {
int i = -1, j = 1;
for(i++; i++; i++)
j++;
printf("%d",i + j);
return 0;
}
How does i get to be 1, and why was j not incremented?
You start with i == -1, j == 1.
Then you run the first i++, which will make i == 0. The result (which is the original value of i) is unused.
Then you test for the first time in i++. Since i is already 0, the test is false, so the for loop will quit. Now the post-increment runs, which makes it i == 1, and the loop exits.
Note how j++; was never reached!
To see it more clearly, you can think about the for loop in the following equivalent way:
i++; // init statement
while (i++) { // condition
j++; // body of the for loop
i++; // iteration expression
}
Here's the order in which it executes:
i is -1 and j is 1
i is incremented (after which i == 0)
The loop checks if i != 0. Since i is 0 at this point, the contents of the loop are skipped.
i is incremented again (after which i == 1)
The code prints i + j, which is 2 because j is unchanged and i is 1.
Here's a program with a while loop that does the same thing as the program in your question:
int main(void) {
int i = -1, j = 1;
i++;
while(i++)
{
j++;
i++;
}
printf("%d",i + j);
return 0;
}
To directly answer your question:
i is 1 afterwards because it is incremented twice from an original value of -1.
j is not incremented because the contents of the loop are skipped.
Let me first explain how for loop execution happens:
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the for loop.
Increment operator: value of i increments after execution if it is i++
Explanation of your code:
for(i++; i++; i++)
At init step i++ been executed but i will be still 0 until it get to condition step of for loop.
i becomes zero it means condition is false but at same time one more i++ already executed.
As condition is false for loop statement will never be executed and value of i will be 1 and value of j remains 1.

What does "for (; --i >= 0; )" mean in C?

What does for (; --i >= 0; ) mean in C?
How is the counter getting decremented and how is it different from for ( ; i >= 0; --i)?
They are very similar, but not the same! First you have to understand how a for loop in C gets executed:
As an example:
1 2, 5 4
| | |
v v v
for(i = 0; i < 5; i++) {
// Do something <-- 3
}
As you can see 2, 3, 4, 5 is a loop until the condition is false.
Now you should clearly see how the for loop gets executed. The difference now is that in your first example:
int i = 5;
for ( ; --i >= 0; )
printf("%d\n", i);
The output would be:
4
3
2
1
0
Because after the first check of the condition (Point 2), it executes the code block of the for statement and i already gets decremented.
In your second example:
int i = 5;
for( ; i>=0; --i)
printf("%d\n", i);
The output would be:
5 // See here the difference
4
3
2
1
0
Here you get the difference, because it gets decremented in Point 4, so the first time it runs with the value 5.
These constructs are formally equivalent to
while (--i >= 0)
{
Body;
}
and
while (i >= 0)
{
Body;
--i;
}
Do you better see the difference?
In general, we can convert any for loop or while loop into a set of mostly linear statements with a goto. Doing this may be helpful to compare the code.
Case 1
### for (; --i >= 0; ) { statements; }
; // Initializer statement
start:
bool condition = (--i >= 0); // Conditional
if (condition) { // If true, we execute the body as so:
statements; // The statements inside the loop
; // Empty increment statement
goto start // Go to the top of the loop.
}
Case 2
### for( ; i>=0; --i) { statements; }
; // Initializer statement
start:
bool condition = (i >= 0); // Conditional
if (condition) { // If true, we execute the body as so:
statements; // The statements inside the loop
--i; // Increment statement
goto start; // Go to the top of the loop.
}
Let's compare the "simpler" code from those two cases.
In the first case, we decrement i for the first time before each loop body. In the second case, we decrement i after each loop body.
The easiest way to see that is to consider what happens when you enter this loop when i == 0. In the first case, after this block of code, you would have a resulting value of i == -1. In the second case, i wouldn't have changed (that is, i == 0), because we never reached the increment statement.
for (; --i >= 0; ) works like this:
Say if you have i as 10, it will decrement the i value and will compare 9 >= 0 and so on.
So the output would be like 9, 8... till 0.
While the loop for( ; i>=0;--i) would first go to 10, then decrement the value and then it would check i>=0. So the output would be 10, 9, 8... till 0.
The first one decrements i and then checks the condition.
The second one checks the condition first and if true, decrements i after the loop body has been executed.
Well, it is the same as saying for( i=0 or some value; --i <= 0 ; do nothing){}
and --i is an predecrement operator.
That means when this piece of code, i.e., --i, is being read, the value of i will decrease by 1 at the same moment.
There are three main components in a for loop.
Initialization, condition, and afterthought.
Initialization happens once at the start of the entire statement. Condition happens before every cycle. Afterthought comes after every cycle. Consider i starts at 2:
for (; --i >= 0; )
Initialization: i = 2
Condition: i = 1
Afterthought: i = 1
Condition: i = 0
Afterthought: i = 0
Condition: i = -1
Exit
In the other case
for( ; i>=0; --i)
Initialization: i = 2
Condition: i = 2
Afterthought: i = 1
Condition: i = 1
Afterthought: i = 0
Condition: i = 0
Afterthought: i = -1
Condition: i = -1
Exit
You can see that the second version actually lasts one cycle longer!
The three parameters (initialization, condition and increment) in for are optional (but they still requires the semicolon ;). So, you can safely write for(;;) and it's the same as while(1). So, expressions like
for(; x > y; x++) { ... }
for(;1;x++) { if(x > y) break;
for(;;) { if(x++ > y) break;
for(;x++ > y;) { ... }
Are valid and equivalent. In this, the increment occurs in the conditional parameters, just like in your code example.

c/c++ for loop condition statement

folks,
I am adding a logic expression in the for loop and it is not behaving as I expected. Could you shine some light on me? Thanks very much.
The following code works fine
for (i=0;i<N;++i)
if (a[i] == 1){
....
}
and I tried to write it this way, it seems the for loop is fully skipped.
for (i=0;i<N && a[i]==1;++i){
....
}
What is wrong with the 2nd way?
The loop continues while the condition is true. Remember that a for-loop for(A; B; C) can be replaced with [conceptually]:
A;
while(B)
{
...
C;
}
So, you have:
i = 0;
while(i < N && a[i] == 1)
{
...
i++;
}
So, if at the first instance a[i] is not 1, then you never enter the loop, and just go to whatever comes after. It's probably not what you wanted to do, which is why it's not doing what you wanted... ;)
This code:
for (i=0;i<N;++i)
if (a[i] == 1){
Means, increment i, starting from 0, keep going until it's greater than or equal to N, for each element in a[] check to see if it's equal to 1
This code however:
while(i < N && a[i] == 1)
Says loop as long as i is less than N and a[i] is equal to 1. So as soon as either of those condtions is false it will break from the loop.
You never enter the loop if a[0] != 1. That's a condition for your for loop to be executed just like how i < N is too.

Resources