C# for语句

计数循环使用for语句比while语句可读性高

for (int i = 0; i < 10; i++)

{

Console.WriteLine("hello");

}

先执行int i=0;语句,且只执行一次

判断循环条件 i<10; 语句的结果是否为true,如果为true,先执行循环体,再执行 i++;语句。

打印九九乘法表

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StatementsExample4
{
    internal class Program
    {
        static void Main(string[] args)
        {
           for(int a=1;a<10;a++)
            {
                for(int b=1;b<10;b++)
                {
                    if (b > a)
                    {
                        break; 
                    }
                    Console.Write("{0}x{1}={2}\t",a,b,a*b);//\t 是制表
                }
                Console.WriteLine();
            }
            Console.ReadLine();
        }
    }
}

该代码可以修改为

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StatementsExample4
{
    internal class Program
    {
        static void Main(string[] args)
        {
           for(int a=1;a<10;a++)
            {
                for(int b=1;b<=a;b++)
                {
                  
                    Console.Write("{0}x{1}={2}\t",a,b,a*b);//\t 是制表
                }
                Console.WriteLine();
            }
            Console.ReadLine();
        }
    }
}

运行结果:

该代码可以修改为打印三角形

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StatementsExample4
{
    internal class Program
    {
        static void Main(string[] args)
        {
           for(int a=1;a<10;a++)
            {
                for(int b=1;b<=a;b++)
                {
                  
                    Console.Write("*\t");//\t 是制表对齐
                }
                Console.WriteLine();
            }
            Console.ReadLine();
        }
    }
}
相关推荐
小峥降临1 小时前
Rokid UXR 的手势追踪虚拟中更真实的手实战开发【含 工程源码 和 最终完成APK】
c#
晨星shine4 天前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户298698530144 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
用户3667462526744 天前
接口文档汇总 - 2.设备状态管理
c#
用户3667462526744 天前
接口文档汇总 - 3.PLC通信管理
c#
Ray Liang5 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Scout-leaf8 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530148 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools9 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的10 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书