kasa ssg
kasa ssg

Reputation: 9

Can someone help me why my program is printing a random number?

I am learning to code in C and I need to create a program which sorts out numbers in an array by even numbers first and then the uneven. The numbers don't have to be sorted smallest to largest. The first entered numbers is supposed to be the size of the array. I managed to figure it out but one number is always missing and presented with a random number. Am i missing something ?

int a[101], a2[101], i, j, n, k = 0;
scanf ("%d", &n);

for (i = 0; i < n; i++)
scanf ("%d", &a[i]);

for (i = 0; i < n; i++)
{
    if (a[i]%2 == 0)
        {
        if (a[i] == 0)
            {
                a2[k] = a[i];
                k++;
                continue;
            }
        a2[k] = a[i];
        k++;
        }
}


for (i = 0; i < n; i++)
{
    if (a[i]%2 != 0)
    {
        a2[k] = a[i];
        k++;
    }
}


for (i = 0; i < n; i++)
    printf ("%d ", a2[i]);


return 0;

I enter the following numbers:

6

1 3 2 5 8 10

I should get: 2 8 10 1 3 5

What I'm getting: 2 8 10 1 3 508

I tried with other combinations too, problem persists but with different number.

Upvotes: 0

Views: 95

Answers (1)

Niloy Rashid
Niloy Rashid

Reputation: 707

Checked your code several time its written well and worked well too. The extra 08 after 5 may be printed by something else. You can use a newline after printing all the element of ara2 to make sure the 08 is printed form any element of ara2 or not. like this:

for (i = 0; i < n; i++)
    printf ("%d ", a2[i]);
printf("\n");

And one more thing. There are no need to add the bellow portion in your code. The code will work same even if you don't add this.

    if (a[i] == 0)
        {
            a2[k] = a[i];
            k++;
            continue;
        }

Happy Coding.

Upvotes: 1

Related Questions