How is the working of fflush(stdin) changing the output in below code?

In no some magical way.

First of all, fflush(stdin); invokes undefined behavior. Don’t use that.

Quoting C11, chapter ยง7.21.5.2, The fflush function (emphasis mine)

If stream points to an output stream or an update stream in which the most recent
operation was not input, the fflush function causes any unwritten data for that stream
to be delivered to the host environment to be written to the file; otherwise, the behavior is
undefined.

That said,

for(j=0;j<n;j++)
{
    fflush(stdin);
    scanf("%d",&arr[i]);
}

looks pretty wrong to me, arr[i] is not guaranteed to be within bounds. It should rather be

scanf("%d",&arr[j]);

Leave a Comment