Runtime Error(SIGSEGV) plz help below my code

#include<stdio.h>

int main()
{
    int i=0,j[5],k=0;
    while(i!=5)
    {
              scanf("\n%d",&j[i]);   
              i++;  
    }
    while(j[k]!=42)
    {
                   printf("\n%d",j[k]);
                   k++;
    }
    
    return 0;
}

who said only 5 inputs…there can be many inputs…u need to stop taking input and stop giving output as soon as u encounter “42”…u r getting a RE as there may be a case such that the 1st five numbers dont contain a 42…in such a case your second while loop will run for a long long time and in the mean while it will access some memory that is not allocated as value of “k” will rise indefinitely…which will give segmentation fault…i.e. SIGSEGV…hope this helps…:slight_smile:

1 Like

As @kunal361 said, the number of inputs is defined by the user. You have predefined them in your program. Use the following code for reference. I will try to explain it step by step:-

#include <iostream>
using namespace std;
int main(){
    int userInput; //declaring a variable to hold user input
    scanf("%d",&userInput);
    while(userInput!=42){ //looping condition
        cout<<userInput<<"\n"; //displaying the user input
        cin>>userInput; //taking input from the user again as the number entered is not 42    
    }
    return 0; //end
}

Your runtime error was caused as you already defined the number of inputs to be taken. Try to read the problem statement carefully before you start coding it. Also try and understand what is expected and what is not expected of you. Most of the time, one thinks a lot over things that are unnecessary. Hopefully you understand! :slight_smile:

1 Like