详解C++ 循环

简介: while 循环, do…while 循环也是可以嵌套使用的实例:打印一个简易的乘法口诀表:🧧


1.while循环


只要给定的条件为真,while 循环语句会重复执行一个目标语句

C++ 中 while 循环的语法:


while(condition)
{
   statement(s);
}


实例:计算 1 加到 100 的值:(while循环版本)🍟


#include <bits/stdc++.h>
using namespace std;
int main()
{
    int sum = 0, n = 1;
    while( n <= 100 )
    {
        sum += n;
        n++;
    }
    cout<< sum <<endl;  // 5050
    return 0;
}


2.for 循环

for 循环允许您编写一个执行特定次数的循环的重复控制结构。

C++ 中 for 循环的语法:


for ( init; condition; increment )
{
   statement(s);
}


实例:计算 1 加到 100 的值:(for循环版本)🍠


#include <bits/stdc++.h>
using namespace std;
int main()
{
    int sum = 0;
    for( int a = 1 ; a <= 100 ; a++ )
    {
        sum += a;
    }
    cout<< sum <<endl;  // 5050
    return 0;
}


还能优化吗?😶‍🌫️


#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n = 100;
    cout << n*(n+1)/2 <<endl;  // 高斯求和:5050
    return 0;
}


3.算法的优劣衡量


对10亿数据集进行测试:


#include <bits/stdc++.h>
using namespace std;
int main()
{
    clock_t startTime,endTime;
    startTime = clock();  // 计时开始
    long long sum = 0;
    for( int a = 1 ; a <= 1000000000 ; a++ )
    {
        sum += a;
    }
    cout<< sum <<endl;  // 500000000500000000
    endTime = clock();  // 计时结束
    cout<< "程序运行时间:" << endTime - startTime <<endl;  // 程序运行时间:3423
    return 0;
}


使用高斯求和算法:


#include <bits/stdc++.h>
using namespace std;
int main()
{
    clock_t startTime,endTime;
    startTime = clock();  // 计时开始
    long long n = 1000000000;
    cout << n*(n+1)/2 <<endl;  // 高斯求和:500000000500000000
    endTime = clock();  // 计时结束
    cout<< "程序运行时间:" << endTime - startTime <<endl;  // 程序运行时间:0
    return 0;
}


4.C++11新特性 auto 写法


for 语句允许简单的范围迭代:


#include <bits/stdc++.h>
using namespace std;
int main()
{
    string heiheipapa = "Shuangmu";
    for (auto s : heiheipapa)
    {
        cout<< s <<endl;
    }
    return 0;
}


5.do…while 循环


do…while 循环与 while 循环类似,但是 do…while 循环会确保至少执行一次循环

C++ 中 do…while 循环的语法:


do
{
   statement(s);
}while( condition );


o…while的典型使用场景,用户名密码输入:


#include <bits/stdc++.h>
using namespace std;
const int MAX_TRY = 3;
const string PASSWORD = "xiaofei";
int main()
{
    string userinput;
    int try_count = 0;
    do
    {
        cout<< "请输入密码:";
        cin>>userinput;
        if ( userinput == PASSWORD )
        {
            cout<< "aha,hacker!" <<endl;
            break;  // 退出循环
        }
        else
        {
            cout<< "密码错误!" <<endl;
            try_count++;
        }
    }while( try_count < 3 );
    return 0;
}


6.break 语句


break 语句会停止执行最内层的循环,然后开始执行该块之后的下一行代码




include <iostream>
using namespace std;
int main ()
{
   // 局部变量声明
   int a = 10;
   // do 循环执行
   do
   {
       cout << "a 的值:" << a << endl;
       a = a + 1;
       if( a > 15)
       {
          // 终止循环
          break;
       }
   }while( a < 20 );
   return 0;
}
/*
a 的值: 10
a 的值: 11
a 的值: 12
a 的值: 13
a 的值: 14
a 的值: 15
*/


7.continue 语句


continue 会跳过当前循环中的代码,强迫开始下一次循环



实例:模拟点名程序🎠

hacker不想让自己上课被老师点到,于是他偷偷修改了老师的随机点名代码


#include <bits/stdc++.h>
using namespace std;
string NAME_LIST[5] = {"Herbert","Baron","hacker","Darren","Elijah"};
int main()
{
    srand((unsigned)time(NULL));  // 随机种子
    for( int i = 0 ; i < 1000 ; i++ )
    {
        int num = rand() % 5;  // 生成 0 - 4 的随机数
        if ( NAME_LIST[num] == "hacker" ) continue;
        cout<< NAME_LIST[num] <<endl;
    }
    return 0;
}


8.循环嵌套结构


