0

Can anyone explain why my code doesn't work?

The inserted code is my attempt to solve the Code Coach problem "That's Odd...". I wrote my code in C. When I try to filter the even numbers from the odd numbers, and store them in an array, the array starts getting some weirds values. I would much appreciate it if some could fix my code and tell me why my program is behaving this way. To run the code: Copy the code, insert it into the Code Coach "That's Odd..." Problem and run to get the inputs. Thank you! https://code.sololearn.com/cGXoMv2CYlBX/?ref=app

1st Sep 2023, 1:59 PM
Mohammed Amin Elm
Mohammed Amin Elm - avatar
1 Respuesta
+ 5
// JaScript modifications ######################### #include <stdio.h> int main() { // Get the first given number and store in 'length'; // This number is denotes the length of the list. int length; int x; // ################### scanf("%d", &length); // Creating the list with the name 'num' int num[length]; // Getting input values and storing them in 'num'. for(int i=0; i<length; i++) { // ############################ scanf("%d", &x); num[i] = x; } // This code SHOULD filter out all the even numbers and store them in 'even'. int even[20]; int p = 0; for(int i=0; i<length; i++) { if(num[i] % 2 == 0) { even[p] = num[i]; p++; } } // DEBUG: prints the values of 'even'. for(int i=0; i<p; i++) { // ##################### printf("%d\n", even[i]); } // In the end, the program loops through the 'even' list and calculates the sum. Then it prints the sum. /* unsigned int sum = 0; for(int i=0; i<20; i++) { sum += even[i]; } printf("%d", sum); */ return 0; }
1st Sep 2023, 2:18 PM
JaScript
JaScript - avatar