Syntax
// syntax
while (expression)
statement;
// or
while (expression) {
statement(s);
}
์ค์ํ ์ ์ infinite loop์ด ๋์ง ์๋๋ก ์ ๊ฒฝ์ฐ๋ ๊ฒ์ ๋๋ค.
Example Codes
// Example 1
#include <iostream>
using namespace std;
int main(){
int i {1};
while (i <= 5) {
cout << i << endl;
i++;
}
}
/*
Output:
1
2
3
4
5
*/
i++๋ฅผ ํตํด loop 1๋ฒ๋น i๋ฅผ 1์ฉ ์ฆ๊ฐ์ํค์ง ์๋๋ค๋ฉด,
i๋ฅผ ์ด๊ธฐํ๋์ ๊ฐ 1์ ๋จธ๋ฌผ๋ฌ ์์ ๊ฒ์ด๊ณ ,
while๋ฌธ์ ์กฐ๊ฑด์์ ์์ํ ๋ฒ์ด๋ ์๊ฐ ์์ผ๋
1์ ๋ฌดํ์ผ๋ก ์ถ๋ ฅํ๋ ํ๋ก๊ทธ๋จ์ด ๋ ๊ฒ์ ๋๋ค.
// Example 2
// while loop ๋ด๋ถ์์ if๋ฌธ ์์ฑ
#include <iostream>
using namespace std;
int main(){
int i {1};
while (i <= 10) {
if (i % 2 == 0)
cout << i << endl;
i++;
}
}
/*
Output:
2
4
6
8
10
*/
// Example 3
// while loop for vector
#include <iostream>
using namespace std;
int main(){
vector<int> my_nums {10, 100, 1000};
int i = 0;
while (i < my_nums.size()){
cout << my_nums[i] << endl;
i++;
}
}
/*
Output
10
100
1000
*/
// Example 4
// using boolean for while loop
#include <iostream>
using namespace std;
int main(){
bool done {false};
int num {0};
cout << "Enter a number between 1 and 5: ";
cin >> num;
while (num <= 1 || num >= 5) {
cout << "Out of range.\nEnter a number between 1 and 5 again: ";
cin >> num;
}
cout << "You entered " << num << ", which is in between 1 and 5." << endl;
cout << "Thank you!" << endl;
}
/*
Output
Enter a number between 1 and 5 again: 5
Out of range.
Enter a number between 1 and 5 again: 100
Out of range.
Enter a number between 1 and 5 again: 3
You entered 3, which is in between 1 and 5.
Thank you!
*/
// Example 5
// using boolean and if in while loop
#include <iostream>
using namespace std;
int main(){
int num {};
cout << "Enter a number in between 1 and 5: ";
cin >> num;
bool done = false;
while (!done){
if (num <= 1 || num >= 5) {
cout << "\nYou entered " << num << endl;
cout << "Out of range. Please re-enter a number between 1-5: ";
cin >> num;
}else{
cout << "\nYou entered " << num << endl;
cout << "Thank you for entering a valid number." << endl;
done = true;
}
}
}
/*
Output:
Enter a number in between 1 and 5: 10
You entered 10
Out of range. Please re-enter a number between 1-5: 1
You entered 1
Out of range. Please re-enter a number between 1-5: 5
You entered 5
Out of range. Please re-enter a number between 1-5: -5
You entered -5
Out of range. Please re-enter a number between 1-5: 3
You entered 3
Thank you for entering a valid number.
*/
'C++ > ๋ฐ๋ณต๋ฌธ (Loop)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C++] do-while Loop (0) | 2023.12.12 |
---|---|
[C++] Range-based for Loop (0) | 2023.12.10 |
[C++] Conditional Operator (์กฐ๊ฑด ์ฐ์ฐ์) (2) | 2023.12.08 |