循环结构

本文详细介绍了C++中三种常见的循环结构:for循环、while循环和do-while循环,并通过具体示例展示了每种循环的应用场景及语法特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

①for循环:

    基本用法:    

int i;
for(i = 0; i < 5; i++)
{
     cout << i << endl;
}    //i在循环体外部还能使用
for(int i = 0; i < 5; i++)
{
   cout << i << endl;
}  //i只能在循环体内使用
     使用实例:

#include <iostream>
using namespace std;

int main()
{
    int year[5], sum = 0;
    float average;
    cout << "The Amazing Accounto will sum and average five numbers for you." << endl;
    cout << "Please enter five values: " << endl;
    for(int i = 0; i < 5; i++)
    {
        cout << "Value " << i+1 << ": ";
        cin >> year[i];
    }
    for(int i = 0; i < 5; i++)
        sum += year[i];
    average = sum/5.0;
    cout << "Five exquisite choices indeed! They sum to " << sum << endl;
    cout << "and average to " << average << endl;
    cout << "The Amazing Accounto bids you adieu!" << endl;
    return 0;
}

②while循环

实例:

#include <iostream>

using namespace std;

int main()
{
    char name[20];
    int i = 0;
    cout << "Enter a name: ";
    cin >> name;
    while(name[i] != '\0')
    {
        cout << name[i] << ": " << int(name[i]) << endl;
        i++;
    }
    return 0;
}

③do-while循环

实例:

#include <iostream>

using namespace std;

int main()
{
    int n;
    cout << "Enter numbers in the range 1-10 to find my favorite number: " << endl;
    do
    {
        cin >> n;
    }while(n != 8);
    return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值