Loop 

by 芊竹

有一天,因為在老師面前罵了髒話,而被罰抄一千字的"我不說髒話"。那要怎麼辦呢?

A. 乖乖的抄囉,阿不然能怎樣?

B. 拿兩支筆同時抄

C. 叫同學幫我抄

電腦那麼厲害,可不可以幫一點忙阿?

((雖然老師會發現不是手寫的啦www

可以喔!!!

Loop in C++

可以重複執行相同指令

  • while loop
  • for loop
  • do-while

While Loop

while(/*條件為真*/){
  /*執行程式*/;
}

P.s.條件可以是「條件」,例如:10>9;

或是「數值」,例如1, 0 (非0即是true)

Example 1

試著印出1~100吧~中間要換行

int n=1;
while(n<=100){
  cout<<n<<'\n';
  n++;
}

Practice 1

A. 倒著印出1~100

B. 計算1到100之間的偶數和(含100)

100
99
98
97
96
95
…

2+4+6+8+…+96+98+100=?

Infinite Loop

電腦就會乖乖的一直做下去!

如果while的條件永遠都成立會發生什麼事呢?

while(1){
//非0即是true,因為1一直都是true,所以迴圈會一直跑下去
   cout<<"It's an infinate loop."
}

所以,通常會搭配continue和break使用

For Loop

for((宣告)初始化變數;條件;更新){
  執行
}
  • 小括號內的東西要用分號隔開
  • C語言不可在小括號內宣告

Example 2

試著印出1~100吧~中間要換行

for(int i=1;i<=100;i++){
  cout<<i<<'\n';
}
for((宣告)初始化變數;條件;更新){
  執行
}

Practice 2

A. 倒著印出1~100

B. 計算1到100之間的奇數和(含1)

100
99
98
97
96
95
…

1+3+5+7+…+95+97+99=?

Practice 3

小小提示:

上禮拜教的 / (除法),整數除法是取商。

例如:10/3=3

while loop

for loop

int n=1;
while(n<=100){
  cout<<n<<'\n';
  n++;
}
for(int n=1;n<=100;n++){
  cout<<n<<'\n'
}

初始化

條件式

更新值

Nested Loop

nested loop

for(int i=0;i<10;i++){
  for(int j=0;j<10;j++){
       cin>>a[i][j];
}
  • 迴圈裡面有迴圈
  • 常用在多為陣列的輸入輸入

Practice 3

想想看行數、列數分別應該填誰呢?

換行符號應該放在哪裡呢?

Break && Continue

Break

Continue

for(int i=0;i<10;i++){
   if(i==5)
   break;
   cout<<i<<" ";
}
// 0 1 2 3 4
for(int i=0;i<10;i++){
  if(i==5)
  continue;
  cout<<i<<" ";
}
//0 1 2 3 4 6 7 8 9

One-dimensional Array 

a

a[0]

a[1]

a[4]

a[3]

a[2]

int a[5];
for(int i=0;i<5;i++){
  cin>>a[i];
}

Practice 4

想法:

  1. 先開一個大小大於10的陣列
  2. 把數字輸入
  3. 反著輸出
#include <iostream>
using namespace std;
int main(){
  int a[11]=0;
  int n=0;
  cin>>n;
  for(int i=0;i<n;i++){
    cin>>a[i];
  }
  for(int i=n-1;i>=0;i--){
    cout<<a[i]<<" ";
  }
  return 0;
}

Multidimensional Array

row (列)

column (欄)

b[0][0]

b[0][1]

b[0][2]

b[1][0]

b[1][1]

b[1][2]

b

for(int i=0;i<2;i++){
  for(int j=0;j<3;j++)
    cin>>b[i][j];
}
Made with Slides.com