當我們想要連續輸出5次HelloWorld,但又不想要打5次同樣的程式碼
需要不斷執行相同的程式碼,這時候就是迴圈登場的最佳時機
loop-迴圈
while (condition)
statement;當條件為真時,執行敘述,直到條件為false時,while迴圈才會停止,和if一樣當敘述只有一行時可省略{}
while loop
int i = 5;
while(i != 0)
{
cout << "HelloWorld!\n";
i -= 1;
}題目: 輸入 j,計算 5 的倍數中不小於 j 的最小值?
int i = 5;
while(i--)
cout << "HelloWorld!\n";#include <iostream>
using namespace std;
signed main()
{
int j;
cin>>j;
int i = 0;
while(i<j)
i += 5;
cout<<i;
}For loop
for(初始化;執行條件;調整)
{
statements;
}for(int i = 0; i < 5; i++){
cout << i << endl;
}ex: 輸出0到4
for(int i=0;i<n;i++)
{
cout<<i<<" ";
}i如果在for迴圈裡宣告,則迴圈結束後i會消失
注意初始化的值和停止條件有沒有=,小心迴圈的次數少跑或多跑
int i = 0;
for(i; i < 50; i = i * 2)
cout << i << " ";
cout << i << "\n";
for(int j = 100; j > 0; j = j / 2)
cout << j << " ";
cout << j << "\n";zerojudge c022. 10783 - Odd Sum
int main(){
int j = 4;
{
int i = 3;
}
cout << j <<"\n";
cout << i <<"\n";
return 0;
}Block Scope { }
只要變數是在 { } 大括號中宣告的,就只在那個區塊內有效。
#include <iostream>
using namespace std;
signed main()
{
int n=73;
bool prime=true;
for(int i=2;i*i<=n;i++)
{
if(n%i==0)
prime=false;
}
cout<<prime;
}ex:
3 4
***
***
***
***
Nested Loop
int x, y;
cin >> x >> y;
for(int i = 0; i < x; i++)
{
for(int j = 0; j < y; j++)
{
cout << "*";
}
cout <<"\n";
}
練習:印出九九乘法表
練習:d649. 數字三角形
int password = 12345678
int i = 0;
while(i < 3)
{
i++;
int input;
cin >> input;
if(input == password)
cout << "correct\n";
else
cout << "wrong\n";
}break;
希望提早結束整個迴圈,可以使用break;
while()
{
if(conditioin)
break;
}
for()
{
if(conditioin)
break;
}int password = 12345678
int i = 0;
while(i < 3)
{
i++;
int input;
cin >> input;
if(input == password)
{
cout << "correct\n";
break;
}
else
cout << "wrong\n";
}continue;
希望跳過迴圈剩下的部分時使用
#include <iostream>
using namespace std;
signed main()
{
int n=10,sum=0;
for(int i=0;i<n;i++)
{
int tmp;
cin>>tmp;
if(tmp < 0)
continue;
sum += tmp;
}
cout<<sum;
}注意在迴圈裡宣告的tmp和i一樣在迴圈外無法使用。
#include <iostream>
using namespace std;
signed main()
{
int n=73;
bool prime=true;
for(int i=2;i*i<=n;i++)
{
if(n%i==0)
{
prime=false;
break;
}
}
cout<<prime;
}其實也可以不用到break;
for(int i=2;i*i<=n && prime;i++)while(cin>>a>>b)
{
statements;
}直到輸入結束或輸入錯誤為止。
按Ctrl+D來表示輸入結束(EOF)
int a = -1;
while(cin>>a)
{
cout<<a*4<<"\n";
}
題目練習
do while迴圈,寫題目幾乎不會用但觀念題會考
do {
statement1;
statement2;
statement3;
} while (cond);
會先執行一次do裡面的敘述,然後到while時判斷,如果條件為真則繼續執行
int n=5;
do {
cout<<"n==4";
} while (n==4);