2

I want to make a new array which contains some of elements from the first array which are greater than 5. (n is the size of the first array)

for (i = 1; i <= n; i++)
{
    if (numbers[i] > 5)
    {
        new_array[i] = numbers[i];
        printf("%d ", new_array[i]);
    }
}

If I do it like this it works perfectly and prints a new array with only those elements that are greater than 5. But if I write it like this:

for (i = 1; i <= n; i++)
{
    if (numbers[i] > 5)
    {
        new_array[i] = numbers[i];
    }
}
for (i = 1; i <= n; i++)
{
    printf("%d ", new_array[i]);
}

It doesn't work. It prints an array of n numbers and on the locations where >5 numbers were in the original array there are these numbers but on other locations there are weird numbers. How can I fix this? I want to find the minimum number in the new array and print it.

2 Answers 2

7

You're using the same index into both the old and new array. You need to keep a separate counter for each.

Also, arrays in C are zero based so you should count from 0 to n-1 instead of 1 to n.

int m = 0;
for (i = 0; i < n; i++)
{
    if (numbers[i] > 5)
    {
        new_array[m] = numbers[i];
        m++;
    }
}
for (i = 0; i < m; i++)
{
    printf("%d ", new_array[i]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

OH! you are right!! I didn't pay attention to it. Thank you so much!
I have been trying to fix it for really long time! It's funny there was such a tiny mistake
@OrangeBike Glad I could help. Feel free to accept this answer if you found it useful.
2

This is because the other locations have never been initialized, so could be literally anything.

You can either initialize the array beforehand or keep a separate index for your new array. For instance int j = 0; Then every time you assign to new_array increment j. This way new_array will only have the elements > 5, and you will know how many elements it holds.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.