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 <stdio.h>
int main(void)
{
int i=0,j,a[9];
while(a[i]!= 42)
{
++i;
scanf("%d",&a[i]);
}
for(j=0;j<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 <stdio.h>
int main(void)
{
int i=0,j,a[9];
scanf("%d",&a[i]);
printf("%d\n",a[i]);
while(a[i]!=42)
{
++i;
scanf("%d",&a[i]);
if(a[i]!=42)
printf("%d\n",a[i]);
}
}
Third one (it was correct):
#include <stdio.h>
int main(void)
{
int i = 0;
while (scanf("%d\n", &i) > 0 && 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).