#I try to only add Odd numbers , but both even and odd number were added
15 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
@solar plume
Screenshots!
Your message appears to contain screenshots but no code. Please send code and error messages in text instead of screenshots if applicable!
bool isOdd(int num) {
return (num % 2 != 0);
}
void addArrayElement(int input, int arr[], int& arrLength) {
arrLength++;
arr[arrLength - 1] = input;
}
void fillArrayWithOdd(int source[], int target[], int sourceLen, int& targetLen) {
targetLen = 0;
for (int i = 0; i < sourceLen; ++i) {
if (isOdd(source[i])) {
addArrayElement(source[i], target, targetLen);
}
}
}
hello
fillArrayWithOdd will copy odd element from the source to the target
what the problem with this code
this is the output second array should only contains odd number
;compile
bool isOdd(int num) {
return (num % 2 != 0);
}
void addArrayElement(int input, int arr[], int& arrLength) {
arrLength++;
arr[arrLength - 1] = input;
}
void fillArrayWithOdd(int source[], int target[], int sourceLen, int& targetLen) {
targetLen = 0;
for (int i = 0; i < sourceLen; ++i) {
if (isOdd(source[i])) {
addArrayElement(source[i], target, targetLen);
}
}
}
#include <iostream>
int main() {
int a[]{1,2,3,4}, b[4], aL = 4, bL = 0;
fillArrayWithOdd(a, b, aL, bL);
for (int i = 0; i < bL; i++) std::cout << b[i] << ' ';
}
The above code seems to work as expected, so it's likely an issue in the output code (that the numbers are the same is suspect)
Program Output
1 3
eschablowski | 54ms | c++ | x86-64 gcc 14.1 | godbolt.org
