079-循环

for循环

语法一:

for(初始化表达式;运行条件表达式;变动表达式)
{
    循环内容;
}

语法二:

循环可以进行嵌套,

for()
{
    for()
    {
        for()
        {
            ....
        }
    }
}

语法三

continue结束本次循环后面的内容

break跳出循环

goto跳到任意位置

语法四

for(;条件;变动)
{
    
}

for(;条件;)
{
    
}

for(;;)
{
    
}

示例

示例一

#include 

int main()
{
	int password, repassword;
lset:
	system("cls");
	std::cout << "请设置六位数密码:";
	std::cin >> password;
	std::cout << "请再输入一次设置的密码:";
	std::cin >> repassword;
	if (password == repassword)
	{
		system("cls");
		std::cout << "开始破解密码!" << std::endl;
		for (int i = 0; i < 1'000'000; i++)
		{
			if (i == password)
			{
				std::cout << "你的密码是:" << i << std::endl;
				goto lexit;
			}
		}
	}
	else
	{
		goto lset;
	}
lexit:
	std::cout << "密码破解成功\n";
}

示例二

#include 
#include 
int main()
{
	for (int i = 1; i <= 9; i++)
	{
		for (int j = 1; j <= i; j++)
		{
			std::cout << std::setw(2) << j << "x" << std::setw(2) <

示例三

#include 
#include 

int main()
{
	bool flag{};
	for (int i = 3; i <= 1000; i+=2)
	{
		flag == false;
		for (int j = 2; j < sqrt(i); j+=2)
		{
			if (i % j == 0)
			{
				flag = true;
				break;
			}	
		}
		if (!flag)
			std::cout << i << "是质数!\n";
	}
}

示例四

#include 

int main()
{
	for (int a = 0; a <= 100; a++)
	{
		for (int b = 0; b <= 100; b++)
		{
			for (int c = 0; c <= 100; c++)
			{
				if ((500 * a + b * 300 + 100 * c / 3 == 10'000) && (a + b + c == 100))
				{
					std::cout << "a有" << a << "件,b有" << b << "件,c有" << c << "件.\n";
				}
			}
		}
	}
}

优化一

#include 

int main()
{
	for (int a = 0; a <= 10'000/500; a++)
	{
		for (int b = 0; b <= 10'000/300; b++)
		{
			if ((500 * a + 300 * b + (100 - a - b) * 100 / 3 == 10'000))
				std::cout << a << "\t" << b << "\t" << 100 - a - b << "\n";
		}
	}
}

优化二

#include 

int main()
{
	for (int a = 0; a <= 10'000/500; a++)
	{
		for (int b = 0; b <= 10'000/300; b++)
		{
			if (((100-a-b)%3==0)&&(500 * a + 300 * b + (100 - a - b) * 100 / 3 == 10'000))
				std::cout << a << "\t" << b << "\t" << 100 - a - b << "\n";
		}
	}
}

优化三

#include 

int main()
{
	for (int i = 0; i <= 3; i++)
		std::cout << "a为" << 4 * i << "\tb为" << 25 - i * 7 << "\tc为" << 75 + 3*i << "\n";
}

示例五

#include 
#include 
#include 

int main()
{
	char in = _getch();
	if (in == 'l' || in == 'L')
	{
		for (int lv{ 1 }; lv <= 100; lv++)
		{
			std::cout << std::setfill(' ');
			std::cout << std::setw(3) << lv << "\t所需的经验是:" << std::setw(10)
				<< lv * lv * 100 << std::endl;
		}
	}
}

while循环

语法

while(条件语句)
{
    语句;
}

示例

#include 

int main()
{
	int password{ 95932714 };
	int crackPss{};

lcrack:
	if (crackPss != password)
	{
		crackPss++;
		goto lcrack;
	}
	std::cout << "路由器Pin-" << crackPss << std::endl;

	for (int crackPass = 0; crackPass!=password; crackPass++)
	{
		if (crackPass5 == password) break;
	}

	std::cout << "路由器Pin-" << crackPss << std::endl;

	crackPss = 0;
	while (crackPss != password)
	{
		crackPss++;
	}
	std::cout << "路由器Pin-" << crackPss << std::endl;
}

你可能感兴趣的:(c++,开发语言,c语言)