循环语句的老祖宗----goto语句:
要慎用goto语句,因为goto语句能直接跳转的程序的设定位置继续执行。
#include<iostream>
using namespace std;
void main()
{
int i = 1;//初始化1
Skip://配合goto跳转
i++;
cout << "*";
if (i < 21)
{
goto Skip;//关键字goto
}
cout << "\n欢迎来到玫瑰坊!\n********************\n";
}
while语句:
#include<iostream>
using namespace std;
void main()
{
int i = 1;//初始化1
while (i<=100&&i>0)//一直执行循环,直到条件为假时结束
{
cout << "I:"<<i<<endl;
i++;
}
}
另一种:
#include<iostream>
using namespace std;
void main()
{
int i=0,j ;
cout << "看几次?\n";
cin >> j;
while (i<j)//一直执行循环,直到条件为假时结束
{
cout << "\n欢迎来到玫瑰坊!\n";
i++;
}
cout << "再见!\n";
}
字符也可以作为while循环的条件:
#include<iostream>
using namespace std;
void main()
{
char choice='Y' ;
while (choice=='y'||choice=='Y')//一直执行循环,直到条件为假时结束
{
cout << "\n欢迎来到玫瑰坊!\n";
cout << "再看一遍按Y,否则按N:";
cin >> choice;
}
cout << "再见!\n";
}
continue与break语句:
#include<iostream>
using namespace std;
void main()
{
int i=0 ;
while (i<3)//一直执行循环,直到条件为假时结束
{
i++;
if (i == 1)
{
break;//强制终止循环
//continue;//跳转到循环的开头
}
cout << "I:"<<i<<endl;
}
cout << "I:" << i << endl;
cout << "再见!\n";
}
死循环while循环:
int main()
{
int i = 0;
while (1)
{
int n;
cout << "请输入一个数字:" << endl;
cin >> n;
cout << "输入的数字为:" << n << endl;
i++; //当i自加到4时,执行break。
if (i > 3)
break;
}
cout << "该程序执行了" << i << "次!" << endl;
return 0;
}
do{........}while();语句
#include<iostream>
using namespace std;
int main()
{
int i ;
cout << "想执行几次?\n";
cin >> i;
do //循环至少会执行1次
{
cout << "欢迎来到玫瑰坊!\n";
i--;
}while (i > 0); //do{} while();
cout << "该程序执行完毕!" << endl;
return 0;
}
for 循环:
int main()
{
int i;
cout << "想执行几次?\n";
cin >> i;
for (int n = 0; n < i;i--)//for循环可以对多个变量进行初始化,只能有一个判断,可以执行操作(i++或者cout等),用逗号隔开
{
cout << "欢迎来到玫瑰坊!\n";
}
cout << "该程序执行完毕!" << endl;
return 0;
}
嵌套for循环:
外面的 循环每执行一次,里面的循环就要完全执行一次。
#include<iostream>
using namespace std;
int main()
{
int a, b;
char c;
cout << "多少行?";
cin >> a;
cout << "多少列?";
cin >> b;
cout << "什么字?";
cin >> c;
for (int i = 0; i < a; i++)
{
for (int j = 0; j< b; j++)//里面的循环要完全执行完
{
cout << c;
}
cout << "\n";
}
return 0;
}
switch语句:
条件很多的话,可以用switch语句。判断条件很多的时候可以使用i f 语句,但比较麻烦所有有了switch语句。
#include<iostream>
using namespace std;
int main()
{
int choice;
cout << "请输入一个整数:";
cin >> choice;
switch (choice) //检查口号中的变量,可以是字符,可是表达式,总之要有一个可判断的值
{
case 0:cout << "输入了0\n"; //如果小括号的值出现在某个case中则执行这条case语句
break; //执行完毕后break会让程序跳出 switch 语句
case 1:cout << "输入了1\n";
break;
case 2:cout << "输入了2\n";
break;
case 3:cout << "输入了3\n";
break;
default: //假如小括号中的值与所有case语句都不相符则,就执行default语句后退出switch语句
cout << "请输入0至3之间的有效数字!\n";
break;
}
cout << "欢迎来到玫瑰坊!\n";
return 0;
}
总结:
假如想要要无条件的跳转到某条语句执行,用goto语句;
假如想要对某种条件进行判断,为真或为假分别执行不同的语句,用 i f 语句;
假如需要检测的条件很多,用 i f....else语句;
假如是对数字或者字符进行检测并且需要检测的条件很多,用switch语句;
假如能够确定循环的次数,用f o r语句;
假如不能确定循环的次数,用while语句;
假如循环体的语句至少要执行一次,那么用do.....while语句;
另:
continue可以使循环又一次重新开始,而break可以使循环直接结束;
循环语句
最新推荐文章于 2022-11-24 13:13:37 发布