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 3 of 5.

Naveen said:   1 decade ago
Easy guys.

Semicolon terminates for loop removing semicolon results in error.

Its is for loop as for as the condition is correct it keep on executing ie in this case printing the values so infinite loop.

@sonalika.

It waits for the input.

Vinuthna said:   1 decade ago
How can we use "%s" in the scanf statement, when the variable declared is of integer type?

Ayush Rai said:   1 decade ago
But it can be possible that the value entered for i maybe 0 then the condition can exit or somehow scanf("%s", &i) may result in 0 depending upon what user input is ?

Sachin said:   1 decade ago
Hi all,

The loop will execute only once because it is terminated by using ';' symbol.

Keerthana said:   1 decade ago
Here i is an integer but is scanned as a string. Will it not result in error?

Harshit Singh said:   1 decade ago
If semicolon get added in the end of for loop then the for loop will never get executed, hence option A.

Jyosna said:   1 decade ago
Here for loop executes only once at that time it will return error while evaluating scanf statement because access specifier is s and it is followed by &i then how loop will execute infinite times.

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.

Sara said:   9 years ago
scanf("%s", &i)
I didn't get this statement. Can anyone explain me please?

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?


Post your comments here:

Your comments will be displayed after verification.