循环结构(个人学习笔记黑马学习)

while循环语句

在屏幕中打印0~9这十个数字

#include <iostream>
using namespace std;

int main() {

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


	system("pause");
	return 0;
}

 

练习案例: 猜数字


案例描述:系统随机生成一个1到100之间的数字,玩家进行猜测,如果猜错,提示玩家数字过大或过小,如果猜对恭喜玩家胜利,并且退出游戏。

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

int main() {

	srand((unsigned int)time(NULL));
	int num = rand() % 100 + 1;
	int num2 = 0;
	cout << "请输入数字" << endl;

	while (1) {
		cin >> num2;
		if (num > num2) {
			cout << "猜小了" << endl;
		}
		else if (num < num2) {
			cout << "猜大了" << endl;

		}
		else {
			cout << "猜对了" << endl;
			break;
		}
	}
	system("pause");
	return 0;
}

 

 


do……while循环语句 

在屏幕中打印0~9这十个数字

#include <iostream>
using namespace std;


int main() {

	int num = 0;
	do {
		cout << num << endl;
		num++;
	} while (num < 10);
	system("pause");
	return 0;
}

 


练习案例: 水仙花数


案例描述: 水仙花数是指一个 3 位数,它的每个位上的数字的 3次幕之和等于它本身
例如: 1^3 + 5^3+ 3^3 = 153
请利用do...while语句,求出所有3位数中的水仙花数 

#include <iostream>
using namespace std;


int main() {

	int i = 100;
	do {
		int x1=i / 100;
		int x2 = i / 10 % 10;
		int x3=i % 10;
		if (x1 * x1 * x1 + x2 * x2 * x2 + x3 * x3 * x3 == i) {
			cout << i << endl;
		}
		i++;
	} while (i < 1000);
	system("pause");
	return 0;
}

 

for循环 

在屏幕中打印0~9这十个数字

#include <iostream>
using namespace std;


int main() {

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

 

 


练习案例:敲桌子


案例描述:从1开始数到数字100如果数字个位含有7,或者数字十位含有7,或者该数字是7的倍数,我们打印敲桌子,其余数字直接打印输出。

#include <iostream>
using namespace std;


int main() {

	for (int i = 0; i <= 100; i++) {
		if (i % 10 == 7 || i / 10 == 7 || i % 7 == 0) {
			cout << "拍桌子" << endl;
		}
		else {
			cout << i << endl;
		}
	}

	system("pause");
	return 0;
}

 

 


嵌套循环

打印10*10方正

#include <iostream>
using namespace std;


int main() {

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

	system("pause");
	return 0;
}

 


乘法口诀表 

#include <iostream>
using namespace std;


int main() {

	for (int i = 1; i <= 9; i++) {
		for (int j = 1; j <= i; j++) {
			cout << j << "*" << i <<"=" << i * j<<"  ";
		}
		cout << endl;
	}

	system("pause");
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值