C++

迴圈

目錄

for迴圈

while迴圈

break/continue

for 迴圈

 

重複計算小幫手

cout<<"hello world"<<endl;
cout<<"hello world"<<endl;
cout<<"hello world"<<endl;
cout<<"hello world"<<endl;
cout<<"hello world"<<endl;
for(int a=0;a<5;a++)
{
  cout<<"hello world"<<endl;
}

for迴圈的功能

for迴圈

認識一下for迴圈

包含初始值、判斷式、遞增遞減及程式主體

須注意範圍

適合處理有次序的事

for迴圈

for(變數初始值;判斷式;調整)//如果判斷成立
{
  執行程式;
}
for(int day=1;day<8;day++)



{
  cout<<"今天是星期"<<day<<endl;
}

宣告整數變數day=1

若day<8 繼續迴圈

每執行完一次迴圈 day遞增1

for(int day=1;day<8;day++)
{
  cout<<"今天是星期"<<day<<endl;
}

int day=1

day<8

輸出

day++

巢狀迴圈 - 現在是幾點?

#include<iostream>
using namespace std;
int main()
{
  for(int hr=1;hr<13;hr++)
  {
    for(int min=1;min<13;min++)
    {
      cout<<"時針指向"<<hr<<" 分針指向"<<min<<endl;
    }
  }
}

while 迴圈

 

無限循環的條件判斷

while迴圈的個人簡介

檢查條件執行程式

無限循環的條件判斷

包含判斷式及程式主體

while迴圈

while(判斷式)//如果判斷成立
{
  執行程式;
}
int vacation=3;
while(vacation>2)
{
  cout<<"yeah";
}

無限輪迴?

無窮迴圈終結者!

調整變數

使用break/continue

int vacation=3;
while(vacation>2)
{
  cout<<"yeah";
  break;
}
int vacation=3;
while(vacation>2)
{
  cout<<"yeah";
  cin>>vacation;
}

for/while迴圈可以互換!

int vacation;
for(vacation=5;vacation>0;vacation--)
{
  cout<<"你的假期還剩下"<<vacation<<"天"<<endl;
}
int vacation;
vacation=5;
while(vacation>0)
{
  cout<<"你的假期還剩下"<<vacation<<"天"<<endl;
  vacation--;
}
億點點小補充

Do-while迴圈

執行程式檢查條件

int vacation;
cin>>vacation;
while(vacation>2)
{
  cout<<"yeah";
  cin>>vacation;
}
int vacation;
do
{
  cout<<"yeah";
  cin>>vacation;
}
while(vacation>2);

記得加分號!

默認條件符合 直接執行程式

break/continue

 

跳脫迴圈好夥伴

break的小檔案

可用在while迴圈跟for迴圈

表強制結束該迴圈

搭配條件判斷使用

continue的小檔案

可用在while迴圈跟for迴圈

表強制結束此次迴圈循環

搭配條件判斷使用

#include<iostream>
using namespace std;
int main()
{
  for(int num=1;num<10;num++)
  {
    if(num==5)
    {
      break;
    }
    cout<<num<<endl;
  }
}
#include<iostream>
using namespace std;
int main()
{
  for(int num=1;num<10;num++)
  {
    if(num==5)
    {
      continue;
    }
    cout<<num<<endl;
  }
}

論兩者的差距

輸出1 2 3 4

因為當num=5的時候break

略過下面的cout跳出迴圈

輸出1 2 3 4 6 7 8 9

因為當num=5的時候continue

略過下面的cout回到條件判斷

回到這行

繼續迴圈

迴圈

By ㄌㄌ

迴圈

  • 60