一个循环内可以嵌套另一个循环。C++ 允许至少 256 个嵌套层次


C++ 中 嵌套 for 循环 语句的语法:


for ( init; condition; increment )
{
   for ( init; condition; increment )
   {
      statement(s);
   }
   statement(s); // 可以放置更多的语句
}


while 循环, do…while 循环也是可以嵌套使用的

实例:打印一个简易的乘法口诀表:🧧


#include <bits/stdc++.h>
using namespace std;
int main()
{
    for( int i = 1 ; i <= 10 ; i++ )
    {
        for( int j = 1 ; j <= 10 ; j++)
        {
            cout<< i << "*" << j << "=" << i * j <<endl;
        }
    }
    return 0;
}
/*
1*1=1
1*2=2
1*3=3
1*4=4
1*5=5
1*6=6
1*7=7
1*8=8
1*9=9
1*10=10
2*1=2
2*2=4
2*3=6
2*4=8
2*5=10
2*6=12
2*7=14
2*8=16
2*9=18
2*10=20
3*1=3
3*2=6
3*3=9
3*4=12
3*5=15
3*6=18
3*7=21
3*8=24
3*9=27
3*10=30
4*1=4
4*2=8
4*3=12
4*4=16
4*5=20
4*6=24
4*7=28
4*8=32
4*9=36
4*10=40
5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50
6*1=6
6*2=12
6*3=18
6*4=24
6*5=30
6*6=36
6*7=42
6*8=48
6*9=54
6*10=60
7*1=7
7*2=14
7*3=21
7*4=28
7*5=35
7*6=42
7*7=49
7*8=56
7*9=63
7*10=70
8*1=8
8*2=16
8*3=24
8*4=32
8*5=40
8*6=48
8*7=56
8*8=64
8*9=72
8*10=80
9*1=9
9*2=18
9*3=27
9*4=36
9*5=45
9*6=54
9*7=63
9*8=72
9*9=81
9*10=90
10*1=10
10*2=20
10*3=30
10*4=40
10*5=50
10*6=60
10*7=70
10*8=80
10*9=90
10*10=100
*/


实例:暴力找质数:🍗


#include <bits/stdc++.h>
using namespace std;
int main()
{
    for( int i = 2 ; i <= 100 ; i++)
    {
        bool is_prime = true;
        for( int j = 2 ; j < i ; j++)
        {
            if( i % j == 0 )
            {
                is_prime = false;
                break;
            }
        }
        if( is_prime == true )
        {
            cout<< i << "是质数" <<endl;
        }
    }
    return 0;
}
目录
相关文章
|
30天前
|
设计模式 测试技术 编译器
C++项目中打破循环依赖的锁链:实用方法大全(一)
C++项目中打破循环依赖的锁链:实用方法大全
78 0
|
2月前
|
机器学习/深度学习 C++
C/C++基础知识——数组、循环
C/C++基础知识——数组、循环
39 0
C/C++基础知识——数组、循环
|
16天前
|
C++
C++ While 和 For 循环:流程控制全解析
本文介绍了C++中的`switch`语句和循环结构。`switch`语句根据表达式的值执行匹配的代码块,可以使用`break`终止执行并跳出`switch`。`default`关键字用于处理没有匹配`case`的情况。接着,文章讲述了三种类型的循环:`while`循环在条件满足时执行代码,`do/while`至少执行一次代码再检查条件,`for`循环适用于已知循环次数的情况。`for`循环包含初始化、条件和递增三个部分。此外,还提到了嵌套循环和C++11引入的`foreach`循环,用于遍历数组元素。最后,鼓励读者关注微信公众号`Let us Coding`获取更多内容。
19 0
|
30天前
|
设计模式 敏捷开发 持续交付
C++项目中打破循环依赖的锁链:实用方法大全(三)
C++项目中打破循环依赖的锁链:实用方法大全
47 0
|
30天前
|
测试技术 持续交付 API
C++项目中打破循环依赖的锁链:实用方法大全(二)
C++项目中打破循环依赖的锁链:实用方法大全
55 0
|
1月前
|
并行计算 编译器 程序员
提升C/C++编程效率:深入C/C++ for循环的优化与应用
提升C/C++编程效率:深入C/C++ for循环的优化与应用
59 0
|
1月前
|
C++
C++系列八:选择、循环与转向
C++系列八:选择、循环与转向
|
1月前
|
C++ 容器
C++语言中for语句循环和作用类型
C++语言中for语句循环和作用类型
24 0
|
1月前
|
存储 C++ 索引
c++for结构循环超详细讲解
c++for结构循环超详细讲解
21 1
|
1月前
|
程序员 C++
c++循环
c++循环
14 0