For loop with ; in C [duplicate] - c

This question already has answers here:
For Loops and stopping conditions
(4 answers)
Closed 2 years ago.
While studying for my exam I saw a question which is as shown below can someone please explain to me that does the ';' means at the end of the for loop and can I also put it in a while loop? And what is the difference between the Compile-time error and the Compilation error?
#include <stdio.h>
int main(){
int value;
for ( value = 1; value <= 15; value+=3);{
printf("%d", value);
}
return 0;
}

This is probably a mistake; it is syntactically correct, but actually would be read by the compiler like this:
for (value = 1; value <= 15; value+=3);
// Unrelated block!
{
printf("%d", value);
}
This means that the loop will execute, then run four more times, but not actually do anything, then the block will execute once.
Where the loop and the block following it are completely separate and unrelated.

The semicolon ; terminates the definition of the loop body. In this case there are no statements in the body of the loop, hence the only affect of the loop is to modify the value of the counter variable, value.
The statement following the semicolon has it's own scope thanks to the curly braces, but it has no real affect in this case.
The printed result will be the value of value after the (empty) loop has executed, i.e. 16.
You could not do the same with a while loop because the variable would need to be incremented within the body of the loop and the value tested at each iteration to decide whether to continue looping.
Of course, you could avoid any loop by initialising value to 16.

Related

question related to for loop condition statement in C [duplicate]

This question already has an answer here:
what is the difference between while(i>0) and while(i)
(1 answer)
Closed 6 months ago.
I am trying to run a program in C, where the following statement is used in the code.
What does the following statement mean in the for loop condition of the given code?
I understand i is being initialised with value 3; and i gets updated in i = i-1 ; but what does the condition part mean? why only i; should it not be i>0? Why both statements give the same output , i.e *** .
Code statements:
int main()
{
for(int i=3;i;i=i-1)
{
printf("*");
}
return 0;
}
Simply, i will be true when != 0. Since your program must keep going until i is zero, It will keep checking. Here's a list of what the condition returns:
i value
output returned by i
3
true
2
true
1
true
0
false (break)
C 2018 6.8.5.3 discusses the for statement, which has the form for (clause-1; expression-2; expression-3) statement, and paragraph 1 says:
… The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body…
6.8.5 4 says:
An iteration statement causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0.
Therefore, with i for the controlling expression, the loop body is executed repeatedly until i compares equal to zero.

Can someone explain output of this C program? [duplicate]

This question already has answers here:
unexpected output in C (recursion)
(3 answers)
Closed 4 years ago.
#include <stdio.h>
int main()
{
static int i = 5;
if (--i)
{
main();
printf("%d\n", i); // will this line executes ?
}
return 0;
}
Output:
0
0
0
0
does code below main(); printf statement instructions is placed to stack every time when main recursive calls happens and executed while terminated from this program?
i is reduced by successive calls to main until zero is reached.
Then printf is called for each level of recursion.
(Note that the behaviour of calling main from itself is well-defined although ill-advised in C, in C++ the behaviour is undefined.)
if (--i)
This will evaluate true the first time (--i == 4). The code recurses into main(). (Recursion: A function calling itself.)
As i is static, it will retain its value of 4 (as opposed to an automatic variable, which would be initialized to 5 again). The if (--i) in this second execution of main() will again be true (evaluating to 3), and will again call main() (for a third execution of the function).
The same for --i == 2 and --i == 1, for four executions of main() (including the first, non-recursive one) total that are evaluating the if condition to true.
The next recursion will evaluate the if condition to --i == 0, and thus false. Skipping the if clause, the function call will just return. i is zero at this point, and -- being static, i.e. only one persistent i for all instances of main() -- will remain at that value.
The main() call one level up the stack -- the one that evaluated --i == 1, then called main() and was waiting for it to return -- will now continue with the statement after the call to main(), and printf() the current value of i... which is 0.
The same happens three more times (for a total of four) until the top-most main() returns. You get four times the current value of i, which is 0.
Note that calling main() from your program is allowed in C, but not in C++. This is specifically for calling main() recursively; for other functions, it is allowed in either language.
(--i) will decrease the value of i to 4 when it is called for the first time and it will continue the decrement of i until (i==0) due to recursion.
Since you have declared the variable i with static keyword and hence a single memory is allocated to it and all the changes are reflected back to it

