Today I created a program which have 3 Functions:
sortArray(array,length);
removeDuplicateInArray(array, length);
max = findMax(array, length);
The program works fine but, if I run it more times let say, three times, the output is only one OK, other two is different and i think that somehow has to do with the length of the array in findMax function, because i remove duplicates and the array does not have the same size . I'm not sure if there is the problem.
The program is this:
#include<stdio.h>
void sortArray(int *array, int length){
int i, j, k, temp;
for(i=0;i<length-1;i++){
for(k=0;k<length-i-1;k++){
if(array[k]<array[k+1]){
temp=array[k];
array[k]=array[k+1];
array[k+1]=temp;
}
}
}
for(j=0;j<length;j++){
printf("%d ",array[j]);
}
printf("\n\n");
}
void removeDuplicateInArray(int *array, int length){
int i,j,k;
for (i = 0; i < length; i++) {
for (j = i + 1; j < length;j++) {
if (array[j] == array[i]) {
for (k = j; k < length; k++) {
array[k] = array[k + 1];
}
length--;
}else{
j++;
}
}
}
for (i = 0; i < length; i++) {
printf("%d ", array[i]);
}
printf("\n\n");
}
int findMax(int *array, int length){
int i;
int max = array[0];
for(i=1;i<length;i++){
if(max == array[i]){
continue;
}
if(max<array[i]){
max = array[i];
}
}
return max;
}
int main(void){
int array[] = {-9,-7,-3,-1,9,7,3,1,-8,-6,-4,-10,-2,8,6,4,2,5,-5,-10};
int length = sizeof array / sizeof array[0];
int max;
sortArray(array,length);
removeDuplicateInArray(array, length);
max = findMax(array, length);
printf("Max = %d\n", max);
return 0;
}
and the output is:
michi@michi-laptop:~$ ./program 9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -10
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10
Max = 9
michi@michi-laptop:~$ ./program
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -10
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10
Max = 9
michi@michi-laptop:~$ ./program
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -10
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10
Max = 2034093120
michi@michi-laptop:~$ ./program
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -10
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10
Max = 912874208
michi@michi-laptop:~$ ./program
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -10
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10
Max = 1269451840
michi@michi-laptop:~$ ./program
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -10
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10
Max = 1946221408
michi@michi-laptop:~$ ./program
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -10
9 8 7 6 5 4 3 2 1 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10
Max = 9
The output should be 9, but the output is not always 9