Why the Semicolon is not emptying the loop body? - c

The semicolon at the end of the for loop is suppose to empty the body and create a null loop. But why this is printing 6?
void main()
{
int i;
for(i=1;i<=5;i++);
{
printf("%d\n",i);
}
}

The loop body is empty, otherwise it would print 1, 2, 3, 4, 5. But the loop head runs nethertheless and in each iteration it increases i. When it reaches 6 which is not <=5 the loop ends. Printing i after the loop prints i as 6. Incrementing i is a side effect of the loop.

It is.at the end of the loop i will be 6 and the printf does this.

The for loop for(i=1;i<=5;i++); will run exactly 5 times, incrementing i from 1 to 6 (even though the for loop body is a no-op). Thus, in here:
{
printf("%d\n",i);
}
the program will print the current value of i, that is 6.

Because you declare the int outside the null loop, the value is saved outside the increment loop.
Read more about it here
The extra brackets do not do anything here because the semicolon exits the loop.
Read more about brackets here.

Try this for fun
#include <stdio.h>
int main(void)
{
int i;
for (i = 1; i <= 5; i++) /* void */;
/* floating block one */
{
int i = 42; /* new i, hides old i */
printf("%d\n",i);
}
/* floating block two */
{
printf("%d\n",i);
}
}

it is quite simple:
for(i=1;i<=5;i++); will be executed 5 times, from 1 to 5
then i=6 ends the for loop and then a new "scoped" statement is executed:
printf("%d\n",i);
therefore prints 6

Related

Why is the output coming as 8883. How is the code is being executed?

Variable i is becoming 8 at the first entry in loop. Then how the condition i <= 2 satisfied next time?
#include <stdio.h>
int main()
{
int i;
for (i = 0; i <= 2; i++)
{
int i = 8;
printf("%d", i);
}
printf("%d", i);
return 0;
}
It prints 8 three times from the loop with i = 0, i = 1 and i = 2.
for(i=0;i<=2;i++)
{
int i=8;
printf("%d",i);
}
The second variable i (the one declared inside the body of the loop) will not affect the first i (the one declared outside the loop), because it is declared in a different scope i.e., inside the loop.
Final the last 3 comes from because the inner most i will be increment on last time before exit the loop. So for:
printf("%d",i);
the variable i will take the value 3.
The variable i you modify inside the loop body is a different variable from the i defined before the for loop and used in the loop tests.
int i defines a new variable only accessible inside the loop body, which is a block with its own scope.
Hence the code prints 8 3 times, once for each iteration of the loop and 3 which is the value of the variable i of the main body after the loop.
Here is a modified version that will print 89 as expected:
#include <stdio.h>
int main() {
int i;
for (i = 0; i <= 2; i++) {
i = 8;
printf("%d", i);
}
printf("%d", i);
return 0;
}
It sets i to 8 and prints 8 inside the loop body for the first iteration, then i gets incremented, 9 is greater than 2 so the loop exits and 9 is printed by the final printf.
int i=8 is a declaration of a new variable (declares and initializes new variable) which is in a local scope that shadows the existing variable from the more general scope.
In other words:
First int i defines variable;
for uses that variable and initializes it with 0 and starts a cycle;
int i=8 - as it is written with int - defines new local variable that because it has the same name that i from outer scope - shadows it ("shadowing" is a term). And so further code in the loop uses new local i which set to 8.
Internal printf("%d",i); prints 8.
Cycle ends and local scope gets erased, and so that internal i=8 erased also.
for lives outside (in more general scope) of the scope of the loop. for condition uses variable from outside, which was set to i=0 in step #2. So for in a second cycle instructed to increment (i++) it, so i=1, which passes the i <= 2 check. So for indeed starts executing next cycle of internal code.
Inside for loop external i gets shadowed by internal int i=8... (step #3).
In short: It is because code declares a new variable with int i.
The good style is to:
for(int i=0;i<=2;i++) - always declare and initialize the variable in one instruction.

Why no output when index value is 0

Change the value of index from o to 1. loop is printing value. Why it is not printing any value when index is assigned to 0?
Currently i = 0 - No Output
Make i = 1 - infinite loop
#include<stdio.h>
int main()
{
for(int i = 0;i++;i<100)
{
printf("Mahesh\n");
}
}
enter code here
C for loop structure:
for ( init; condition; increment )
You have actually added i++ in the place of condition and i<100 in the place of increment.
Flow Control of for loop in C:
init step is executed first and only once.
Condition is evaluated next and if it is True, the body of the loop is executed. If False, the body of the loop doesn't execute and the flow jumps to the next statement after the for loop.
After the body of the loop executes once, the flow control jumps to increment statement and then condition is evaluated again.
Body of loop, Condition and increment steps are repeated in the same order till the condition becomes False after which the for loop terminates.
Your loop is:
for(int i = 0;i++;i<100)
In this, you have i++ as the condition. Now, in this i is evaluated first followed ++. Since, i is 0, it leads to the loop exiting as the condition evaluates to False. But, if you change i to 1, the condition (i.e. i) evaluates to True and it enters the loop.
If you have not done this deliberately, you need the loop like below:
for (int i = 0; i < 100; i++)
The syntax for a for loop in C is as follows:
for ( init; condition; increment ) {
statement(s);
}
-init: initialising the index variable with the value you would like to start the iteration at.
-condition: the condition for the iteration to continue until met
-incremenet: indicating how much you want the program to incremenet your index by
Hence in your example is should be:
for(int i = 0; i < 100; i++){
//yourcode
}
Hope that helps
The parameters of for loop are:
for(initialization; Condition; Next iteration initialization){
//code
}
The initialization(s) can be more than one separated by commas.
The condition will continue if have 1 (or the value TRUE which means the same thing as 1) or will break if the condition is not met i.e the value 0 (or FALSE). You can have multiple conditions as well by the use of && or || or commas.
The third parameter is what you want to do in the next iteration. It can have multiple commands too. I suggest you run the following code and change it to observe the results:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j;
for( i=0,j=0;i<10 || j<5;i++,j++)
printf("%d\t%d\n",i,j);
return 0;
}
#include<stdio.h>
int main()
{
int i = 0;
// Postfix Increment Operator
for (i = 0; i++; i<100) // Condition is false, Because the i is Zero
{
printf("Mahesh");
}
printf("%d", i); // i outputs One here
// Prefix Increment Operator
for (i = 0; ++i; i<100) // Condition is True, Because the i is One
{
printf("Mahesh");
}
}

