1

I was writing a simple sorting program but scanf() appears to be stuck and keeps taking infinite inputs. I know if I enter an invalid input this will happen. But, even when I enter int this occurs.

Here is the code:

#include <stdio.h>

int main() {
    int arr[5],temp,pos,i=0;
    printf("Enter the elements\n");

    while(i<5){
        scanf("%d ",&arr[i]);
        ++i;
    }

    printf("Sorted Array:");

    for(int i=0;i<4;++i){
        pos = i;
        for(int j=i+1;j<5;++i){
            if(arr[pos]>arr[j])
                pos = j;
        }

        temp = arr[i];
        arr[i] = arr[pos];
        arr[pos] = temp;
    }

    for(int i=0;i<5;++i){
        printf("%d",arr[i]);
    }

    return 0;
}
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
Mukund Madhav
  • 35
  • 1
  • 6

2 Answers2

4

The problem with your code isn't about the scanf(). It is due to improper loops constraints.

for(int i=0;i<4;++i){
       pos = i;
         for(int j=i+1;j<5;++i){
             if(arr[pos]>arr[j])
                pos = j;
        }
         temp = arr[i];
         arr[i] = arr[pos];
        arr[pos] = temp;

    }

The above sorting loop is the reason for your problem. You have to change ++i in inner loop to ++j which will solve your issue.!!

for(int i=0;i<4;++i){
       pos = i;
         for(int j=i+1;j<5;++j){
             if(arr[pos]>arr[j])
                pos = j;
        }
         temp = arr[i];
         arr[i] = arr[pos];
        arr[pos] = temp;

    }

You can correct the code like this.! Hope this helps.!!

Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
0

It seems you had minor typo mistake, changes ++i to ++j in sorting inner loop will solve the problem.

Pankaj
  • 401
  • 1
  • 6
  • 16