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();
        }
    }
}
相关推荐
菥菥爱嘻嘻17 分钟前
JS手写代码篇---手写ajax
开发语言·javascript·ajax
江梦寻23 分钟前
MacOS下Homebrew国内镜像加速指南(2025最新国内镜像加速)
开发语言·后端·python·macos·架构·策略模式
霖檬ing26 分钟前
Python——MySQL远程控制
开发语言·python·mysql
qq_429879671 小时前
省略号和可变参数模板
开发语言·c++·算法
优秀的颜2 小时前
计算机基础知识(第五篇)
java·开发语言·分布式
CodeWithMe2 小时前
【C/C++】std::vector成员函数清单
开发语言·c++
uyeonashi2 小时前
【QT控件】输入类控件详解
开发语言·c++·qt
iCxhust4 小时前
Prj10--8088单板机C语言8259测试(1)
c语言·开发语言
枫叶kx4 小时前
1Panel运行的.net程序无法读取系统字体(因为使用了docker)
c#
крон6 小时前
【Auto.js例程】华为备忘录导出到其他手机
开发语言·javascript·智能手机