while loop statement
- flow chart
-
Instructions
while (condition) {
Statement 1
Statement 2
if(XXX){
break;
}
if(XXX){
continue;
}
…
}
-
The role of break
Jump out of the loop you are in.
-
coutinue
End this cycle and enter the next cycle
-
Example: 1 + 2 + 3 +… + 100
#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
int main(void) {
int i = 1;
int s = 0;
while (i<=100) {
s += i;
i++;
}
cout << "s=" << s << endl;
system("pause");
return 0;
}
for loop statement
- flow chart
-
Instructions
for (expression 1; expression 2; expression 3) {
Loop body
}
-
Description:
Expression 1: Prepare for the loop
Expression 2: Loop condition
Expression 3: Change the loop count
-
note:
Expression 1, Expression 2, Expression 3, any one or more of these 3 expressions can be omitted!
But the ";" cannot be omitted!
-
for (; ; ) {
Loop body
}
Is equivalent to:
while (1) {
Loop body
}
-
Example: 1 + 2 + 3 +… + 100
#include <iostream>
using namespace std;
//后羿射日
int main(void) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum = sum + i;
}
cout << sum << endl;
return 0;
}
do while loop statement
- flow chart
-
Use occasion:
Execute the loop body once, and then judge the conditions to determine whether to continue the next round of loop!
That is: execute the loop body at least once!
-
Instructions
do {
Loop body
} while (condition)
-
Example: 1 + 2 + 3 +…+100
#include <iostream>
using namespace std;
int main(void) {
int s = 0;
int i = 1;
do {
s += i;
i++;
} while(i<=100);
cout << s << endl;
return 0;
}
Control statements in the loop break continue
-
break
End this layer of loop.
-
continue
End this cycle and enter a cycle