简体   繁体   English

我们是否必须创建一个偶数和一个奇数数组?

[英]Do we have to create an even and an odd array?

How can we modify the following code (which initially asks the user for 10 numbers to be entered, get stored in an array, and printed on the screen) so that the even numbers are printed on the first line, and the odd on the second:我们如何修改以下代码(最初要求用户输入 10 个数字,将其存储在数组中,然后打印在屏幕上),以便在第一行打印偶数,在第二行打印奇数:

#include <stdlib.h>
#include <stdio.h>
int i,j;
int array_1[10];
int main() {
    for(i=0;i<10;i++) {
    printf("Enter a number: ");
        scanf("%d", &array_1[i]);
    }
    printf("The elements of the array are: ");
    for (j=0;j<10;j++) {
        printf("%d ", array_1[j]);
    }
    printf("\n");
    return 0;
}

No need to create a new array.无需创建新数组。 You can just go through it first checking for even numbers, and then again for odd numbers.您可以通过它首先检查偶数,然后再检查奇数,只需 go。 Also, there's no need to declare i and j before using them.此外,在使用 i 和 j 之前无需声明它们。 You can just declare them and initialize them in the for loop:您可以声明它们并在 for 循环中初始化它们:

#include <stdlib.h>
#include <stdio.h>
int array_1[10];
int main() {
    for(int i=0;i<10;i++) {
    printf("Enter a number: ");
        scanf("%d", &array_1[i]);
    }
    printf("The elements of the array are: ");
    
    // Print even numbers
    for (int j=0;j<10;j++) {
        if(array_1[j] % 2 == 0)
            printf("%d ", array_1[j]);
    }
    printf("\n");

    // Print odd numbers
    for (int j=0;j<10;j++) {
        if(array_1[j] % 2 != 0)
            printf("%d ", array_1[j]);
    }
    printf("\n");
    return 0;
}

Edit: As tadman suggested in the comment below, there's a better and cleaner way to do this kind of task.编辑:正如 tadman 在下面的评论中建议的那样,有一种更好、更清洁的方法来完成这种任务。 As you can see in the above example, I'm repeating 4 lines of code where only one character changes.正如您在上面的示例中所看到的,我重复了 4 行代码,其中只有一个字符发生了变化。 This task could be abstracted into a function to reduce code repetition:可以将此任务抽象为 function 以减少代码重复:

void printIfMod(int* arr, size_t array_size, int mod){
    for (int j=0;j<array_size;j++) {
        if(arr[j] % 2 != mod)
            continue;
        printf("%d ", arr[j]);
    }
    printf("\n");

Remember to add a function prototype before main if you place the function after main:如果将 function 放在 main 之后,请记住在 main 之前添加 function 原型:

void printIfMod(int* arr, size_t array_size, int mod);
int main(){...}

Now, to print the numbers, call the method with modulo 0 to get even numbers, and 1 to get odd numbers:现在,要打印数字,调用模 0 得到偶数和 1 得到奇数的方法:

// Print even numbers
void printIfMod(&array_1, 10, 0);

// Print odd numbers
void printIfMod(&array_1, 10, 1);

One last note, hard-coding array_size is not wise, and that goes for all arrays.最后一点,硬编码array_size是不明智的,这适用于所有 arrays。 I recommend using sizeof() to dynamically calculate the size of your array:我建议使用sizeof()动态计算数组的大小:

size_t size = sizeof(array_1) / sizeof(int);
// Print even numbers
void printIfMod(&array_1, size, 0);

// Print odd numbers
void printIfMod(&array_1, size, 1);

O(n) Solution: O(n) 解决方案:

you have to add odd numbers at the back of the array and add the even numbers at the front of the array and keep track of the indexes.您必须在数组的后面添加奇数并在数组的前面添加偶数并跟踪索引。


int array_1[10];

int main() {

    int even = 0, odd = 10;

    for (int i = 0; i < 10; i++) {
        printf("Enter a number: ");
        int inp;
        scanf("%d", &inp);
        if (inp % 2 == 0) {
            array_1[even++] = inp;
        } else {
            array_1[--odd] = inp;
        }
    }

    // even numbers
    for (int i = 0; i < even; i++) {
        printf("%i ", array_1[i]);
    }
    printf("\n");

    // odd numbers
    for (int i = 9; i >= odd; i--) {
        printf("%i ", array_1[i]);
    }
    printf("\n");

    return 0;
}

Since you asked, here is how I would do it.既然你问了,这就是我的做法。 I suspect this may leave you with more questions than answers through.我怀疑这可能会给您留下比答案更多的问题。

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

#define NUMBERS_SIZE 10

typedef bool (*number_validator)(int num);

bool isEven(int num)
{
    return (num & 1) == 0;
}

bool isOdd(int num)
{
    return (num & 1) != 0;
}

void print(const char *title, int *array, int array_size, number_validator isValid)
{
    printf("%s", title);
    bool first = true;
    for (int i = 0; i < array_size; ++i)
    {
        if (isValid(array[i]))
        {
            if (!first)
            {
                printf(", ");
            }
            printf("%d", array[i]);
            first = false;
        }
    }
    printf("\n");
}

int main()
{
    int numbers[NUMBERS_SIZE] = { 0 };

    for (int i = 0; i < NUMBERS_SIZE; i++)
    {
        printf("Enter a number: ");
        scanf("%d", &numbers[i]);
    }

    printf("\n");
    print("Even: ", numbers, NUMBERS_SIZE, isEven);
    print(" Odd: ", numbers, NUMBERS_SIZE, isOdd);

    return 0;
}

Demo on ideone ideone 上的演示

you can try this way.I have used binary AND(&) instead of MOD(%) as it is faster:您可以尝试这种方式。我使用二进制 AND(&) 而不是 MOD(%) 因为它更快:

#include <stdlib.h>
#include <stdio.h>
int i,j;
int array_1[10];

int main()
{
for(i=0; i<10; i++)
{
  printf("Enter a number: ");
  scanf("%d", &array_1[i]);
}

printf("The Even elements of the array are: ");

for (j=0; j<10; j++)
{
    if((array_1[j]&1) == 0)
        printf("%d ", array_1[j]);
}

printf("\nThe Odd elements of the array are: ");

for (j=0; j<10; j++)
{
    if((array_1[j]&1) != 0)
        printf("%d ", array_1[j]);
}

printf("\n");
return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM