[黑马程序员C++笔记]P37-P41嵌套循环/跳转语句

发布于:2022-10-19 ⋅ 阅读:(611) ⋅ 点赞:(0)

视频地址:黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难_哔哩哔哩_bilibili

目录

P37程序流程结构-嵌套循环

P38程序流程结构-嵌套循环案例-乘法口诀表

P39程序流程结构-调转语句-break语句

P40程序流程结构-跳转语句-continue

P41程序流程结构-跳转语句-goto


P37程序流程结构-嵌套循环

作用:在循环体中再嵌套一层循环,结局实际问题

例如我们想在屏幕中打印如下图片,就需要利用嵌套循环

 

#include <iostream>
using namespace std;
int main() {
	for (int i = 1; i <= 10; i++) {
		for (int j = 1; j <= 10; j++) {
			cout << "*"<<" ";
		}
		cout << endl;
	}
	system("pause");
	return 0;
}

运行后的结果为:

P38程序流程结构-嵌套循环案例-乘法口诀表

 

 

int main() {
	for (int i = 1; i < 10; i++) {
		for (int j = 1; j <= i; j++) {
			cout << i << "*" << j << "="<<i * j <<" ";
		}
		cout << endl;
	}
	system("pause");
	return 0;

}

运行后的结果为:

P39程序流程结构-调转语句-break语句

作用:用于跳出选择结构或者循环结构

break使用的时机:

  • 出现在switch条件语句中,作用时终止case并跳出switch;
  • 出现在循坏语句中,作用时跳出当前循环语句;
  • 出现在嵌套循环中,作用时跳出最近的内层循环;

示例:

1、出现在switch条件语句中,作用时终止case并跳出switc

#include <iostream>
using namespace std;
int main() {
	// break使用时机
    //1、使用在switch语句中,用于终止case并跳出switch
	cout << "请选择副本难度:" << endl;
	cout << "1、普通" << endl;
	cout << "2、中等" << endl;
	cout << "3、困难" << endl;
	int num = 0;
	cin >> num;
	switch (num) {
	case 1:
		cout << "您选择的是普通难度" << endl;
		break;
	case 2:
		cout << "您选择的是中等难度" << endl;
		break;
	case 3:
		cout << "您选择的是困难难度" << endl;
		break;
	}
	system("pause");
	return 0;

}

运行后的结果为:

 若没有break,运行后的结果为:

 2、出现在循坏语句中,作用时跳出当前循环语句;(以for循环为例)

若没有break:

for (int i = 0; i < 10; i++) {
		cout << i << endl;
	}

运行后的结果为:

 若加入break:

	for (int i = 0; i < 10; i++) {
		if (i == 5) {
			break;
		}
		cout << i << endl;
	}

运行后的结果为:

3、出现在嵌套循环中,作用时跳出最近的内层循环

for (int i = 0; i < 10; i++)
	{
		for (int j = 0; j < 10; j++)
		{
			if (j == 5)
			{
				break;
			}
			cout << "*" << " ";
		}
		cout << endl;
	}

运行后的结果为:

P40程序流程结构-跳转语句-continue

作用:在循环语句中,跳过本次循环中余下尚未执行的语句,继续执行下一次循环

示例:

int main() {

	for (int i = 0; i < 10; i++)
	{
		if (i % 2 == 0)
		{
			continue;//可以筛选条件, 执行到此就不再向下执行,执行下一次循环
		}
		cout << i << endl;
	}
	
	system("pause");

	return 0;
}

运行后的结果为:

P41程序流程结构-跳转语句-goto

作用:可以无条件跳转语句

语法: goto 标记;

解释:如果标记的名称存在,执行到goto语句时,会跳转到标记的位置

示例:

int main() {

	cout << "1" << endl;

	goto FLAG;

	cout << "2" << endl;
	cout << "3" << endl;
	cout << "4" << endl;

	FLAG:

	cout << "5" << endl;
	
	system("pause");

	return 0;
}

注意:在程序中不建议使用goto语句,以免造成程序流程混乱

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到