C Programming - Declarations and Initializations - Discussion

Discussion Forum : Declarations and Initializations - Find Output of Program (Q.No. 11)
11.
In the following program how long will the for loop get executed?
#include<stdio.h>
int main()
{
    int i=5;
    for(;scanf("%s", &i); printf("%d\n", i));
    return 0;
}
The for loop would not get executed at all
The for loop would get executed only once
The for loop would get executed 5 times
The for loop would get executed infinite times
Answer: Option
Explanation:

During the for loop execution scanf() ask input and then printf() prints that given input. This process will be continued repeatedly because, scanf() returns the number of input given, the condition is always true(user gives a input means it reurns '1').

Hence this for loop would get executed infinite times.

Discussion:
49 comments Page 2 of 5.

Sundar said:   1 decade ago
@Wikiok

Yes. You are absolutely correct.

@All

While testing this type of code this system may hang due to infinite loop (press Ctrl+C to exit in DOS).

Ramya said:   1 decade ago
Hi sundhar. Here we don't have any initialization to i.

So how we get infinite loop. Explain me.

Shiva said:   1 decade ago
Hi Ramya,

For loop syntax is: for(;;)

Here we have three places for initialization, condition and increment/decrement.

These are choices, if we dont write any one from those three. There is no problem in execution.

In our program there is no initialization part so it will not affect to the program, it just checks the condition and it executes both condition, increment/decrement parts. It wont see about initialization, if it is there it will execute.

So the program is correct.

Sandip said:   1 decade ago
Here for loop end with (;)
Is it correct syntax ?
please any body help me...

Adi said:   1 decade ago
I think printf () is terminated by ;.

So here use it.

Kush said:   1 decade ago
Can anyone explain what exactly does this mean in this question ?
scanf("%s", &i)

Sonalika said:   1 decade ago
What if user do not gives any input? how it would run then. !

Priyanka said:   1 decade ago
The for loop ends with a semi-colon, so how can it run infinte times?

Krati said:   1 decade ago
@priyanka.
For loop with a ; execute condition until it fail but loop with a ; never execute statement next to for loop that's why for loop in this example execute until it fail but there is so such condition and that's why execute infinite times.

Sameer said:   1 decade ago
What if I remove the semicolon?

What will happen?

I heard that semicolon terminates the loop. correct me if I'm wrong.


Post your comments here:

Your comments will be displayed after verification.