C++学习 --循环

目录

1, while语句

2, do ...while语句

3, for语句

4, continue语句

5, break语句

6, goto语句

7, 嵌套循环


1, while语句

通过while (表达式){语句块}, 可实现循环, 直到表达式条件为假,跳出循环

#include <iostream>
using namespace std;

int main()
{
	/*功能: 输入0~9*/
	int num = 0;

	//while循环,表达式为假,跳出循环
	while (num < 10)
	{
		cout << num << " ";
		num++;
	}

	cout << endl;

	system("pause");

	return 0;
}
--------------------------------------------------
输出结果:
0 1 2 3 4 5 6 7 8 9

2, do ...while语句

通过do{语句块}while(表达式), 可实现循环, 直到表达式条件为假,跳出循环, 与while语句的区别是先进行一次语句块,再进行判断

#include <iostream>
using namespace std;

int main()
{	
	/*功能: 输入0~9*/
	int num = 0;

	do
	{
		cout << num << " ";
		num++;
	} while (num < 10);

	cout << endl;

	system("pause");

	return 0;
}
--------------------------------------------------
输出结果:
0 1 2 3 4 5 6 7 8 9

3, for语句

通过for (数据类型 循环变量; 条件表达式; 循环变量修改), 可实现循环, 相比于while语句,可避免死循环出现

#include <iostream>
using namespace std;

int main()
{	
	/*功能: 输入0~9*/
	for (int i = 0; i < 10; i++)
	{
		cout << i << " ";
	}
	cout << endl;

	system("pause");

	return 0;
}
--------------------------------------------------
输出结果:
0 1 2 3 4 5 6 7 8 9

4, continue语句

通过continue语句, 可跳出当前循环, 进行下次循环

#include <iostream>
using namespace std;

int main()
{	
	/*功能: 使用continue跳出本次循环*/
	for (int i = 0; i < 10; i++)
	{
		if (i == 5)
		{
			//通过continue跳出本次循环
			continue;
		}
		cout << i << " ";
	}
	cout << endl;

	system("pause");

	return 0;
}
--------------------------------------------------
输出结果:
0 1 2 3 4 6 7 8 9

5, break语句

通过break语句, 可跳出循环

#include <iostream>
using namespace std;

int main()
{	
	/*功能: 使用break跳出循环*/
	for (int i = 0; i < 10; i++)
	{
		if (i == 5)
		{
			//通过break跳出循环
			break;
		}
		cout << i << " ";
	}
	cout << endl;

	system("pause");

	return 0;
}
--------------------------------------------------
输出结果:
0 1 2 3 4

6, goto语句

通过goto 标记, 可实现语句跳转

#include <iostream>
using namespace std;

/*功能:goto语句*/
int main()
{	
	cout << "语句1" << endl;
	cout << "语句2" << endl;
	//通过goto语句,跳转到FLAG处执行
	int FLAG = 0;
	if (FLAG)
	{
		goto FLAG;
	}
	cout << "语句3" << endl;
	cout << "语句4" << endl;
    //FLAG后有冒号
	FLAG:
	cout << "语句5" << endl;

	system("pause");

	return 0;
}
--------------------------------------------------------
输出结果:
若FLAG = 0, 输出为
语句1
语句2
语句3
语句4
语句5
-------------------------------------------------------
若FLAG = 1, 输出为
语句1
语句2
语句5

7, 嵌套循环

循环中使用循环的方式叫着嵌套循环

#include <iostream>
#include <string>
using namespace std;

/*嵌套循环*/
int main() 
{
	for (int i = 0; i < 5; i++)
	{
		for (int j = 0; j < 5; j++)
		{
			cout << j << " ";
		}
		cout << endl;
	}

	system("pause");
	
	return 0;
}
-------------------------------------------------
输出结果:
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值