Home > Software design >  I didn't know why my array is displaying wrong numbers. Just want to know why is that so?
I didn't know why my array is displaying wrong numbers. Just want to know why is that so?

Time:11-15

Didn't know why my odd array is displaying some large number. I want to print only the odd numbers from the array in a sorted manner.
Like if the array is 1 4 6 8 0 9
Print only 1 9
selectionSort() is just the function that sorts the array.

int main()
{
    int T, n, p, size,sum=0,si=0;
    cin >> T;
    for (int i = 0; i < T; i  )
    {
        cin >> n;
        int a[n];
        int odd[n];
        for (int j = 0; j < n; j  )
        {
            cin >> a[j];
        }
        for (int j = 0; j < n; j  )
        {
            p = 0;
            if (a[j] % 2 != 0){
                odd[p  ] = a[j];
                si  ;
            }
        }
        selectionSort(odd, si);

What is wrong here in for loop?

    for (int k = 0; k < si; k  )
    {
        cout << odd[k] << endl;
        // sum  = odd[j];
    }

        // cout << sum << endl;
        sum = 0;
        si=0;
    }
    return 0;
}
Output is :
1
4
1 5 7 9
9
16
4200276
6422112
Expecting 
1
4
1 5 7 9
1
5
7
9

CodePudding user response:

This loop:

    for (int j = 0; j < n; j  )
    {
        p = 0;
        if (a[j] % 2 != 0){
            odd[p  ] = a[j];
            si  ;
        }
    }

Only ever assigns to odd[0]. You conditionally increment p, but then always set it to 0 again.

Since your code expects si to match the count of valid entries in odd, your code can be simplified to:

    for (int j = 0; j < n; j  )
    {
        if (a[j] % 2 != 0){
            odd[si  ] = a[j];
        }
    }

CodePudding user response:

p=0 is not necessary in the for loop. odd[p ] = a[j] equation always mean odd[0]=a[j]. Put p=0 out of the for loop.

CodePudding user response:

You are declaring an array with a variable, which shouln't be allowed but I don't know which compiler you are using so I won't go too deep onto that.

You've never initialized the odd array, the values inside of it are undefined

  •  Tags:  
  • c
  • Related