c/c++ for loop condition statement - c

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.

Related

C program: print prime number between 1 to 100

I was just wondering why my code doesn't work. Yes I know that it's easy to find answers online but I just wanted to delve in why the things I do doesn't function well rather than simply getting answers.
#include <stdio.h>
int main() {
int i;
int j;
printf("all prime numbers between 1 and 100\n");
for (i = 2; i <= 100; ++i) {
if (i % !i != 0 && i>0 ) {
printf("%d ", i);
}
}
}
As you have noticed yourself, there are tons of example code for this out there, so there's little point for me in showing how to calculate primes. So instead, I show how to debug your code. In this case I'd doe something like this:
for (i = 2; i <= 100; ++i) {
printf("i: %d !i: %d\n", i, !i);
printf("i \% !i != 0: ", i % !i != 0);
if (i % !i != 0 && i>0 ) {
printf("%d ", i);
}
}
The exact printouts is something that you have to find out for yourself. But start with individual values, and then look at more complicated expressions. Also, use parenthesis whenever unsure. I don't know exactly how the expression in your if statement is parsed. I can think of several possibilities. Like:
((i % !i) != 0) && (i>0)
(i % (!i != 0)) && (i>0)
(i % !i) != (0 && i>0)
The point here is that your code does not work, and you have a very messy expression that is hard to understand exactly what it does. So use parenthesis.
Another thing you should do with that expression is to motivate each part with words. Can you explain why you have i>0? Because that's always true, to it's completely pointless. Instead of asking why it doesn't work. Try to explain to yourself why it should work. Get more and more detailed until you find something that you cannot explain. Then you probably have your bug there.
The definition of a prime is that it is an integer strictly greater than one, and is not divisible by any other integers than itself and and one. So now it's your job to explain how i % !i != 0 && i>0 should be able to check if i is an integer or not. And take explicit examples. For instance, if i is 5, describe the process when i % !i != 0 && i>0 checks if it is divisible by 2. Then explain how it checks for divisibility by 3.
The very simple question to your answer why it does not work is because the algorithm is wrong. :)

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.

Loop within loop does not run

This code should count the number of prime numbers based on user input. If user input is 10, then I should get 4. However, I only get 0. Why does the second loop not run?
#include<stdio.h>
#include<math.h>
int main()
{
int N;
scanf("%d", &N);
int numprime;
numprime = 0;
int P=1;
for (P; P<N; P++)
{
if (P%2==0)
continue;
int e = sqrt(P);
for (int j=3;j<=e;j+=2)
{
if (P%j!=0)
{
numprime = numprime + 1;
}
else
{
continue;
}
}
}
printf("%d", numprime);
}
Why does the second loop not run?
It does run, once, when e is equal to 3 (that means that this happens when P is equal to 9), in the case that input is 10.
Change this:
for (P; P<N; P++)
to this:
for (; P <= N; P++)
since the first part had no effect, and more importantly, you want to check all N numbers, so the stop condition had to be modified.
Then, you need to change this:
for (int j=3;j<=e;j+=2)
to this:
for(int j = 2; j <= e; j+=2)
in order to check for prime numbers, are suggested here.
Furthermore, you need to change this:
if (P % j != 0)
to this:
if (P % j == 0)
since P is actually a prime number when the condition is met.
Moreover, you need to get rid of this:
if(P % 2 == 0) continue;
since for example 2 is a prime number, but it meets this condition, and will not be taken into account!
From your code, it looks like P starts out as 1, so e is sqrt(1), which is again 1, and j is 3. Therefore, j is not less than or equal to 1, and the test at the top of the inner loop fails, so the loop doesn't execute the first time through. This pattern continues for each iteration of the outer loop until P becomes large enough that sqrt(P) is greater than 3, at which point the inner loop does run.

compound condition in for loop

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.

Resources