C# 完全学习指南C# 完全学习指南
首页
基础教程
进阶内容
实战项目
编程指南
首页
基础教程
进阶内容
实战项目
编程指南
  • 基础教程

    • 📚 基础教程
    • 第1章 - 认识 C#
    • 第2章 - 环境搭建
    • 第3章 - 第一个程序
    • 第4章 - 变量与数据类型
    • 第5章 - 运算符
    • 第6章 - 控制流程
    • 第7章 - 循环语句
    • 第8章 - 数组
    • 第9章 - 方法
    • 第10章 - 面向对象基础
    • 第11章 - 类与对象
    • 第12章 - 继承
    • 第13章 - 多态
    • 第14章 - 封装
    • 第15章 - 接口

第8章 - 数组

嗨,朋友!我是长安。

如果要存储100个学生的成绩,难道要创建100个变量吗?当然不用!这一章我们要学习数组,批量管理相同类型的数据。

🤔 什么是数组?

数组是一组相同类型数据的集合,就像一排有序的储物柜。

类比:

  • 单个变量:一个盒子
  • 数组:一排编号的盒子(0号、1号、2号...)

🌟 声明和初始化数组

方式1:声明后赋值

// 声明数组
int[] scores;

// 创建数组(指定大小)
scores = new int[5];

// 赋值
scores[0] = 85;
scores[1] = 90;
scores[2] = 78;
scores[3] = 92;
scores[4] = 88;

方式2:声明时初始化

// 完整写法
int[] scores = new int[] { 85, 90, 78, 92, 88 };

// 简化写法(推荐)
int[] scores = { 85, 90, 78, 92, 88 };
string[] names = { "张三", "李四", "王五" };

索引从0开始

数组的索引是从 0 开始的!

  • 第1个元素:array[0]
  • 第2个元素:array[1]
  • 第n个元素:array[n-1]

📖 访问数组元素

int[] scores = { 85, 90, 78, 92, 88 };

// 访问元素
Console.WriteLine(scores[0]);  // 85
Console.WriteLine(scores[2]);  // 78

// 修改元素
scores[0] = 95;
Console.WriteLine(scores[0]);  // 95

// 数组长度
Console.WriteLine($"数组长度:{scores.Length}");  // 5

🔄 遍历数组

方式1:for 循环

int[] scores = { 85, 90, 78, 92, 88 };

for (int i = 0; i < scores.Length; i++)
{
    Console.WriteLine($"scores[{i}] = {scores[i]}");
}

方式2:foreach 循环(推荐)

foreach (int score in scores)
{
    Console.WriteLine(score);
}

选择建议

  • 需要索引:用 for 循环
  • 只遍历值:用 foreach 循环

💡 数组的常用操作

计算数组元素的和

int[] scores = { 85, 90, 78, 92, 88 };
int sum = 0;

foreach (int score in scores)
{
    sum += score;
}

double average = (double)sum / scores.Length;
Console.WriteLine($"总分:{sum}");
Console.WriteLine($"平均分:{average:F2}");

查找最大值和最小值

int[] numbers = { 5, 2, 9, 1, 7, 3 };

int max = numbers[0];
int min = numbers[0];

foreach (int num in numbers)
{
    if (num > max) max = num;
    if (num < min) min = num;
}

Console.WriteLine($"最大值:{max}");  // 9
Console.WriteLine($"最小值:{min}");  // 1

数组排序

int[] numbers = { 5, 2, 9, 1, 7, 3 };

// 升序排序
Array.Sort(numbers);
Console.WriteLine("升序:" + string.Join(", ", numbers));
// 输出:1, 2, 3, 5, 7, 9

// 降序排序
Array.Reverse(numbers);
Console.WriteLine("降序:" + string.Join(", ", numbers));
// 输出:9, 7, 5, 3, 2, 1

查找元素

string[] names = { "张三", "李四", "王五", "赵六" };

// 查找元素索引
int index = Array.IndexOf(names, "王五");
Console.WriteLine($"王五的索引:{index}");  // 2

