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.

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?

Anu said:   8 years ago
I am not getting this, please give a clear explanation.

Divya said:   8 years ago
Hi everyone, I just checked the output and the above code is not taking any input from user instead it is printing 5 infinite times. I couldn't understand this. Can anyone explain how this will work?

Vishi said:   8 years ago
So, which is the correct answer?

Option A or D?

Rakesh said:   8 years ago
No, It will not execute. In scanf statement, they put %s for int. It's an error.

Yallaling said:   8 years ago
Yeah, even I also got the same output @Manjula. What is the meaning of that unexpected error occurred?

Manjula said:   8 years ago
@All.

After executing this same program, I got this error " Unexpected error occurred. Please try again after few seconds." it is showing error in scanf and printf.

Actually, it's not executing the for loop so may be the answer is not correct please check and give me the solution.

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.

Bala Ramya said:   9 years ago
Here, why they used %s for integer type. Will anyone explain it?

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.