A
A
Artyom2022-01-25 21:06:10
C++ / C#
Artyom, 2022-01-25 21:06:10

How to form an array from those positive elements of the original array, which are arranged in ascending order?

There is a problem in my code:

The code
Console.Write("Введите n: ");
            int n = Convert.ToInt32(Console.ReadLine());

            int[] a = new int[n];

            int[] b = new int[n];

            Console.WriteLine("\nВведите элементы массива: ");
            for (int i = 0; i < n; i++) a[i] = Convert.ToInt32(Console.ReadLine());

            int s = 0;
            for (int i = 0; i < n - 1; i++)
            {
                if (a[i] > 0 && a[i] < a[i + 1] && a[i + 1] > 0)
                {
                    b[s] = a[i];

                    b[s + 1] = a[i + 1];
                    
                    s++;
                }
            }

            Array.Resize(ref b, s + 1);

            Console.WriteLine("\nМассив из положительных элементов, которые расположен в порядке возрастания: ");
            Console.WriteLine(string.Join(" ", b));


I give input: -1 -2 3 4 -5 -6 9 10
In theory, I should get: 3 4 9 10

But at the output: 3 9 10, the four disappears somewhere

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Myclass, 2022-01-26
@shindayoni

some strange formula a[i] > 0 && a[i] < a[i + 1] && a[i + 1] > 0,
for number 3 all conditions are met, but for number 4 - no. Tk. track. after it is the number -5 and the condition a[i + 1] > 0 - those is not fulfilled for it. the condition is not suitable for the expected result.
Here is another option. Positive knowledge is always inserted into the second array, but the counter for the next value is incremented only when the "left less than right" conditions are met. Otherwise, count remains in place and at the next. If the number is positive, the array element is overwritten with the new value.
well somewhere like this:

int s = 0;
            for (int i = 0; i < n; i++)
            {
                if (a[i] > 0)
                {
                    b[s] = a[i];
                  	if ( (s==0) || (s > 0 && b[s-1] < b[s]) )
                    {
                      s++;
                    }
                }
            }

don't forget that the last element in the b array is not part of the correct answer. Elements of b with index less than

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question