// 检查是否存在
bool exists = Array.Exists(names, name => name == "李四");
Console.WriteLine($"是否存在李四:{exists}");  // true

🎨 多维数组

二维数组(矩阵)

// 声明并初始化
int[,] matrix = {
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};

// 访问元素
Console.WriteLine(matrix[0, 0]);  // 1
Console.WriteLine(matrix[1, 2]);  // 6

// 遍历二维数组
for (int i = 0; i < matrix.GetLength(0); i++)  // 行数
{
    for (int j = 0; j < matrix.GetLength(1); j++)  // 列数
    {
        Console.Write(matrix[i, j] + " ");
    }
    Console.WriteLine();
}

交错数组(数组的数组)

// 每行长度可以不同
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };

// 遍历
for (int i = 0; i < jaggedArray.Length; i++)
{
    for (int j = 0; j < jaggedArray[i].Length; j++)
    {
        Console.Write(jaggedArray[i][j] + " ");
    }
    Console.WriteLine();
}

💡 实战示例

示例1:学生成绩管理

using System;

namespace StudentScores
{
    class Program
    {
        static void Main(string[] args)
        {
            // 存储5个学生的成绩
            int[] scores = new int[5];
            
            // 输入成绩
            Console.WriteLine("请输入5个学生的成绩:");
            for (int i = 0; i < scores.Length; i++)
            {
                Console.Write($"学生{i + 1}:");
                scores[i] = int.Parse(Console.ReadLine());
            }
            
            // 计算总分和平均分
            int sum = 0;
            foreach (int score in scores)
            {
                sum += score;
            }
            double average = (double)sum / scores.Length;
            
            // 查找最高分和最低分
            int max = scores[0];
            int min = scores[0];
            foreach (int score in scores)
            {
                if (score > max) max = score;
                if (score < min) min = score;
            }
            
            // 统计及格人数
            int passCount = 0;
            foreach (int score in scores)
            {
                if (score >= 60) passCount++;
            }
            
            // 显示结果
            Console.WriteLine("\n===== 统计结果 =====");
            Console.WriteLine($"总分:{sum}");
            Console.WriteLine($"平均分:{average:F2}");
            Console.WriteLine($"最高分:{max}");
            Console.WriteLine($"最低分:{min}");
            Console.WriteLine($"及格人数:{passCount}");
            Console.WriteLine($"及格率:{(double)passCount / scores.Length * 100:F2}%");
            
            Console.ReadKey();
        }
    }
}

示例2:冒泡排序

int[] numbers = { 5, 2, 9, 1, 7, 3 };

Console.WriteLine("排序前:" + string.Join(", ", numbers));

// 冒泡排序
for (int i = 0; i < numbers.Length - 1; i++)
{
    for (int j = 0; j < numbers.Length - 1 - i; j++)
    {
        if (numbers[j] > numbers[j + 1])
        {
            // 交换
            int temp = numbers[j];
            numbers[j] = numbers[j + 1];
            numbers[j + 1] = temp;
        }
    }
}

Console.WriteLine("排序后:" + string.Join(", ", numbers));

📝 本章小结

  • 数组是存储同类型数据的集合
  • 索引从 0 开始
  • 使用 Length 获取数组长度
  • for 和 foreach 遍历数组
  • Array 类提供了很多实用方法
  • 二维数组用于表示矩阵

🎯 下一步

掌握了数组后,下一章我们要学习方法,让代码更有条理!

下一章:方法 →

💪 练习题

  1. 创建一个数组存储10个随机数,找出最大值和最小值
  2. 反转数组(不使用 Array.Reverse())
  3. 统计数组中偶数的个数
  4. 实现选择排序算法
答案提示
  1. 使用循环遍历比较
  2. 使用两个指针,头尾交换
  3. 使用 % 运算符判断
  4. 每次找最小值放到前面
最近更新: 2025/12/27 14:02
Contributors: 王长安
Prev
第7章 - 循环语句
Next
第9章 - 方法