编程基础之流程控制

无论任何程序源码都是按照从上到下依次执行的,本文在不涉及函数的前提下,讨论基础的流程控制。

一、从上往下依次执行

Console.WriteLine("Hello World!");
Console.WriteLine("this is first program");

二、判断分支,根据结果执行不同的操作

Console.Write("请输入一个数字");
            int a = int.Parse(Console.ReadLine());
            if (a == 1)
            {
                Console.WriteLine("Hello World!");
            }
            else
            {
                Console.WriteLine("this is first program");
            }

三目运算:单个判断的简写形式

int a = 1;
            Console.WriteLine(a==1?true:false);

在判断的时候可以执行多个判断,用else if 表示,else语句也可以省略。

三、循环语句

某一条件执行多次判断,直到判断不成立再结束。

在循环判断中有多个方式:for循环 while循环、do…while循环、for…in循环、foreach循环。根据自己需要使用不同的循环;

1、for循环

for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(i);
            }

for(表达式1;判断条件;表达式2)

{

循环体

}

image

2、while循环

int a = 0;
            while (true) {
                a++;
                Console.WriteLine("你好");
                if (a == 10) {
                    break;
                }
            }

image

3、do…while 循环  先执行循环体再进行判断

int a = 0;
            do {
                Console.WriteLine("你好");
                a++;
            } while (a < 10);

image

4、for…in循环

不同语言定义不同或部分语言没有这个循环,略

5、foreach循环

常用于遍历数据。

四、循环之switch:

不同分支,执行不同的代码,但所有分支都会中断循环。

int a = 1;
            switch (a) {
                case 1:
                    Console.WriteLine("1");
                    break;
                case 2:
                    Console.WriteLine("2");
                    break;
                default:
                    Console.WriteLine("other");
                    break;
            }

image

猜你喜欢

转载自www.cnblogs.com/Csharp-Learn/p/9426272.html