C++学习-循环语句-4

目录

while循环

do…while循环语句

for循环语句

嵌套循环


 

while循环

#include <iostream>
using namespace std;

int main(){
    
    int num = 0;
    // 一定要避免死循环的出现
    while (num < 10)
    {
        // cout << num << endl;
        // num++;
        cout << num++ << endl;  //这个和上面的是一样的
    }
    
    return 0;
} 

输出:
0
1
2
3
4
5
6
7
8
9

do…while循环语句

与while的区别在于do…while会先执行一次循环,再判断循环条件

#include <iostream>
using namespace std;

int main(){

    int num = 0;

    do
    { 
        cout << num << endl;
        num++;
    } while (num < 10);
    return 0;
}

水仙花数

#include <iostream>
using namespace std;

int main(){

    int num = 100;
    int hundred = 0;
    int ten = 0;
    int one = 0;

    do
    {
        hundred = num / 100;
        ten = (num - hundred*100) / 10;
        one = (num - hundred*100 - ten*10);
        if (hundred*hundred*hundred + ten*ten*ten + one*one*one == num)
        {
            cout << num << endl;
        }
        num++;

    } while (num < 1000);
    
    return 0;
} 

输出:
153
370
371
407

for循环语句

#include <iostream>
using namespace std;

int main(){

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

例子:找7(个位或十位有7或者是7的倍数)

#include <iostream>
using namespace std;

int main(){

    int hundred = 0;
    int ten = 0;
    int one = 0;

    for (int num = 0;num < 101;num++)
    {
        hundred = num / 100;
        ten = (num - hundred*100) / 10;
        one = (num - hundred*100 - ten*10); 

        if (one==7||ten==7||num % 7==0) //这里只有一条|的话可以输出但是会有警告
        {
            cout << num << endl;
        }
    }
    
    return 0;
} 

嵌套循环

#include <iostream>
using namespace std;

int main(){
    for (int i = 0 ; i < 10 ; i++)
    { 
        for (int j = 0 ; j < 10 ; j++)
        {
            cout << "* ";
            // cout << "* " << endl; 注意:不能加后面的这个,否则会一条输出不会一行
        }
        cout << endl;
    }

    return 0;
} 

输出:
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *

九九乘法表

#include <iostream>
using namespace std;

int main(){
    for (int i = 1 ; i < 10 ; i++)
    { 
        for (int j = 1 ; j < 10 ; j++)
        {
            if (j < i+1)
            { 
                cout << j << "×" << i << " ";
            }
        }
        cout << endl;
    }

    return 0;
} 

输出:
1×1
1×2 2×2
1×3 2×3 3×3
1×4 2×4 3×4 4×4
1×5 2×5 3×5 4×5 5×5
1×6 2×6 3×6 4×6 5×6 6×6
1×7 2×7 3×7 4×7 5×7 6×7 7×7
1×8 2×8 3×8 4×8 5×8 6×8 7×8 8×8
1×9 2×9 3×9 4×9 5×9 6×9 7×9 8×9 9×9

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值