Increasing Array with Rows

2019-08-13 11:25发布

Say I have an an array of numbers:

int[] that = new [] {1, 2, 3, 2, 4, 8, 9, 7};

I'm trying to display them so that the numbers that are increasing have their own line. For example the result would be:

1 2 3

2 4 8 9

7

I'm able to do the first row using,

for (int i = 1; i < that.Length; i++) 
{
    if (that[i-1] < that[i]) 
    {
        Console.Write(that[i-1] + " ");
    }
}

The thing is this works for the first row because 1-3 are increasing but stops after that. I'm not exactly sure how to continue so that 2 4 8 9, then 7 are written.

标签: c# arrays row
4条回答
霸刀☆藐视天下
2楼-- · 2019-08-13 12:05

I have a feeling this is homework so I'm going to leave the actual coding to you. But here's how to do it in plain language:

  1. Have a variable where we store the previous value. Let's call it oldValue, and start it with zero (if you're only using positive numbers in your array).
  2. Go through the array one item at a time.
  3. Check to see if that number is larger than oldValue.
  4. If FALSE, print the new line character. "\n" in C#.
  5. Print that number and make oldValue equal that number.
  6. Unless your numbers are finished get the next number and go to step 3.
查看更多
家丑人穷心不美
3楼-- · 2019-08-13 12:11

You never create a new line.

int[] arr = new[] {1, 2, 3, 2, 4, 8, 9, 7};

for(var i = 0; i < arr.Length; i++){
 if(i == 0 || ((i < arr.Length - 1) && arr[i] < arr[i + 1])){
  Console.Write(arr[i]);
 } else {
  Console.Write("{0}\n", arr[i]);
 } 
}

Output:

123
2489
7

Couple of remarks:

  • Avoid the usage of this as a variable name. It's a reserved keyword.
  • Use \n as a newline character.
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-08-13 12:12
        int[] numbers = new int[] { 1, 2, 3, 2, 4, 8, 9, 7 };

        String orderedNumbers = String.Empty;

        for (int i = 0; i < numbers.Length; i++)
        {
            if (i == 0 || numbers[i] > numbers[i - 1])
            {
                orderedNumbers += numbers[i].ToString();
            }
            else
            {
                orderedNumbers += System.Environment.NewLine + numbers[i].ToString();
            }
        }

        MessageBox.Show(orderedNumbers);
查看更多
\"骚年 ilove
5楼-- · 2019-08-13 12:17

There are a number of ways you can do this, either by appending a string with characters until a lesser one is reached and then using the Console.WriteLine() command to write the entire string at once, or (the easier way given your code) which is to simply test for the new value being lesser than the previous and inserting a newline character into your text.

// Start at zero
for (int i = 0; i < this.Length; i++) 
{
    // If this is not the first element in the array
    //   and the new element is smaller than the previous
    if (i > 0 && this[i] < this[i-1]) 
    {
        // Then insert a new line into the output
        Console.Write(Environment.NewLine);
    }
    Console.Write(this[i] + " ");
}
查看更多
登录 后发表回答