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();
        }
    }
}
相关推荐
kid_sup5 分钟前
C语言错题本
c语言·开发语言
白总Server32 分钟前
MySQL在大数据场景应用
大数据·开发语言·数据库·后端·mysql·golang·php
c语言鹌鹑蛋33 分钟前
C++进阶 --- 多继承中的虚表问题
开发语言·c++
姑苏老陈39 分钟前
【Python基础】Python文件处理
开发语言·python·python文件操作
luoluoal41 分钟前
java项目之企业级工位管理系统源码(springboot)
java·开发语言·spring boot
ch_s_t42 分钟前
新峰商城之购物车(一)
java·开发语言
君莫愁。1 小时前
【Unity】检测鼠标点击位置是否有2D对象
unity·c#·游戏引擎
学步_技术1 小时前
Python编码系列—Python工厂方法模式:构建灵活对象的秘诀
开发语言·python·工厂方法模式
Deryck_德瑞克1 小时前
Java集合笔记
java·开发语言·笔记
MengYiKeNan1 小时前
C++二分函数lower_bound和upper_bound的用法
开发语言·c++·算法