C for loop continues incrementation

Newb here.
I'm probably missing something trivial but:
Here's the thing: http://i.imgur.com/8BmPci5.png
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Sort Numbers (zuerst)
int numbers [10];
int i,j;
j = 0;
int read;
printf("Input numbers: \n");
for (i=0;i<10;i++) {
scanf("%d",&read);
if (read == 27) {
break;
} else {
numbers[i] = read;
j++;
}
}
printf("j is: %d, i is: %d\n", j, i);
for (i=0;i<j;i++) {
printf("numbers[%d] is: %d\n", i, numbers[i]);
}
return 0;
}
Output:
Input numbers:
1
2
3
^[
j is: 10, i is: 10
numbers[0] is: 1
numbers[1] is: 2
numbers[2] is: 3
numbers[3] is: 3
numbers[4] is: 3
numbers[5] is: 3
numbers[6] is: 3
numbers[7] is: 3
numbers[8] is: 3
numbers[9] is: 3
I have a for loop (goes from 0 to <10). I also have a scanf inside wich scans for an int. If it ain't ESC (ASCII 27), then it puts it into an array and it increments the value of j. If it's an ESC, it ('s supposed to) break (exit the loop). Later, only j (or j-1) number of array items would be printed.
Issue: j (and i too) increments to 10, even if break is called at ~ i = 3 or 4.
Break supposed to exit the for loop without doing anything after it's called, right? Quote from BeginnersBook.com:
It is used to come out of the loop instantly. When a break statement is encountered inside a loop, the control directly comes out of loop and the loop gets terminated. It is used with if statement, whenever used inside loop.
What's wrong with my code? Thanks in advance.
You're being naughty in that you're not checking the return value of scanf, which will tell you the number of variables that were successfully populated. In your case, you want that to be 1 to signal that something was read into your variable read.
If you try to pass \033 (ASCII encoded ESC), then scanf will fail to parse that to an int. Then the previous value of read will be retained (which could give you undefined effects if it hasn't yet been set to anything), and read == 27 will almost certainly be 0. That behaviour accounts for the output you are observing.
If scanf does fail, you could try reading a char from the stream, and check if that is equal to \033.

Why this isn't an infinite loop? How is it working?

Trying this code and the output as per my book is -10 to -1. How this is being printed is really baffling me.
#include <stdio.h>
void main()
{
int var = -10;
for(; var; printf("%d\n ", var++));
}
Let's go through this step by step:
The int var variable is initialised to -10. So far, so good.
Now we get to the interesting part of this: the for loop. We have a powerful construct with the following form:
for (/* initialisation-statement */ ; /* condition */ ; /* iteration-statement */)
/* statement or block of code */
With your code, we have nothing for the initialisation statement (int var = -10 could go here), var for the condition, and printf("%d\n ", var++) for the iteration statement.
In case you're not familiar with how for loops, here's a more primitive (but still equivalent) form:
{
/* initialisation-statement */;
startloop:
if (/* condition */) {
/* statement or block of code */
/* iteration-statement */;
goto startloop;
}
}
Putting for(int var = -10; var; printf("%d\n ", var++)); into this, we get:
{
int var = -10;
startloop:
if (var) {
;
printf("%d\n ", var++);
goto startloop;
}
}
When the printf("%d\n ", var++); statement is executed, it prints the value of var++ to stdout. The postfix version of the ++ operator increments the value, but evaluates to the original value.
Because var controls the loop, it will keep the loop going as long as it evaluates to true (non-zero). Since var is incrementing from -10, it will end up reaching 0 and ending the loop.
SIDE NOTE: void main() is not standard. Use int main(void) or int main(int argc, char *argv[]) instead.
It is working for below reasons
The var in the if condition serves as a boolean expression, its value is evaluated and any non-zero value serves as true and a zero value serves as false.
var++ in printf("%d\n ", var++) is postfix operator applied on var. It takes the current value and then increments var by one.
Eventually var reaches zero (Read it along with the first point)
Here you have your code a little bit formatted. Note that the following code does exactly the same thing as yours:
#include <stdio.h>
int main()
{
int var;
for (var=-10; var!=0 ;var++) {
printf("%d\n ", var);
}
return 0;
}
The condition var!=0 will be evaluated in your code as well automatically. In C everything !=0 is true and 0 is false.
Generally in programming, every integer (to a boolean) except for a 0 is interpreted as the boolean true.
Only a 0 is interpreted as false, so the loop breaks at var = 0 and 0 doesn't get printed.
Also: If you would put any positive integer in var and run the same loop, the loop would count up infinite times because it never hits 0, except if you'd wait to get to an overflow. That is, when you add 1 to 2,147,483,647 (increment) and get a -2,147,483,648. Since then var is negative again but still counting up, eventually you reach 0 and the loop will break.
first, var++ means var = var + 1;
which means that the loop goes from -10 to -1.
therefore printf("%d\n ", var++) will increment var by one and print the var.
the diff between var++ and ++var is that in var++ the printf happened first and than the +1 because of that you see output from -10 to -1.
second, 0 in C means false. then var become 0 the loop stops.
also the loop can be for(int var = -10;var;printf("%d\n ", var++)) ; which is the same as for(;var;printf("%d\n ", var++)) ;

(segfault) Error reading variable, cannot read variable at address X

I'm trying to write code for the gas station problem, where you have a fixed number of cities(linear) and you want to get from one end to the other with as few stops as possible, stopping wherever necessary to refill your gas tank. This is my main function; the function for calculation I've left out for now.
I keep segfaulting saying unable to access tank and arr during the call to solver(the function I'm using to solve).
int main(void)
{
int tank;
int cities;
int ans;
scanf("%d %d",&cities, &tank);
int *arr;
arr=(int *)calloc(cities,sizeof(int));
int *arr2;
arr2=(int *)calloc(cities,sizeof(int));
int i;
for(i=0;i<cities;++i)
scanf("%d",&arr[i]);
arr2[i]=0;
for(i=1;i<cities;++i)
arr2[i]=arr[i]-arr[i-1];
for(i=0;i<cities;++i)
printf(" %d ",arr2[i]);
ans=solver(tank, arr2,cities);
printf("\n ans is %d",ans);
return 0;
}
Can I get some pointers here(terrible pun)?
I'm using the input as:
6 3
0
1
3
4
7
10
Arr holds [0,1,3,4,7,10]
Arr2 holds the differences.
Your loop statement is the problem because of missing encolsing {}:
for(i=0;i<cities;++i) // loop
scanf("%d",&arr[i]); // but there is no enclosing braces. so this is the only statement that loops
arr2[i]=0; //<<<<<< this is executed when loop is finished, i.e i==cities
In other words, you assign arr2[cities], which is out of bouds as it's indexed from 0 to cities-1. This causes the segfault.
Looking at the rest of the code, I guess you inteded to to:
...
for(i=0;i<cities;++i) { // loop, but for the block
scanf("%d",&arr[i]);
arr2[i]=0;
}
...

Resources