C#学习笔记,2021/12/9

for循环语句 
for语句
for(初始表达式;条件表达式;增量表达式 )
{
   循环体代码;
}
注意
初始表达式:声明循环变量,几率循环的次数[int i=1]
条件表达式:循环的条件;[i<=10]
增量表达式:改变循环条件的代码,使循环代码终有一天不在成立;[i++]
执行过程:
  1. 程序首先执行“初始表达式”,声明一个循环变量,用来记录循环的次数;然后执行“条件表达式”,判断循环条件是否成立,如果“条件表达式”返回的结果为ture,则执行循环代码体。
  2. 当执行玩循环代码后,执行“增量表达式”,然后再次执行“条件表达式”,继续判断循环条件是否成立,如果成立则继续循环代码题,如果不成立,则跳出for循环结构。
 
代码入下:
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("heheheheheh{0}",i);
            }
            Console.ReadKey();
输出结果:
heheheheheh0
heheheheheh1
heheheheheh2
heheheheheh3
heheheheheh4
heheheheheh5
heheheheheh6
heheheheheh7
heheheheheh8
heheheheheh9
演示:1+2+3+.....+100之和。
代码入下:
            int sum = 0;
            for (int i = 0; i <=100; i++)
            {
                sum += i;
            }
            Console.WriteLine(sum);
            Console.ReadKey();
代码输出结果为5050
 
作业:打印1到10
            for (int i = 1; i <=10; i++)
            {
                Console.WriteLine(i);
            }
            Console.ReadKey();
作业:计算1到100所有奇数的和,再计算所有偶数的和。
奇数和:
            int sum = 0;
            for (int i = 1; i <=100; i+=2)
            {
                sum+=i;
            }
            Console.WriteLine(sum);
            Console.ReadKey();
结果2500
偶数和 :
            int sum = 0;//计算偶数和
            for (int i = 2; i <=100; i+=2)
            {
                sum += i;
            }
            Console.WriteLine(sum);
            Console.ReadKey();
结果2550
 
 
posted @ 2021-12-09 20:42  Doser点点  阅读(61)  评论(0)    收藏  举报