Why the loop is running from 2 to 7?
int i;
for(i=1;i<=6;printf("\n%d\n",i))
i++;
The output of this is
2
3
4
5
6
7
but limit of i is 6.
The Syntax of a for loop is
for ( clause-1 ; expression-2 ; expression-3 ) statement
The execution is as below, quoting from C11, chapter §6.8.5.3, (emphasis mine)
The expression expression-2 is the controlling expression that is
evaluated before each execution of the loop body. The expression expression-3 is
evaluated as a void expression after each execution of the loop body. [....]
Here, i++ is the body and printf("\n%d\n",i) is the expression-3.
So, the order of execution would be something like
i = 1;
start loop
i < = 6 //==> TRUE
i++; //i == 2
printf // Will print 2 ///iteration 1 done
i < = 6 //==> TRUE
i++; //i == 3
printf // Will print 3 ///iteration 2 done
.
.
.
i < = 6 //==> TRUE
i++; //i == 6
printf // Will print 6 ///iteration 5 done
i < = 6 //==> TRUE
i++; //i == 7
printf // Will print 7 ///iteration 6 done
i < = 6 ==> FALSE
end loop.
A for loop like
for(i=1;i<=6;printf("\n%d\n",i))
i++;
is equivalent to
{
i = 1; // Initialization clause from for loop
while (i <= 6) // Condition clause from for loop
{
i++; // Body of for loop
printf("\n%d\n", i); // "Increment" clause from for loop
}
}
As you can see, the printf is done after the variable i is incremented, which of course means it will print the incremented value (2 to 7).
The workings of the loop are equivalent to the now-obvious
int i;
for (i = 1; i <= 6; /*intentionally blank*/){
i++;
printf("\n%d\n", i);
}
as, conceptually, the 3rd expression in the for loop is ran just before the closing brace of the loop body.
You have written the for loop in an unusual manner.
The operation of a for loop is given below.
The initialization is done first. i=1
Then the expression is checked i<=6
Then the body is carried out i++
Then the increment is carried out. In your case this is printf("\n%d\n",i)
Repeat Step 2 to 4, until step 2 is FALSE.
In your case, you can see that the printf will be done for i==7 first, and then the expression will be checked for i==7. After that the for loop will exit. Similarly the first print will be done only after one increment on i
So, first print will be for 2 and last will be for 7
You've written the loop incorrectly - you've swapped the body of the loop with the incrementation code. So after having done i++ which is in the body of the loop, it does the printf as the incrementation when that should be the other way around.
Write the for loop correctly as follows.
int i;
for(i=1;i<=6;i++)
printf("\n%d\n",i)
Related
I am using a program to detect the boundary of each data type, which is like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
/*first while loop using a++ dosesn't give us a right answer*/
int a = 0;
while (a++ > 0);
printf("int max first = %d\n", a-1);
/*second while loop using ++a performs well*/
int b = 0;
while (++b > 0);
printf("int max second = %d\n", b-1);
system("pause");
return 0;
}
After I compile this propram and excute it, it returns:
int max first = 0
int max second = 2147483647
So I try to debug it, and I find out that in the first part, after a++ becomes 1, then it just stop autoincrement and jump the while loop,while in second part it runs well, why is this happening?
The pre-increment operator (e.g. ++b) is done first, and the value of the expression is the incremented value.
That is
int b = 0;
while (++b > 0) ...
will increment b first and then check its value using the larger-than comparison. Since in the very first iteration ++b will make b equal to 1 the condition will be 1 > 0 which is true.
Now the post-increment operator does the increment after the old value is used.
So for example a++ will return the old value of a and then do the increment.
So with
int a = 0;
while (a++ > 0) ...
the very first iteration a++ will return 0 which means you have the condition 0 > 0 which is false and the loop will never even iterate once. But the value of a will still be incremented, so afterwards it will be equal to 1 (when the loop have already ended).
This behavior of the pre- and post-operators should be part of any decent book, tutorial or class.
after a++ becomes 1, then it just stop autoincrement and jump the
while loop
This happens because of the post and pre increment operators and the ; in while loop working together.
a will be incremented by 1 after the condition a++ > 0 is evaluated. Thus, the condition fails. The ; at the end of the while statement results in an empty loop and the next print statement will be executed even if the condition on which the while loop is based returns true.
This is exactly what happens in the second while loop - the pre increment operator will increment b before the condition is checked inside while (++b > 0);. The empty while loop keeps on adding one to the value of b until there is an overflow.
At this point, strictly speaking, you have invoked undefined behaviour because the operation has resulted in overflowing a signed integer.
Let me rewrite the main function you wrote - so that it becomes easier to understand.
int main()
{
/*first while loop*/
int a = 0;
while (a > 0){ a = a + 1; }
printf("int max first = %d\n", a-1);
/*second while loop*/
int b = 0;
b = b + 1;
while (b > 0){ b = b + 1; }
printf("int max second = %d\n", b-1);
system("pause");
return 0;
}
Some observations regarding what happened here:
Because at the beginning of the first while loop - the value of a is 0 - which is not greater than 0; the loop gets skipped at the beginning. As a result, the first printf outputs 0.
At the beginning of the second while loop, before evaluating the loop control condition; the loop control variable b gets incremented by 1, resulting the value of b becoming 1; which is greater than 0. For this reason, the second loop is executed.
While executing the second loop, the value of b keeps incrementing by 1 until the value of b overflows. At this point, the program encounters undefined behaviour - and exits the while loop if the program doesn't crash or keeps executing the loop indefinitely (in which case, at some stage the OS will terminate the program; or ask the user to terminate it - as the program will become non-responsive).
You mentioned that you wanted to measure the limit of int values; I hope this reference and this reference will help you in some way.
What will be the output of the program?
#include<stdio.h>
void main()
{
int i = 0;
while(i < 10)
{
i++;
printf("%d\n",i);
}
}
Will the output start from 0 or from 1 as I my professor taught me that the value of the variable is incremented only at the end of the loop while using i++ unlike in ++i?
The side effect of incrementing using either the prefix ++ or the postfix ++ occurs before the statement i++; completes. The fact that the statement is in a loop doesn't change that.
Your professor is correct. The first time printf is called in the loop, i will have the value 1 because the previous statement incremented the value.
Had you instead had the following code:
while(i < 10)
{
printf("%d\n",i++);
}
Then 0 would be printed on the first iteration. In this case, the value of i is incremented, but the postfix ++ operator means that the old value of i is passed to the printf call.
will start from 1 since the line i++ ends before you enter the next line which prints, the ++i compared to i++ is different when you increment it while doing something else in the same line/command.
for example: if you use
printf("%d",i++);
it would print 0 before incrementing i but if you put it like this:
printf("%d",++i);
it will first increment i (from 0 to 1) and then print i(which is 1 the first time it's printed).
Your code will print 1 as first value.
i++ increments the value at the end of the statement, and vice versa ++i increments the value before the statement. This is usually used when assigning variables:
i = 5;
int a = ++i; // a=6, i=6
i = 5;
int b = i++; // b=5, i=6
I have a code:
while (i = j) {
/* not important */
}
For how long will this while loop work? Is it till the moment when the value of variable j is equal to zero?
For while loop properties, quoting C11, chapter §6.8.5/p4, (emphasis mine)
An iteration statement causes a statement called the loop body to be executed repeatedly
until the controlling expression compares equal to 0. [...]
and considering the assignment inside the loop condition, quoting §6.5.16/p3
[...] An
assignment expression has the value of the left operand after the assignment,111) but is not
an lvalue. [...]
So, every time the loop condition is executed, first the current value of j will be assigned to i and then, the value of i will be taken as the controlling expression value.
In other words, the loop will continue until j becomes 0.
That said, iff you are sure about the assignment part as the loop condition statement, put it into double parenthesis like
while ((i = j)){
Less confusion for the compiler and the next developer/maintainer.
For how long will this while loop work? Is it till the moment when the value of variable j is equal to zero?
A while loop would would work till it's the condition or expression evaluates to be false (i.e, 0).
In your code, YES while loop works till the moment when the value of variable j is equal to 0.
Note : The assignment operator in C returns the value of the variable that was assigned i.e, the value of the expression i = j os equal to j.
In while(i = j) , first i is assigned with value of jand then the expression is evaluated whether true or false.
Why not try a simple program :) :
#include <stdio.h>
int main(void)
{
int i = 0,j =10;
while (i = j)
{
printf("in loop when j = %d\n",j);
j--;
}
printf("exited loop when j = %d",j);
}
output :
in loop when j = 10
in loop when j = 9
in loop when j = 8
in loop when j = 7
in loop when j = 6
in loop when j = 5
in loop when j = 4
in loop when j = 3
in loop when j = 2
in loop when j = 1
exited loop when j = 0
An assignment operation always returns the result of the assignment, so the loop will continue until j == 0, this behavior exists so you can chain many assignment operations together like so:
a = b = c;
Please explain me why the last printf gives value 11?
I really don't understand why it happened.
When a = 10 the condition is not fulfilled so why this value has changed to 11?
Incrementation goes as soon as the condition is checked?
Code:
int main(void) {
int a = 0;
while(a++ < 10){
printf("%d ", a);
}
printf("\n%d ", a);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
11
Let's look at a++ < 10 when a is equal to 10.
The first thing that will happen is 10 < 10 will be evaluated (to false), and then a will be incremented to 11. Then your printf statement outside the while loop executes.
When the ++ comes on the right hand side of the variable, it's the last thing evaluated on the line.
Try changing a++ < 10 to ++a < 10, rerunning your code, and comparing the results.
The post increment operator increments the value of the variable before it after the execution of the statement.
Let's take an example,
int k = 5 ;
printf("%d\n", k++ );
printf("%d", k );
will output
5
6
because in the first printf(), the output is shown and only after that, the value is incremented.
So, lets look at your code
while(a++ < 10)
it checks a < 10 and then after that, it increments a.
Lets move to a few iterations in your loop.
When a is 9, the while loop checks 9 < 10 and then increments a to 10, so you will get output for that iteration as 10, and similarly, for the next iteration, it will check 10 < 10 but the while loop does not execute, but the value of a is incremented to 11 and thus, in your next printf() , you get output as 11.
Let's look at a simpler piece of code to show what a++ does.
int a = 0;
int b = a++;
printf("%d %d\n", a, b);
I think that you'd expect this to output 1 1. In reality, it will output 1 0!
This is because of what a++ does. It increments the value of a, but the value of the expression a++ is the initial pre-incremented value of a.
If we wanted to write that initial code at the top of my answer as multiple statements, it would actually be translated to:
int a = 0;
int b = a;
a = a + 1;
printf("%d %d\n", a, b);
The other increment that we have access to is pre-increment. The difference there is that the value of the expression ++a is the value of a after it was incremented.
Because it's post-increment. The compiler will first evaluate a<10 and THEN increment a by 1.
This question already has answers here:
What does the comma operator , do?
(8 answers)
Closed 8 years ago.
I can't understand how this works and why it produces
the following output.
int main()
{
int i=0;
int a=5;
int x=0;
for(i=0; i<5; x=(i++,a++))
{
printf("i=%d a=%d x=%d\n",i,a,x);
}
}
this give as output:
i=0 a=5 x=0
i=1 a=6 x=5
i=2 a=7 x=6
i=3 a=8 x=7
i=4 a=9 x=8
Forget about the ++ for the moment, they're just a distraction.
int a = 5;
int i = 0;
int x = (i, a);
Sets the value of x to 5. The i is evaluated and discarded, then the a is evaluated and assigned to x.
In your loop, the post-increment a++ does what it always does; returns the current value and then increments the variable. So x takes the value of a before it is incremented, then a's value is increased by 1. Because i++ was also evaluated, its value increases as well.
I suppose you understand a for loop like this:
for(i=0; i<5; i++)
you might as well want to increment two variables; if you separate them with a comma; like this:
for(i=0; i<5; i++,a++)
at the start of each loop, both i and a will be incremented. Now only the expression x=(i++,a++) needs to be explained:
x gets the last of both values assigned. It is the same as writing:
x=i++;
x=a++;
of course a is post-incremented so first its value is assigned to x; and only then a is incremented.
It is simple both the operators that you have used are 'Post Increment', this means that assignment will happen first then the increment in variable will happen.
Let us understand with an example,
Suppose,
i=5
x=i++;
printf("%d", x)
The above code will give output as 5
and
i=5
x=++i;
printf("%d", x)
and this will give output as 6.
Hope you understand the logic.
The comma operator means: execute all, and return the last value;
Example:
A = (b+=1,c+2,d+1);
This sentence will add 1 to b, sum 2 to c (but will not modify it) and sum 1 to d. Hence d+1 is the last expression A will be set to its value.
The post and pre operator ++ are tricky.
A++ means: return the value of A and after that, you increment it.
++A means: increment A and then return the value of it.
so if A=2
b=A++; // set b to 2 and increments A one unity
b=++A; // increments A to 4 and sets b to 4
Consider your example and the output (except I made the initial value of x to be 22):
int i=0;
int a=5;
int x=22;
for(i=0; i<5; x=(i++,a++))
{
printf("i=%d a=%d x=%d\n",i,a,x);
}
Prints:
i=0 a=5 x=22
i=1 a=6 x=5
i=2 a=7 x=6
i=3 a=8 x=7
i=4 a=9 x=8
Notice that x has either the initial value of x prior to the loop or the previous value from the last trip through the loop.
Recall that any for loop can be expressed as an equivelent while loop.
The for loop of:
for(exp 1; exp 2; exp 3){
expressions
}
Is equivalent to:
exp 1;
while(exp 2){
expressions
exp 3;
}
So your for loop can be written as:
int i=0; // exp 1 from the for loop
int a=5;
int x=22;
while(i<5){ // exp 2
// loop body
printf("i=%d a=%d x=%d\n",i,a,x);
x=(i++,a++); // exp 3 from the for loop
}
Prints same output.
The fact that exp 3 is evaluated at the end of the loop (whether it is a for or while loop) is why x has the previous value of x in the body of the loop.
The final thing to consider is the comma operator. The expression:
i=(a+=2, a+b)
^^^ evaluate a then add 2
^ comma operator in this case
^^ add b to a
^ store the final expression -- the RH of the comma operator --
into i