C#入门5.6——迭代语句之for语句

本文介绍C#中for循环的基本语法及其使用方法,包括如何创建死循环及for循环的应用实例。此外,还提供了一个使用for循环打印99乘法表的经典案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

for语句格式:

for(初始条件;判断条件;循环条件)

{

循环语句;

}


for循环可以记录循环的次数,有效控制循环的方式。有时候我们会省略初始条件、判断条件、循环条件,这时候两个分号是不能省略的,此时构成死循环。

死循环应用实例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("请输入需要计算阶乘的数:");
            for(;;)
            {
                int a=int.Parse(Console.ReadLine());
                int jieCheng = 1;
                for(int i=1;i<=a;i++)
                {
                    jieCheng *= i;
                }
                Console.WriteLine("阶乘的结果是:"+jieCheng);
            }
                 
        }
    }
}

附加for循环嵌套经典例题:99乘法表

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("99乘法表");
            int i, j;
            for(i=1;i<=9;i++)
            {
                for (j = 1; j <= 9; j++)
                {
                    if (i >= j)
                        Console.Write("{0}×{1}={2}\t", j, i, i * j);
                }
                Console.Write("\n");
            }
            Console.ReadKey();    
        }
    }
}


运行结果:(经典就是经典)

99乘法表
1×1=1
1×2=2  2×2=4
1×3=3  2×3=6  3×3=9
1×4=4  2×4=8  3×4=12 4×4=16
1×5=5  2×5=10 3×5=15 4×5=20 5×5=25
1×6=6  2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
1×7=7  2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
1×8=8  2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
1×9=9  2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值