It already has some answers with alternative solutions to the question it intends to solve, but it is always good to understand where we went wrong and what does not serve our goal. This is where my answer focuses.
Starting with the second for
:
for(i=0; i<10; i++){
if(vet[i] == 0){
c++;
}
}
This for
counts the boxes with 0 to be able to discount this amount of the size and show the correct final size, but it is unnecessary to do this in a separate block, since you can do it in the for
that removes zeros. It still doesn’t break the logic.
The problem comes in the for
next:
for(i=0; i<10; i++){
if(vet[i] == 0){
if(vet[i+1] == 0) s=2;
aux=vet[i];
vet[i]=vet[i+s];
vet[i+1]=aux;
s++;
}
}
He has several problems actually. The second condition, the if(vet[i+1] == 0) s=2;
, only allows you to see if you have two zeroes in a row to switch with the element 2 boxes in front. But what if you have 3 ? or 4 ? You can never do it with just one if
Because you don’t know how many zeroes in a row. This would have to be replaced by a loop to find the next element other than 0, or the end if there is no one else. In this loop the s
would always have to start at 1, to leave the house in front where is the zero.
Then the exchange between the two elements was also not correct, the vet[i+1]=aux;
, for use i+1
when you should wear i+s
.
To correct only your second for
can do so:
for(i=0; i<10; i++){
if(vet[i] == 0){
s = 1; //começa sempre em 1
while(i + s < 10 && vet[i+s] == 0){ //com while em vez de if
s++;
}
if (i + s >= 10){ //se não tem mais zeros à frente para trocar termina
break;
}
aux=vet[i];
vet[i]=vet[i+s];
vet[i+s]=aux; //agora i+s
//sem o incremento s++;
}
}
l = 10 - c;
Note that I had to include the l = 10 - c;
for the i
no longer necessarily ends at the end, which makes the old l = i - c;
doesn’t always work properly.
See this change working on ideone
It is important to note that there are better algorithms for this problem, which are not only simpler but more efficient. One of them is what is in response posed by alandplm. I just showed you how to correct the logic you wrote to do the intended.
good solution, easy to understand
– zentrunix