标签:style blog http color 使用 strong for 2014
for循环
1.初始状态
2.循环条件
3.循环体
4.状态改变
语法 for( 初始状态 ; 循环条件 ; 状态改变 )
{
循环体;
}
eg:
1 for (int i = 1; i <= 10; i++) 2 { 3 Console.Write(i); 4 }
输出结果为
1 //100以内所有数的和 2 int sum = 0; 3 for (int i = 1; i <= 100; i++) 4 { 5 sum = sum + i; 6 } 7 Console.WriteLine(sum);
1 //公园里有一只猴子和一堆桃子,每次吃掉一般的桃子,再把剩下的桃子扔掉一个坏的,第七天睁开眼发现只有一个桃子了,问刚开始公园里有多少桃子? 2 int sum = 1; 3 for (int i = 1; i < 7; i++) 4 { 5 sum = (sum + 1) * 2; 6 } 7 Console.WriteLine("刚开始公园里有{0}个桃子。", sum);
1 //有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,第24个月兔子总数为多少? 2 int n1 = 1, n2 = 1, num = 1; 3 for (int i = 3; i <= 24; i++) 4 { 5 num = n1 + n2;//第n个月兔子的数量=前两个月的兔子数量的和 6 n1 = n2; 7 n2 = num; 8 } 9 Console.WriteLine(num);
1 //for循环嵌套的使用 2 for (int i = 1; i <= 6; i++) 3 { 4 for (int j = 1; j <= 6 - i; j++) 5 { 6 Console.Write(" "); 7 } 8 for (int k = 1; k <= i + i - 1; k++) 9 { 10 Console.Write("★"); 11 } 12 Console.Write("\n"); 13 }
上面代码输出结果为
//菱形 for (int i = 1; i <= 6; i++) { for (int j = 1; j <= 6 - i; j++) { Console.Write(" "); } for (int k = 1; k <= i + i - 1; k++) { Console.Write("★"); } Console.Write("\n"); } for (int l = 7; l <= 11; l++) { for (int m = 1; m <= l - 6; m++) { Console.Write(" "); } for (int n = 1; n <= 2 * (12 - l) - 1; n++) { Console.Write("★"); } Console.Write("\n"); }
上面代码显示结果为,及图解
标签:style blog http color 使用 strong for 2014
原文地址:http://www.cnblogs.com/zsmj001/p/3919711.html