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();
        }
    }
}
相关推荐
asdfg12589634 分钟前
一文理解Java中的泛型
java·开发语言
Hiter_John11 分钟前
Golang的变量常量初始化
开发语言·后端·golang
电商API_1800790524729 分钟前
免 TOP 入驻,第三方淘宝商品详情 API 快速接入与代码示例
java·大数据·开发语言·数据库·爬虫·数据分析
c2385635 分钟前
C++列表初始化与变量类型推导
开发语言·c++
代码小库37 分钟前
【2026前端最新面试题——day10】JavaScript 高频面试题
开发语言·前端·javascript
零陵上将军_xdr1 小时前
后端转全栈学习-Day4-JavaScript 基础-2
开发语言·javascript·学习
小科先生1 小时前
初学者安装java
java·开发语言
ID_180079054731 小时前
小红书笔记评论 API 接口深度解析(带全套 JSON 示例・技术实战版)
java·开发语言·windows
折戟不必沉沙1 小时前
C++四种类型转换是什么
开发语言·c++
天青色等烟雨..1 小时前
AI赋能R-Meta分析核心技术:从热点挖掘到高级模型、助力高效科研与论文发表
开发语言·人工智能·r语言