imox
imox

Reputation: 1554

Working of scanf under for loop

I have a question about working of for loop in C. Please have a look at the following code:

#include<stdio.h>

void main()
{
    int ar[10],i;
    printf("Enter 10 numbers:");
    for(i=0;i<10;i++)
        scanf("%d",&ar[i]);
    for(i=0;i<10;i++)
        printf("%d",ar[i]);
}

When I execute this and give the following input:

1 2 3 4 5 6 7 8 9 10 11 12

I have given 12 inputs but the loop was supposed to run for only 10 times (scanf loop). I can give even more inputs and it is happy to take it unless I hit enter key. Is there something about for loop that I'm missing here?

Upvotes: 3

Views: 450

Answers (1)

Crowman
Crowman

Reputation: 25908

Perhaps the following program will help you visualize what's going on:

#include<stdio.h>

int main(void)
{
    int ar[10], br[2], i;
    printf("Enter 12 numbers: ");
    fflush(stdout);

    for( i = 0; i < 10; ++i ) {
        scanf("%d", &ar[i]);
    }

    printf("We've read the first 10, let's print them...\n");

    for( i = 0; i < 10; ++i ) {
        printf("%d ", ar[i]);
    }

    printf("\nNow, let's read the last 2...\n");

    for( i = 0; i < 2; ++i ) {
        scanf("%d", &br[i]);
    }

    printf("We've read the last 2, let's print them...\n");

    for( i = 0; i < 2; ++i ) {
        printf("%d ", br[i]);
    }

    putchar('\n');

    return 0;
}

which outputs:

paul@local:~/Documents/src/sandbox$ ./scanning
Enter 12 numbers: 1 2 3 4 5 6 7 8 9 10 11 12
We've read the first 10, let's print them...
1 2 3 4 5 6 7 8 9 10 
Now, let's read the last 2...
We've read the last 2, let's print them...
11 12 
paul@local:~/Documents/src/sandbox$ 

As you'll see, after reading the first ten, the last two numbers are still in the input buffer, and we can read them in a separate loop without actually asking for any more input. In this case, all the inputting is done after the end of the first call to scanf(). The program can just continue to read whatever's in the input buffer without the user ever having to hit another key.

What happened with your program is that you just returned from main() and quit without ever attempting to read those last two numbers you input. This example program shows that they're still in there, available to be read, however.

If you run the example program but you enter less than 12 numbers, then at some point the input is going to run out, and scanf() is going to stop and wait for you to enter some more before continuing.

Upvotes: 1

Related Questions