题目
本关的编程任务是补全右侧代码片段中Begin至End中间的代码,具体要求如下:
定义一个数组中的数组
该数组具有2行3列
当代码初始化数组之后,打印第2行2列的值
任务描述
定义一个数组的数组,且能够任意访问该数组中的值。程序能够完整运行。
测试要求
平台将编译用户补全后代码,并根据程序的输出判断程序是否正确。
以下是测试样例:
测试输入:
预期输出:
数组a第二行第二列的值:1
知识点
数组
数组在访问之前需要初始化。
数组的初始化有两种方式。
第一种直接指定数组,使用,分割元素值,例如
int[] myArray = {1, 4, 6, 2};
//其中,myArray有4个元素,皆是整数。
第二种方式使用new显式地初始化,并用一个常量4定义其大小,4也可为变量,这种方式会给数组赋予同一个默认值0:
int[] myArray = new int[4];
//等同于 int[] myArray = {0, 0, 0, 0};
也可以使用两种方式的组合形式,但数组大小必须和元素个数相匹配:
int[] myArray = new int[4]{1, 4, 6, 2};
使用变量定义数组的时候,变量需要const关键字限定,const限定变量为一个常量。例如:
const int arraySize = 4;
int[] myArray = new int[arraySize];
上面定义的数组为一维数组,除了一维数组,还有多维数组,使用二维数组作为实例,例如:
int[,] my2Array = new int[2,3];
//或是使用嵌套的花括号
//int[,] my2Array = {{1, 55, 66}, {1, 33, 42}}
获取数组的长度
数组的length属性用于记录数组中有多少个元素或存储单元,即记录数组的长度是多少。
int[] nums = new int[10];//声明一个int型数组并动态初始化其大小为10
Console.WriteLine(nums.length);//显示当前数组的大小
输出:10
遍历数组
通俗的理解,遍历数组就是:把数组中的元素都看一遍。
示例如下:
int[] arr = {1,3,5,7,9};
for(int i = 0 ; i<arr.length; i++){
Console.Write(arr[i] + ",");
}
输出:1,3,5,7,9
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C2
{
class Program
{
static void Main(string[] args)
{
/********** Begin *********/
//Define an array of arrays: a
int[,] a = new int[2, 3];
/********** End *********/
//Initialize the array
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
a[i,j] = i * j;
}
}
/********** Begin *********/
//Print the second row of column 2 of array a
Console.WriteLine("数组a第二行第二列的值:"+a[1,1]);
Console.ReadKey();
/********** End *********/
}
}
}
题目链接
链接: C# 不一样的数组 .