# Thread: Problem(s) with an array!!

1. ## Problem(s) with an array!!

Hi everyone,
Before you read my code, i want to mention that the main function was giving to me, that means that i should create all the functions presented in main.that is what the exercise requires.

No one of the option within the choice_operation function is done correctly, I mean, it list huge numbers like 418033 or something.
Code:
```#include <stdio.h>
#include <stdlib.h>
#define SIZE 3
void sort_array(int []);
int search(int, int[]);
void choice_operation(int []);
int main(){
int ar[SIZE];			//array declaration (SIZE is constant)
sort_array(ar);		//sort the array
choice_operation(ar);	//display a list of operations
system("PAUSE");
return 0;
}
for (int i = 0 ; i < SIZE ; i++)
scanf("%d",&x[i]);
}
void sort_array(int x[]){
int index,i,j;
for (i = 1 ; i < SIZE ; i++){
x[i] = index;
for(j = i - 1 ; j < 0 ; j--){
if (x[j] > x[i])
x[j+1] = x[j];
}
x[j] = index;
}
}
int search (int v,int x[]){
for (int i = 0 ; i < SIZE ; i++){
if (x[i] == v)
return(i);
}
return(-1);
}
void choice_operation(int x[]){
int y,sum = 0,a = 0,v;
printf("To display the max and the min of the array, enter 1\n");
printf("To know a position of a value, Enter 2\n");
printf("To find the average, Enter 3\n");
printf("To list the elements of the array, Enter 4\n");
printf("To exit, Enter any other character.\n");
scanf("%d",&y);
switch(y){
case 1:
printf("the max is %d, and the min is %d\n",x[0],x[SIZE-1]);
break;
case 2:
printf("Enter a value to know its position within the array:\n");
scanf("%d",&v);
a = search(v,x);
if(a != -1)
printf("the positions of %d is %d\n",v,a);
else
printf("this element does not belong to the array\n");
break;
case 3:
for (int i = 0 ; i < SIZE ; i++)
sum += x[i];
printf("The average is %d\n",(sum / SIZE));
break;
case 4:
for(int i = 0 ; i < SIZE ; i++)
printf("%d\n",x[i]);
break;
default:
printf("The program ends.\n");

}

}```

2. You never specified a question.
Also beware in your sort_array function - j is -1 when the loop ends, so you access out-of-bounds.

3. Your sort function doesn't ever happen -- j is never <0, so the for loop skips. You want to go while j >= 0 perhaps. Also, everything gets set to the uninitialized value of index.

All in all, you should rework sort.

4. Ok, but this is all happening because actually i didn't get the insertion sorting..can anybody help please??

5. Do you know how to do any kind of sorting? Do you know the insertion sort algorithm, if that's what you're trying to use?

6. ya ya I know the bubble sort...this insertion was briefly discussed in class, so i didn't get it..

7. Why don't you use bubblesort then, if you know it? If the answer is "Because the assignment is for insertion sort", then you'll have to go back in time and pay attention/take notes in class this time around. Or, alternatively, read one of the 63854 "introduction to insertion sort" articles on the internet. iMalc has one on his website, for example.