runtime error

How to resolve the segmentation fault runtime error?
I am getting it again and again despite making changes to my code.
This in reference to the last question of the practice problems.
link:easy Problem - CodeChef

My code is as follows:
int main()
{
int i=0;
int a[10];

for(i=0;i<10;i++)
scanf(“%d”,a[i]);

for(i=0;i<10;i++)
{
while(a[i]!=42)
{
printf(“%d”,a[i]);
printf(“\n”);}}
return 0;
}

The number of inputs for this problem are not 10 as you have assumed but a lot more. My suggestion is you apply a simpler algorithm :

  1. Input number (only 1 variable required)

  2. If 42 break from loop.

  3. Else print the number and start again from step 1.

The advantage of this is you dont need to store all elements in an array. you can compute and print on the fly

Changed the code but again runtime error!

int main()
{
int a,i;
scanf("%d",a);
for(i=0;;i++)
{
if
(a==42)
break;
else
printf("%d \n",a);
}
return 0;
}

Few things : 1) scanf("%d",&a); you missed ‘&’ 2) scanf should be inside the for loop as you need to take input everytime after you print a number

1 Like

oops…!!
thnx for pointing the mistake…

i have one more doubt that when i am writing the code in c++
i am getting the compile error for
1)cin was not declared in this scope
2)cout was not declared in this scope

code is:
int main()
{
int a,i;
for(i=0;;i++)
{
cin>>a;
if (a==42)
break;
else
cout<<a<<"\n";
}
return 0;
}

You havent used appropriate header files. put iostream and write using namespace std; above main.

i had tried with including the header files but it didnt help…!

no.you didnt put iostream header. here is the AC code : CodeChef: Practical coding for everyone

oh…i had used <iostream.h> instead of <iostream that’s why it wasn’t working…!!
but i want to ask why does the code run in C wihtout including header files?