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();
        }
    }
}
相关推荐
uppp»19 分钟前
深入理解 Java 反射机制:获取类信息与动态操作
java·开发语言
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
ll7788115 小时前
LeetCode每日精进:20.有效的括号
c语言·开发语言·算法·leetcode·职场和发展
Jackson@ML7 小时前
Python数据可视化简介
开发语言·python·数据可视化
赵琳琅7 小时前
Java语言的云计算
开发语言·后端·golang
lly2024067 小时前
jQuery 杂项方法
开发语言
赵琳琅7 小时前
MDX语言的安全开发
开发语言·后端·golang
开开又心心的学嵌入式7 小时前
C语言——指针进阶应用
c语言·开发语言
开开又心心的学嵌入式7 小时前
C语言——指针基础知识
c语言·开发语言
lonelyhiker7 小时前
javascript的原型链
开发语言·javascript·原型模式