what happens when increment counter and test counter are interchanged in for-loop syntax? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
please explain why
Case 1:
int main()
{
int i;
for(i=1;i++;i<100)
printf("%d",i);
return 0;
}
results in infinite loop, whereas
Case 2:
int main()
{
int i;
for(i=0;i++;i<100)
printf("%d",i);
return 0;
}
Doesn't run the loop even once?
Please clarify how to interpret this kind of syntax?
The syntax of a for loop in C programming language is:
for ( init; condition; increment )
{
statement(s);
}
Here is the flow of control in a for loop:
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 flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
In First Case:
init set i = 1
conditon - here i = 1 which is true in c. (Post increment increases the value after execution of statment)
body - executes printf("%d",i);
increment - i<100 which is not affecting the value of i.
Now In C for all values from 1 to infinity, its value is true, hence executing infinetly
In Second Case
init set i = 0
conditon - here i = 0 (again Post Increment) which is false in c, therefore the loop gets exit.
Hence it is not executing even once.
Flow diagram of For Loop :
The proper syntax is
for (i=1; i<100; i++) {
something
}
What's actually happening?
The for loop takes three arguments,
1. The initial condition, or initialization that happens at the beginning, before the loop is executed. In this case it's i=1 that is set i as 1
2. The final condition that is checked at the beginning of every loop. If this condition is not met, the loop is broken. In this case it's i<100. So, if at the start of next loop, when i >= 100 the loop is broken.
3. The step or periodic operation at the end of loop. In this case it's i++. At the end of every loop i is incremented by 1.
What's happening with your code
for (i=1; i++; i<100)
The first part is good.
The second is executed at the beginning of each loop. i++ returns the value of i then increments it. (In contrast to ++i, which does the opposite.) Since in your first example i=1, it starts at one, and the second argument always returns a value >= 1 which is interpreted as true. But in your second example, i starts at 0. So during first iteration the second argument returns 0, which is interpreted as false, and the loop never starts.
The third one is executed at the end, and never affects the loop in any way.
int main()
{
int i;
for(i=0;i++;i<100)
printf("%d",i);
return 0;
}
as for loop is having syntax
for(initialize variable; condition check; increment/decrement)
you have initialize variable as i = 0
in condition checking part you have written i++ i.e post increment so i remain 0 which means FALSE and hence it will exit for loop.
Try this :
int main()
{
int i;
for(i=0;i<100;i++)
printf("%d",i);
return 0;
}

Preincrement in character pointers [duplicate]

