Read elements from keyboard until a negative value! Insert those elements into an array such that the array is always sorted.
I added the code and its outcome. I have a zero on the first position always, and I wanna get rid of it!
#include <stdio.h>
#include <stdlib.h>
int a[100], nr_elem=0;
void InsertInAscendingOrder(int x){
int i;
int pos;
for(i=0; i<nr_elem; i++){
if(a[i]>x){
pos = i;
break;
}
else{
a[nr_elem] = x;
}
}
for(int k=nr_elem; k>=pos; k--){
a[k] = a[k-1];
}
a[pos] = x;
nr_elem++;
}
void printArray(){
for(int i=0; i<nr_elem; i++){
printf("%d ", a[i]);
}
}
int main()
{
int x;
do{
InsertInAscendingOrder(x);
printf("x=");
scanf("%d", &x);
}while(x>0);
printArray();
return 0;
}
Output:
x=10
x=13
x=4
x=90
x=5
x=17
x=-1
0 4 5 10 13 17 90
There are a few issues with your code. Notably, you're inserting
xbefore it's initialized on the first loop iteration, and potentially on subsequent iterations because you haven't verified thatscanfsucceeded.As a good practice, let's get rid of the
100megic number and use a constant. We'll also check the return value ofscanf. And we'll make sure the while loop can't overflow the array.In
InsertInAscendingOrderwe can handle the special case of the first insertion by just inserting the value at index0and incrementingnr_elem.Otherwise we'll look for the index where the first value larger than
xresides, then usememmoveto shift every other element before assigning to that index.As a demonstration:
As noted in comments, the above still exhibits two notable problems.
On erroneous input, the erroneous input will stay in the buffer to be read endlessly and continue resulting in errors. This can be resolved by using
fgetsto read a line of input and then attempt to usesscanfto read an int from it.Secondly, you should try to avoid using global variables. Instead pass state to and from functions via arguments and return values. I have continued using them here because I felt it would be too much change and distract from the issues I have addressed.
It may help to bundle related pieces of data into a struct. E.g.
For an idea of how an even more flexible struct (that allows for varying capacities) might look in a complete program, see below. Not a single global variable in sight.