Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

c - 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:

#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("
");
    return 0;
}
question from:https://stackoverflow.com/questions/65911603/do-we-have-to-create-an-even-and-an-odd-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

O(n) Solution:

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("
");

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

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...