I first wrote this: (which works as expected)
#include<iostream>
using namespace std;
int main() {
int a[5],cpy[5],ctr = 0;
for (int i = 0 ; i<5 ; i++) {
cout<<"Enter Value for index "<<i<<": ";
cin>>a[i];
}
for (int i = 0 ; i<5 ; i++)
if (a[i]%2==0) {
cpy[ctr]=a[i];
ctr++;
}
for (int i = 0 ; i<5 ; i++)
if (a[i]%2!=0) {
cpy[ctr]=a[i];
ctr++;
}
for (int i = 0 ; i<5 ; i++)
cout<<cpy[i]<<" ";
return 0;
}
Wanted to make it more condensed/cleaner by improving my logic, this is what I came up with:
#include<iostream>
using namespace std;
int main() {
int a[5],cpy[5],ctr = 0;
for (int i = 0 ; i<5 ; i++) {
cout<<"Enter Value for index "<<i<<": ";
cin>>a[i];
}
for (int i = 0 ; i<5 && a[i]%2==0 ; i++,ctr++)
cpy[ctr]=a[i];
for (int i = 0 ; i<5 && a[i]%2!=0 ; i++,ctr++)
cpy[ctr]=a[i];
for (int i = 0 ; i<5 ; i++)
cout<<cpy[i]<<" ";
return 0;
}
Expected Result:
Enter Value for index 0: 1
Enter Value for index 1: 2
Enter Value for index 2: 3
Enter Value for index 3: 4
Enter Value for index 4: 5
2 4 1 3 5
What i get after running 2nd version:
Enter Value for index 0: 1
Enter Value for index 1: 2
Enter Value for index 2: 3
Enter Value for index 3: 4
Enter Value for index 4: 5
1 0 24 0 0
Can you suggest where I am wrong in the 2nd block of code. The first block works correctly.