c If odd, fill from the front of the array; if even, fill from the back

Asked 2 weeks ago, Updated 2 weeks ago, 2 views

int main(void)
{
    int temp[10];
    int arr[10];
    int a = 0, b = 0;
    for (int i = 0; i < 10; i++)
    {
        scanf("%d", &arr[i]);
        temp[i] = arr[i];
    }
    for (int i = 0; i < 10; i++)
    {
        if (arr[i] % 2 == 0)
        {
            arr[9-a] = temp[i];
            a++;
        }
        else
        {
            arr[b] = temp[i];
            b++;
        }
    }
    for (int i = 0; i < 10; i++)
        printf("%d ", arr[i]);
    return 0;
}

It is coded so that if the number entered is odd, it is filled from the front of the array and if it is even, it is filled from the back, but the result is different.

I have no idea what the problem is.

c

2022-09-20 15:00

1 Answers

#include <stdio.h>

int main(void)
{
    int temp[10];
    intarr[10]; // Think of this as just putting the results
    int a = 0, b = 0;
    for (int i = 0; i < 10; i++)
    {
        scanf("%d", &temp[i]);
//        //        temp[i] = arr[i];
    }
    for (int i = 0; i < 10; i++)
    {
//        If (arr[i]%2 == 0) // This is where the result is put, but when this is branched, the changed value is reflected.
        if (temp[i] % 2 == 0)
        {
            arr[9-a] = temp[i];
            a++;
        }
        else
        {
            arr[b] = temp[i];
            b++;
        }
    }
    for (int i = 0; i < 10; i++)
        printf("%d ", arr[i]);
    return 0

/* 
Existing Code Results
13
14
15
16
17
18
19
20
21
22
13 15 17 19 22 21 20 18 16 14

After the change
13
14
15
16
17
18
19
20
21
22
13 15 17 19 21 22 20 18 16 14
*/


2022-09-20 15:00

If you have any answers or tips


© 2022 pinfo. All rights reserved.