#Trying to code this (from a C tutorial), don't know why output is unexpected.

10 messages · Page 1 of 1 (latest)

ebon laurel
#

Tried to write this three different ways (this one happens to use modulus remainder) why are the 2nd set of ternaries resulting in unexpected output?

#include <stdio.h>

int main() {
    int input1, input2, input3;
    
    printf("Input three integers:");
    scanf("%d", &input1);
    scanf("%d", &input2);
    scanf("%d", &input3);

    int sumEven;
    int sumOdd;

    sumOdd += input1 % 2 == 1 ? input1:0;
    sumOdd += input2 % 2 == 1 ? input2:0;
    sumOdd += input3 % 2 == 1? input3:0;

    sumEven += (input1 % 2 == 0) ? input1:0;
    sumEven += (input2 % 2 == 0) ? input2:0;
    sumEven += (input3 % 2 == 0) ? input3:0;

    printf("Sum of even numbers: %d\n", sumEven);
    printf("Sum of odd numbers: %d", sumOdd);

    return 0;
}

Input: 1 2 3

Expected output:
Even: 2
Odd : 4

Actual output:
Even: 18
Odd: 4

Thanks

drowsy ventureBOT
#

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 run !howto ask.

ebon laurel
#

compiler is MinGW

#

Context: code is meant to grab three inputs, and output sum of even and sum of odd numbers.

vivid light
#

You need to initialize your variables sumEven and sumOdd, probably you want to initialize them to 0 as the default value.
If you don't do that then the variables value is garbage and accessing it is UB (undefined behaviour).

ebon laurel
#

OH

#

c Doesn't have default values? I thought you only needed to initialize constants

vivid light
#

C has some default values, but not like this for local variables

ebon laurel
#

Ah I see, thank you.

drowsy ventureBOT
#

Thank you and let us know if you have any more questions!

This thread is now set to auto-hide after an hour of inactivity