循环语句主要用于重复执行嵌入语句,常见循环语句如下:
while
【流程图】
【语法格式】
while()
{
}
【应用举例】
创建一个数组,然后通过while语句输出数组中的所有成员
namespace 循环语句
{
class Program
{
static void Main(string[] args)
{
int[] myNum = new int[6] { 927, 112, 111, 524, 521, 2009 };
int s = 0;
while (s < 6)
{
Console.WriteLine("myNum[{0}]的值为{1}", s, myNum[s]);
s++;
}
Console.ReadLine();
}
}
}
【备注】
break和continue的区别:
break是结束整个循环体,continue是结束单次循环。比如现在有包含“2648”四个数的一个数组,判断如果小于5,则输出,否则不输出。如果:
break:在判断6不符合条件后,此段程序结束,不再判断后面的“4,8”
continue:在判断6不符合条件后,直接跳到判断4,而不再顾及后面的语句
do…while
【流程图】
【语法格式】
do
{
}while();
【应用举例】
输入1-10之间的正整数
{思路:声明一个变量a=1,使其每次a=a+1,直到a<11}
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
int a = 10;
do
{
Console.WriteLine("a 的值: {0}", a);
a = a + 1;
} while (a < 20);
Console.ReadLine();
}
}
}
for
【流程图】
【语法格式】
for([初始值];[条件];[迭代])
{
}
【应用举例】
namespace 循环语句
{
class Program
{
static void Main(string[] args)
{
int[] myNum = new int[6] { 927, 112, 111, 524, 521, 2009 };
int s = 0;
while (s < 6)
{
Console.WriteLine("myNum[{0}]的值为{1}", s, myNum[s]);
s++;
}
Console.ReadLine();
}
}
}
得到的结果:
foreach
【流程图】
【语法格式】
foreach([类型] [迭代变量名] in [集合类型表达式])
{
[语句块]
}
【应用举例】
namespace 循环语句
{
class Program
{
static void Main(string[] args)
{
ArrayList lists = new ArrayList();
lists.add("明日科技");
lists.add("编程字典");
Console.WriteLine("集合列表:");
foreach (string strName in lists)
{
Console.WriteLine(strName);
}
Console.ReadLine();
}
}
}
【小结】
对于循环语句的使用,还需多独立练习。