I'm doing an exercise in C, but I don't know why as first result I have always -1 (that is impossible). I have -1 only after the swap to ordinate the array.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
main(){
int vet[100], cont[100];
int i, c, f=100;
int swap;
int r=0;
int search;
srand(time(NULL));
for(i=0;i<100;i++){
vet[i]=rand()%100+1;
}
while(r==0){
r=1;
for(i=0;i<100;i++){
if(vet[i]>vet[i+1]){
swap=vet[i+1];
vet[i+1]=vet[i];
vet[i]=swap;
r=0;
}
}
}
for(i=0;i<100;i++){
printf("%d) %d\n", i+1, vet[i]);
}
i=0;
r=0;
printf("Inserisci numero da ricercare (1-10000) -> ");
scanf("%d", &search);
if(search>10000 || search<0){
printf("Hai inserito un valore non valido\n");
}
else{
c=(i+f)/2;
while(vet[c]!=search && i<f){
if(vet[c]<search){
i=c+1;
c=(i+f)/2;
}
else if(vet[c]>search){
f=c-1;
c=(i+f)/2;
}
if(vet[c]==search){
cont[r]=c+1;
r++;
}
}
if(vet[c]!=search){
printf("Non e\' stato trovato nessun valore %d", search◆
}
else{
for(i=0;i<r;i++){
printf("%d\n", cont[i]);
}
}
}
}
Now I must use srand(time(NULL))
I know that there are better solutions.
The exercise isn't complete, now I' m trying to solve this error, someone can help me?
EDIT: I'm using OPENVMS to compile, link and run
Your problem is probably here:
for(i=0;i<100;i++){
if(vet[i]>vet[i+1]){
When i=99
, and you access vet[i+1]
, you are off the end of the array. This element is not defined, and it's probably just fluke that you don't get any worse behaviour.
EDIT: So the solution is to change in
for(i=0;i<99;i++){
if(vet[i]>vet[i+1]){