SPOJ problem: Life, the Universe, and Everything Your program is to use the brute-force approach in order to find the answer to Life, the Universe, and Everything. More precisely, rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.


I was solving this problem and I submitted 3 solutions and I got "SEGMENTATION FAULT" for the first 2. The third one finally executed successfully, but I wanted to know where I made a mistake while solving.

1st I submitted:

#include &lt;stdio.h&gt;
  int main(void) 
    {
      int i=0,j,a[9];

      while(a[i]!= 42)
       {
         ++i;
         scanf("%d",&amp;a[i]);
       }
     for(j=0;j&lt;i;j++)
     {
      printf("%d",a[j]);
       printf("\n");
      }
    return 0;
  }


2nd I submitted (after reading a comment that output has to be printed immediately after taking the input):

#include &lt;stdio.h&gt;
int main(void) 
 {
  int i=0,j,a[9];

 scanf("%d",&amp;a[i]);
 printf("%d\n",a[i]);

 while(a[i]!=42)
  {
   ++i;
   scanf("%d",&amp;a[i]);
   if(a[i]!=42)
    printf("%d\n",a[i]);
  }
}


Third one (it was correct):

 #include &lt;stdio.h&gt;

  int main(void) 
  {
   int i = 0;
   while (scanf("%d\n", &amp;i) &gt; 0 &amp;&amp; i != 42) 
   {
    printf("%d\n", i);
   }
    return 0;
   }


Can anyone point where my approach has gone wrong? When I executed the first 2 on www.ideone.com they both ran successfully over there but on SPOJ there was a runtime error (segmentation fault).
The working solution is quite good, actually. You check the return value of scanf(), and you use the while loop condition smartly to say exactly what you mean to accomplish.  The only thing wrong with it is the indentation.

Here is one reasonable way to format it.

#include &lt;stdio.h&gt;

int main(void)
{
    int i = 0;
    while (scanf("%d\n", &amp;i) &gt; 0 &amp;&amp; i != 42) 
    {
        printf("%d\n", i);
    }
    return 0;
}


The initialization of i to 0 and return 0 are actually not needed, but I don't have a problem with making them explicit.

As for your failed attempts, they fail because they attempt to store all of their input, which isn't necessary to do. When there are more than 9 inputs, the buffer overflows.