如何使用FOR循环打印一维数组元素

时间:2019-06-02 16:09:35

标签: c#

我正在设计一个FOR循环,以显示一维数组中的元素。

我的任务是使用FOR循环。不是foreach循环。我尝试过将foreach循环嵌套在for循环中,反之亦然...无济于事。另外,我还需要在for循环结构中使用GetUpperBound()方法。

        int Upper = Tally.GetUpperBound(0);
        int Lower = Tally.GetLowerBound(0);

        int RollNumber = 1;


        Console.WriteLine("Roll\t\tCount\t\t");

        for (int Count = 0; Count <= Upper; ++Count)
        {
            if (RollNumber < 13)
            {
                ++RollNumber;
            }
            Console.WriteLine("{0}\t\t{1}\t\t", RollNumber, /* what goes here */ );
        }

我想知道1)我尝试做的事情是否可能,以及2)如何使用一个WriteLine语句从本质上递增地列出数组元素中包含的整数...我是新手,是否有人可以帮助指出正确的方向,将不胜感激。或者,如果您需要任何其他信息来帮助我做我想做的事,那就告诉我。

2 个答案:

答案 0 :(得分:1)

根据Tally的使用情况,我认为GetLowerBound()是您的数组。我仍然不确定您当前正在做什么,但是如果您要打印一维数组的元素,这是您的解决方案:

var array = new int[10]; // Tally in your case

for (int i = 0; i < array.Length; i++)
{
    Console.WriteLine($"{i + 1}: {array[i]}"); // Print "[line number]: [element]".
    // Console.WriteLine(array[i]); // Print element only.
}

如果您绝对需要使用GetLowerBound()GetUpperBound()(这是一维数组的绝对开销,根本不需要):

var array = new int[10];

var lowerBound = array.GetLowerBound(0);
var upperBound = array.GetUpperBound(0);

for (int i = lowerBound; i <= upperBound; i++)
{
    Console.WriteLine($"{i + 1}: {array[i]}"); // Print "[line number]: [element]".
    // Console.WriteLine(array[i]); // Print element only.
}

在两种解决方案中,元素的打印:

Console.WriteLine($"{i + 1}: {array[i]}");

取决于它们的类型。对于数字和字符串之类的简单类型(如您的情况),这就足够了。如果包含的项目是对象,则必须自定义此项目,因为当前它仅使用默认的.ToString()方法并打印对象类型。

Console.WriteLine($"{i + 1}: {array[i]}");

等效于:

Console.WriteLine((i + 1) + ": " + array[i]);

Console.WriteLine(string.Format("{0}: {1}", i + 1, array[i]));

或简单地:

Console.WriteLine("{0}: {1}", i + 1, array[i]);

此外,请尽量不要在PascalCase中命名您的变量,换句话说,不要以大写字母开头。这是为其他目的保留的(例如属性,方法,类等,但这在您的时间范围之外)。使用camelCase


最后,为了解决您的问题,您可以抛弃RollNumber变量,并利用Count来将其用作遍历数组的索引以及当前数组的指针。元素(或行号)。

int Upper = Tally.GetUpperBound(0); // This is equal to Tally.Length
int Lower = Tally.GetLowerBound(0); // This is equal to 0.

Console.WriteLine("Roll\t\tCount\t\t");

for (int Count = Lower; Count <= Upper; Count++)
{
    Console.WriteLine("{0}\t\t{1}\t\t", Count + 1, Tally[Count]);
}

评论后编辑:

数组是包装元素的结构。所以基本上您有一系列的物品。在数组的上下文中,您可以按索引访问每个单独的元素。重要的是在这里要注意,索引从0开始,而不是从1开始。因此,简而言之:  array[0]将返回数组中的第一项,array[1]将返回第二项..直到array[array.length-1]将返回数组中的最后一项。 您可以使用“ Count”变量作为索引来遍历该集合,因为它的值从Lower(基本上为0)更改,该值对应于数组中的第一项,并依次递增其值直到Upper(array)。长度-1),它对应于数组(或最后一项)中的最高索引。

在这里您可以找到有关Arrays,它们的内部工作原理以及如何对它们执行操作的更多信息。本文是针对C#的,但是数组的上下文及其上的操作对几乎所有编程语言都有效。

答案 1 :(得分:0)

此示例显示如何使用您的要求(使用 for 循环和 GetUpperBound )显示数组的内容

int[] Tally = new int[] { 100, 200, 300, 400 };
for (int i = 0; i <= Tally.GetUpperBound(0); ++i) {
    Console.WriteLine("{0}\t{1}", i, Tally[i]);
}

https://dotnetfiddle.net/Ie2pJz