Segmentation Fault (Core Dumped) Print Numbers

0

I wrote an algorithm that prints all integers in a closed range from A to B, with A and B integers. However, when compiling and mounting the file in linux bash, a "segmentation fault" occurred. Can anyone explain 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;
}
    
asked by anonymous 10.11.2016 / 18:37

1 answer

1

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

The return imprimir; also did not make sense. I have corrected you (at least the way I understood the problem). In your statement you said you wanted the closed range between A and B integers, but you were creating a constraint for the non-negative integers in the code. Remember that if exercise should work for integers, it also covers 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 : I 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 more accustomed. : -)

I hope I have been able to understand your problem correctly to help you.

    
10.11.2016 / 19:14