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.

Sinju said:   9 years ago
Here, for loop and the scan are linked like a same group, I think for loop can write in a separate fashion, then how it correct, and also for loop can not end with a semicolon.

Pragathi said:   6 years ago
In scanf("%s"&I).

Here %s format specifier is used for string. For string no need to take & operator in scanf then how it execute? Explain to me, please.

Wikiok said:   1 decade ago
for (;;) ==> infinite loop. You don't need a condition

while (1) ; ==> while (1) { ; } ==> while (1) {...} where "..." are program lines.

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).

Akhilesh said:   1 decade ago
hi all...
while(1); //this is Infinite loop its ok..i got

while(1) //dis is also Infinite loop bt how i m not geting plz explain more
{
...
}

Thankx

Balaguru said:   7 years ago
for(;scanf("%s", &i); printf("%d\n", i));

In this, when you put semicolon to the for loop it doesn't read that loop.
(5)

Rishikesh said:   9 years ago
Has anyone seen an for loop terminating with a semicolon? It is false as the logic will not enter inside loop also it is syntactically wrong.

Met30 said:   8 years ago
The loop is only going to run once because of semicolon irrespective of scanf or printf, then how the answer comes to infinite?

Sonu Shaw said:   9 years ago
When I run above the code and give as the input 0, 1. Then the output comes 48, 49 like that.

Could you explain, please?

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.