Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Loop not exiting
Index -> Programming, C -> C Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Fasih




PostPosted: 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]);
    }
    }
}
Sponsor
Sponsor
Sponsor
sponsor
Insectoid




PostPosted: 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.
Fasih




PostPosted: 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?
Tony




PostPosted: 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.
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
Fasih




PostPosted: 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.
Tony




PostPosted: Tue Oct 04, 2011 10:07 pm   Post subject: RE:Loop not exiting

Guess what happens when I enter 101st number in Wink
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
Display posts from previous:   
   Index -> Programming, C -> C Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 6 Posts ]
Jump to:   


Style:  
Search: