Reputation: 145
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.
Upvotes: 1
Views: 1362
Reputation: 907
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.
Upvotes: 1
Reputation: 224342
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]);
}
Upvotes: 6