Suppose we are given an array a[10] such that it contains both even and odd numbers. We have to move the even elements to another array say b[10] and odd elements(numbers) to array c[10]. the numbers in array are to be entered by the user which means we do not know the exact number of even and odd elements present in a. Let us assume that there are 5 even numbers and 5 odd numbers but the size of array b and c is 10. what should we do so that they don''t print garbage value

Recommended Answers

All 3 Replies

There are (at least) 2 easy approaches.

One is to simply keep a count of how many numbers you add to each array, and do not access the array beyond that limit. You will need such a count anyway when you are populating the b&c arrays so that you know which array element to fill next. Just make sure you retain that count for later.

Another approach is to pre-fill each element of each array with a nonsense value that can never exist in your real data. For example, if you know your data will always be positive numbers you could initially set each array element to -1. Then if you see a -1 in an array element you know that array element has not been used for real data so you can skip it. This approach avoids the need to retain a "used elements" count for each array, but you run the risk that the nonsense value you choose does in fact appear in your valid data.

You have posted this twice. Please DO NOT do that! I answered the question already... :-( If the double posting was in error, then I understand that this happens occasionally (fat fingers on the keyboard), but don't make it a habit.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.