This question already has answers here:
What is the difference between ++i and i++?
(20 answers)
Closed 7 years ago.
I was toying with the concept of array pointers. I wrote this simple program:
#include <stdio.h>
int main (int argc, char **argv){
char s[] = "Hello world!\n";
char *i;
for (i = s; *i; ++i){
printf(i);
}
return 0;
}
which gives the very amusing output:
Hello world!
ello world!
llo world!
lo world!
o world!
world!
world!
orld!
rld!
ld!
d!
!
When I wrote this, however, I was under the impression that the output would start from the second row. Reason being, in the for loop, I use a pre-increment notation. i is set to the beginning of s, the Boolean condition is checked and it holds true, then i gets incremented and the block executes.
That was my impression, but obviously it is erroneous as the block executes before i gets incremented. I rewrote the program using a post-increment notation and got exactly the same result which confirms my hypothesis. If that is the case, then how are they treated differently in this program?
for (initialization; condition; increase) statement;
This for works in the following way:
initialization is executed. Generally, this declares a counter variable, and sets it to some initial value. This is executed a single time, at the beginning of the loop.
condition is checked. If it is true, the loop continues; otherwise, the loop ends, and statement is skipped, going directly to step 5.
statement is executed. As usual, it can be either a single statement or a block enclosed in curly braces { }.
increase is executed, and the loop gets back to step 2.
the loop ends: execution continues by the next statement after it.
There is no difference between postincrement and preincrement because increase is executed separately anyway.
The increment expression of the for loop is executed after the body. For your case
for (i = s; *i; ++i){
printf(i);
}
is similar to
i = s; // loop init
while (*i) // loop condition
{
printf(i);
++i; // loop increment
}
i is set to the beginning of s, the Boolean condition is checked and it holds true, then i gets incremented and the block executes.
Not quite. The actual syntax is
i is set to the beginning of s
the Boolean condition is checked
2.1. if it holds true the block executes,
2.2. come out of loop otherwise.
then i gets incremented and continue to step 2.
Note: In this particular scenario, pre and post increment to i are not going to make any difference.
the equivalent of
for( a ; b ; c )
{
statements
}
is
a ;
while( b )
{
statement
c ;
}
and
++i ;
i++ ;
are the same things, because i is only evaluated and the evaluation isn't used
Reason being, in the for loop, I use a pre-increment notation. i is set to the beginning of s, the Boolean condition is checked and it holds true, then i gets incremented and the block executes.
No. i is incremented after the block executes.
I rewrote the program using a post-increment notation and got exactly the same result which confirms my hypothesis. If that is the case, then how are they treated differently in this program?
They're not. Post-increment or pre-increment isn't going to make a blind bit of difference. The difference between those two is in the result of the expression i++, ++i (namely, will it evaluate to the previous value or to the new value?). It does not magically alter the entire flow of an encapsulating control structure. The evaluated result of the increment expression is just thrown away so it doesn't matter what you do as long as you provide an expression that results in incrementing i.
It's like how this:
int main()
{
int x = 5;
int y = 5;
int a = x++;
int b = ++y;
}
will result in different values for a and b because the result of the increment expression is used, whereas the following programs:
int main()
{
int x = 5;
x++;
}
int main()
{
int x = 5;
++x;
}
are identical.
i gets incremented after the block get executed.
Try this:
for(int i = 0; i < 5; ++i )
{
printf("\n %d",i);
}

Can an empty for-loop be "correct"?

I have a doubt about the for loop of the following code in C:
main()
{
int i=1;
for(;;)
{
printf("%d",i++);
if(i>10)
break;
}
}
I saw this code in a question paper. I thought that the for loop won't work because it has no condition in it. But the answer says that the code has no error. Is it true ? If true, how ?
The regular for loop has three parts:
Initialization
Condition
Increment
Usually they are written like this:
for (initialization; condition; increment) { statements }
But all three parts are optional. In your case, all parts are indeed missing from the for loop, but are present elsewhere:
The initialization is int i=1
The condition is if (i>10) break
The increment is i++
The above code can be equivalently written as:
for (int i=1; i <= 10; i++) {
printf("%d", i);
}
So all the parts necessary for a for loop are present, except they are not inside the actual for construct. The loop would work, it's just not a very readable way to write it.
The for (;;) loop is an infinite loop, though in this case the body of the loop takes actions that ensure that it does not run forever. Each component of the control is optional. A missing condition is equivalent to 1 or true.
The loop would be more clearly written as:
for (int i = 1; i < 11; i++)
printf("%d", i);
We can still debate whether the output is sensible:
12345678910
could be produced more easily with:
puts("12345678910");
and you get a newline at the end. But these are meta-issues. As written, the loop 'works'. It is syntactically correct. It also terminates.
You are not specifying any parameters or conditions in your for loop, therefore, it would be an endless loop. Since there is a break condition based on another external variable, it would not be infinite.
This should be re-written as:
for (int i = 1; i <= 10; i++)
printf("%d",i++);
It's an infinite loop. When there is not a condition in for and we use ;; the statements in the body of for will be executed infinitely. However because there is a break statement inside it's body, if the variable i will be greater than 10, the execution will be stopped.
As it is stated in MSDN:
The statement for(;;) is the customary way to produce an infinite loop which can only be exited with a break, goto, or return statement.
For further documentation, please look here.
Even if a for loop is not having any condition in it, the needed conditions are specified inside the for loop.
The printf statement has i++ which keeps on increasing the value of i and next we have if statement which will check if value of i is less than 10. Once i is greater than 10 it will break the loop.

Resources