{for-while loop​}

espc 社長兼教學 林馥唯

{for-while loop​}

espc 社長兼教學 林馥唯

Print 1 to 10 ???

# PRESENTING CODE

You can do like this 

#include <iostream>

using namespace std;

int main()
{
    cout <<"1 2 3 4 5 6 7 8 9 10 ";
    return 0;
}

How about do like this!

# PRESENTING CODE
#include <iostream>

using namespace std;

int main()
{
    for (int i=1;i<=10;i++){
        cout<<i<<" ";
    }
    return 0;
}

It just look like...

# PRESENTING CODE

How about print 1 to 10000??

# PRESENTING CODE
int main()
{
    cout <<"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36"
    return 0;
}

How about print 1 to 10000??

# PRESENTING CODE
int main()
{
    cout <<"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36"
    return 0;
}
# PRESENTING CODE

遞增/遞減 運算子

# PRESENTING CODE

\

# PRESENTING CODE

While Loop

#include <iostream>

using namespace std;

int main()
{
    while (condition){
        do something;
    }
    return 0;
}

So how to use while loop to print 1~10000

# PRESENTING CODE
#include <iostream>

using namespace std;

int main()
{
    int cnt = 1;
    while (cnt<=10000) {
    cout<<cnt<<" ";
    cnt++;
    }

    return 0;
}

<key>while loop內 變數值必須更新

 

# PRESENTING CODE

Do-while loop

#include <iostream>

using namespace std;

int main()
{
   do{
	    do somthing
    }while(condition);

    return 0;
}
# PRESENTING CODE

Do-while V.S. While

continue/break

# PRESENTING CODE
# PRESENTING CODE

For Loop

#include <iostream>

using namespace std;

int main()
{
   for (initial;condition;change){
       do something;
   }

    return 0;
}

For Loop

# PRESENTING CODE

for (初始值;檢查條件;調整){

執行敘述

}

1.用;相隔

2.需有初始化

3.執行迴圈之條件

4.注意i之生命週期

While v.s. for

# PRESENTING CODE
#include<iostream>
using namespace std;
int main(){
    int cnt = 1;
    while (cnt<=100) {
        cout << cnt  << endl;
        cnt++;
    }
    return 0;
}
#include<iostream>
using namespace std;
int main(){
	for(int cnt = 1;cnt<=100;cnt++){
		cout << cnt << endl;
	}
	return 0;
}
# PRESENTING CODE

choose for or while 

<key>是否知道迴圈運作次數

while 

用於不知迴圈所需運作次數

=>吃輸入直到 EOF

for

用於知道迴圈所需運作次數

=>已知有 n 個數字要輸入

Practice

 

ZeroJudge a058: MOD3 Link

 

ZeroJudge d074: 電腦教室 Link

Q&A

Thanks for your listening!

Made with Slides.com