Ternary operator in while loop - c

In this scenario, why is it that the output for i is 1 and not 0, since the while loop decrements the value for i two times from it's original value i=2?
#include<stdio.h>
int main(){
int i=2,j=2;
while(i+1?--i:j++)
printf("%d",i);
return 0;
}

It is because your complicated ternary operator can be reduced to
while(--i)
Explanation.
i+1 == 3, --i executes. i == 1 so the body of while loop executes (prints 1). now i+1 == 2, --i executes, i == 0 which is false in C and body of the while loop is being skipped.
i is decremneted twice - but printf executed only 1 time.
You can test it adding one more printf:
int main(){
int i=2,j=2;
while(i+1?--i:j++)
printf("%d\n",i);
printf("%d\n",i);
return 0;
}
and the result will be as expected
1
0

Related

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.

Can anyone tell me why this program go to infinite times?

#include< stdio.h>
int main()
{
int n,a=0,i=1,b=11;
while(i<=2)
{
while(i>0)
{
a=a+b;
i--;
}
printf("%d",a);
i++;
}
}
but if i make a little change i will get the output..
what is the difference between both the code??
#include< stdio.h>
int main()
{
int n,a=0,i=1,b=11;
while(i<=2)
{
n=i;
while(n>0)
{
a=a+b;
n--;
}
printf("%d\n",a);
i++;
}
}
output-
11
33
while (i <= 2)
{
while (i > 0)
{
a = a + b;
i--; <- out the inner while loop when i = 0
}
printf("%d", a);
i++; <- at here, the i==0 each time, so infinity loop
}
Because your nested loop always restores the value of i to 0,
And 0 <= 2 is always true, thus it keeps on going.
Initially the value of i is 1, the first loop starts by checking i<=2 , which is true for i=1, then the second loop checks i>0, which is also true, then the second loop decreases the value of i to 0 by i--;
This time the test condition for the nested loop fails and the inner loop exits, back in the first loop, the condition is satisfied as i=0 is<= 2 thus i is incremented, now i = 1.
This keeps on going forever.
In the second code, you're copying the current value of i to n, thus, initially i = 1;
Condition for first loop satisfied, then you set n = i,
And check n >0 which is true as n = i = 1
In this loop you are decrementing n and n becomes 0, thus the loop quits, and the outer loop increments i, i now being 2 allows the outer loop to run and then again n = i = 2,
The inner loop runs twice and then exits and i is incremented to 3 failing the outer loop condition and hence quitting the loop. And you get the result.
In the first code your
While(i<=2) never ends because you add 1 to i with i++ and then you subtract 1 from i with i-- and you never get i=3 to end the while loop.

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.

why it is acting like infinite loop

# include<stdio.h>
int somthing(int);
int main()
{
int i=9;
somthing(i);
return 0;
}
int somthing(int i)
{
if(i == 0)
return 0;
else
printf("%d,", i);
somthing (i--);
}
I am not getting why compiler prints only 9 9 9 and then says time out that is its running infinitely.
I did post decrement on i variable one less value should go into loop every time and it should print values from 9 to 0 , code works fine when doing pre decrement on i variable .
I did post decrement on i variable one less value should go into loop every time and it should print values from 9 to 0
what you are using i-- is post increment. It would send the value of i to the something() function and then decrement the value of i. so, the somthing() function always gets the value 9. thus it goes to an infinite recursive call.
what you need is preincrement --i. It will decrement the value of i and then send it to the function somthing()
int somthing(int i)
{
if(i == 0)
return 0;
else
printf("%d,", i);
somthing (--i);
}
Do this instead. See if this works

Resources