Computer Science Canada

Loop not exiting

Author:  Fasih [ Tue Oct 04, 2011 9:01 pm ]
Post subject:  Loop not exiting

So i have a for loop and in the loop I am entering integers into an array of integers. I want it to quit if the integer that was inputted was 0, but it won't exit. If i enter a 0 again it will. Why won't it the first time? :s

code:
#include <stdio.h>
int x=0;
int main()
{
    read();
}
void read()
{
    int x=0,b=1;
    int a[100];
    for (x = 0;x<=100;x++)
    {
       scanf("%d\n",&a[x]);
       if (a[x]==0)break;       
    }
       
    if (a[x]==0){
    int t;
    for (t=x-1;t>=0;t--){
            printf("%d\n",a[t]);
    }
    }
}

Author:  Insectoid [ Tue Oct 04, 2011 9:35 pm ]
Post subject:  RE:Loop not exiting

Look at your scanf. There's something there that shouldn't be.

Author:  Fasih [ Tue Oct 04, 2011 9:53 pm ]
Post subject:  RE:Loop not exiting

Isn't it supposed to be %d and the & before the variable?

Author:  Tony [ Tue Oct 04, 2011 9:54 pm ]
Post subject:  RE:Loop not exiting

Also, you can read in more data than your buffer has space for.

Author:  Fasih [ Tue Oct 04, 2011 9:56 pm ]
Post subject:  Re: RE:Loop not exiting

Tony @ Tue Oct 04, 2011 9:54 pm wrote:
Also, you can read in more data than your buffer has space for.

Yeah but I just chose 100, even though I'm expecting much less.

Ohhh the \n

My prof always puts it in so I did... wow.

Author:  Tony [ Tue Oct 04, 2011 10:07 pm ]
Post subject:  RE:Loop not exiting

Guess what happens when I enter 101st number in Wink


: