0
Program to sepearate and print even and odd numbers of an N element array in two different lines
What did i do wrong here--- #include <bits/stdc++.h> using namespace std; int main() { int n,i,j,k; cin>>n; int arr[n]; int even[j]; int odd[k]; j=0; k=0; for( i=0; i<n; i++) { cin>>arr[i]; if(arr[i]%2==0) { even[j]=arr[i]; j++; } else { odd[k]=arr[i]; k++; } } for(i=0; i<j;i++) { cout<<even[i]<<" "; } cout<<endl; for(i=0; i<k;i++) { cout<<odd[i]<<" "; } return 0; }
1 Réponse
+ 3
When declaring your integer variables, you leave all of them in an uninitialized state, yet a few lines later you try to initialize arrays with their values. What size do you expect "even" and "odd" to have if both 'j' and 'k' were not initialized?
Since you didn't provide values for them, they will still contain whatever value has been stored in their respective memory space before - a garbage value. If one of them were to equal zero by chance, the declaration would even be ill because arrays with a size of zero are illegal in C++.
You can fix this by initializing both "even" and "odd" with 'n' instead, this will ensure both have at least the necessary size to hold their elements and will make for a working solution.
Although this is not exactly clean C++, since VLA's only work as a compiler extension and are not supported by the standard. For a standard-compliant solution, dymanically allocated arrays or vectors should be preferred.