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();
        }
    }
}
相关推荐
听风的码38 分钟前
Vue2封装Axios
开发语言·前端·javascript·vue.js
素界UI设计2 小时前
建筑行业变革:用Three.js构建BIM数据可视化孪生平台
开发语言·javascript·信息可视化
王廷胡_白嫖帝2 小时前
Qt个人通讯录项目开发教程 - 从零开始构建联系人管理系统
开发语言·qt
疯狂的代M夫3 小时前
C++对象的内存布局
开发语言·c++
mit6.8243 小时前
Linux下C#项目构建
开发语言·c#
群联云防护小杜4 小时前
从一次 DDoS 的“死亡回放”看现代攻击链的进化
开发语言·python·linq
霸敛4 小时前
好家园房产中介网后台管理完整(python+flask+mysql)
开发语言·python·flask
Momentary_SixthSense4 小时前
RESP协议
java·开发语言·javascript·redis·后端·python·mysql
Nita.5 小时前
.NET 中的延迟初始化:Lazy<T> 与LazyInitializer
c#·.net
only-lucky5 小时前
C++中的 Eigen库使用
开发语言·c++