Segmentation Fault (Dumped Core) Print Numbers

Asked

Viewed 71 times

0

I wrote an algorithm that prints all integers in a closed interval from A to B, with A and B integers. However, when I was compiling and assembling the file on the linux bash, there was a "Segmentation fault". Can anyone explain to me why?

#include <stdio.h>
int imprimir(int a, int b){
int i;
   if(a=b){
return a;
   }else{
 if(a<b){
   for(i=a;i<=b;a++){
     printf("%d",a);
}
   }else{
     for(i=b;i<=a;b++){
        printf("%d",b);  
   }
  }
 }
}

int main(int argc, char*argv[]){
 int a, b;

 printf("Forneca dois numeros quaisquer");
 scanf("%d%d",a,b);
 if(a<0 && b<0){
 printf("Digite um numero inteiro nao negativo");
 scanf("%d %d",a,b);
}

imprimir(a,b);
return imprimir;
}

1 answer

1


Your code contained some errors. An example is the first if. I believe you wanted to make a comparison (==), and not an assignment (=). Another mistake was the lack of & at the time of reading with scanf().

The return imprimir; also made no sense. I fixed it for you (at least the way I understood the problem). In your statement you said you wanted the closed interval between A and B integers, but you were creating a constraint for the nonnegative integers in the code. Remember that if the exercise should work for the integers, it also covers the negative values. The code below works for both positive and negative.

#include <stdio.h>
void imprimir(int a, int b) {
    int menor, maior;
    if (a > b) { menor = b; maior = a; }
    else { menor = a; maior = b; }
    while (menor != maior + 1) {
        printf("%i ", menor);
        menor++;
    }
}

int main(int argc, char*argv[]) {
    int a, b;

    printf("Forneca dois numeros quaisquer: ");
    scanf("%d %d", &a, &b);
    imprimir(a,b);
}

Edited code: just changed the return type of the print function, since it should only print and does not need to return a int. But leave it the way you’re most used to. :-)

I hope I have managed to understand your problem correctly to help you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.