0

My problem: Input the string1 and split string1 into string a containing even number and string b containing odd number.

ex: array: 4 3 1 2 6 8

array a: 2 4 6 8 array b: 1 3

when i ran this code, it had problem. Can you help me find the mistakes?

#include<stdio.h>
#include<conio.h>
#include<string.h>

void problem(int a[100], int n);
void bubblesort(int a[100], int n);
void print_array(int a[100], int n);

int main()
{
    int b[100],c[100],evenlen=0,oddlen=0,a[100], n;
    printf("Input n: "); scanf_s("%d", &n);
    printf("Input array: ");
    for (int i = 0; i < n; i++)
    {
        scanf_s("%d", &a[i]);
    }
    for (int i = 0; i < n; i++)
    {
        if ((a[i] % 2) == 0)
        {
            a[i] = b[evenlen];
            evenlen++;
        }
        else
        {
            a[i] = c[oddlen];
            oddlen++;
        }
    }
    bubblesort(b, evenlen);
    bubblesort(c, oddlen);
    printf("The even array : "); print_array(b, evenlen);
    printf("\nThe odd array : "); print_array(c, oddlen);
    _getch();
    return 0;
}

void bubblesort(int a[100], int n)
{
    int hold;
    for (int pass = 0; pass < n;pass++)
        for (int i = 0; i < n - 1; i++)
        {
        if (a[i]>a[i + 1])
          {
           hold = a[i];
           a[i] = a[i + 1];
           a[i + 1] = hold;
          }
        }
}

void print_array(int a[100], int n)
{
    for (int i = 0; i < n; i++)
        printf("%d ", a[i]);
}
2
  • 1
    when i ran this code, it had problem...what problem? Commented Apr 17, 2015 at 7:37
  • looks that bubblesort() does not sort your array. Google for bubble sort algorithm. Commented Apr 17, 2015 at 7:38

2 Answers 2

6

This loop is troublesome:

for (int i = 0; i < n; i++)
{
    if ((a[i] % 2) == 0)
    {
        a[i] = b[evenlen];
        evenlen++;
    }
    else
    {
        a[i] = c[oddlen];
        oddlen++;
    }
}

It's troublesome because you assign to the entries in the a array from the (uninitialized) b and c arrays.

Because the b and c arrays are not initialized their contents is indeterminate and reading from them leads to undefined behavior.

I think you meant to do the opposite assignments, assign to the b and c arrays from a.

Sign up to request clarification or add additional context in comments.

Comments

2

you are doing assigning in wrong way

change this line

a[i] = b[evenlen]; // wrong line

to

b[evenlen] = a[i] ;  

And

a[i] = c[oddlen];   // wrong line

To

c[oddlen] = a[i];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.