Help with C code

Asked

Viewed 55 times

-3

In the code below the intention was to create a vector with 10 spaces, then receive 10 values typed by the user, check if the values are equal or less than 0 and assign the value 1 in these cases, but I did something wrong that he does this procedure only with the first number inserted, the rest remains, I imagine the loop is wrong, but I didn’t understand how to fix...

inserir a descrição da imagem aqui

  • Your third is (impression of the resulting vector) is within the second when it should be after the end of the second (test and replace all negatives).

  • Also remembering that if your array has size 10, the indices of this array will be between 0 and 9, not between 0 and 10 as in your code. Allocating a value at position 10 may not generate an immediate error, but you will be allocating a value in a memory space that does not belong to the array, and may even overwrite a value being used by another part of the program.

1 answer

1

As already said in other comments you are missing in the famous "off-by-one", IE, you are accessing a position outside of your array.

When we declare arrays, what is placed between brackets is the size of the array, not the final index you want. That is to say:

int numeros[10];

Creates the array called numeros that can store only 10 ints, so the indexes range from 0 to 9.

Their laços for iteram from 0 to 10, then you are accessing 11 positions and not 10 and therefore accessing a position outside the array.

Now the second part of the error is due to how you are trying to apply the proposed algorithm and this subdivides into 2 errors:

  1. According to the proposed algorithm, you need to go through the array once to change the values that are <= 0 and another for out of that to then print the result, but you did 2 laços for nested...
  2. Besides having the 2 laços for aninhados, you used the same control variable in 2. Then when the second is over, i has value 11 then when the first goes will check if i <= 10, as i is 11 he does not perform.

Arranging the code to assign the 1 correctly and without extrapolating the limit of the array is like this:

for( i = 0; i < 10; ++i )
{
    if( X[i] <= 0 )
    {
        X[i] = 1;
    }
}

Now just do the laço for of impression after that laço for fully execute.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.