Java while 循环与示例
Java while 循环是一种控制流语句,它允许根据给定的布尔条件重复执行代码。 while 循环可以被认为是一个重复的 if 语句。当我们需要重复执行一个语句块时, Java中的 while 循环就派上用场了。 while 循环被视为重复的 if 语句。如果迭代次数不固定,建议使用while循环。
句法:
while (test_expression)
{
// statements
update_expression;
}
While 循环的各个部分是:
1. 测试表达式:在这个表达式中,我们要测试条件。如果条件评估为真,那么我们将执行循环体并转到更新表达式。否则,我们将退出 while 循环。
例子:
i <= 10
2. 更新表达式:执行循环体后,该表达式将循环变量增加/减少某个值。
例子:
i++;
While 循环如何执行?
- 控制落入while循环。
- 流程跳转到 Condition
- 条件经过测试。
- 如果 Condition 为真,则流量进入 Body。
- 如果 Condition 产生 false,则流程将超出循环
- 循环体内的语句被执行。
- 更新发生。
- 控制流回到步骤 2。
- do-while 循环已结束,流程已流出。
流程图对于while循环(控制流):
示例 1:该程序将尝试打印 5 次“Hello World”。
Java
// Java program to illustrate while loop.
class whileLoopDemo {
public static void main(String args[])
{
// initialization expression
int i = 1;
// test expression
while (i < 6) {
System.out.println("Hello World");
// update expression
i++;
}
}
}
Java
// Java program to illustrate while loop
class whileLoopDemo {
public static void main(String args[])
{
int x = 1, sum = 0;
// Exit when x becomes greater than 4
while (x <= 10) {
// summing up x
sum = sum + x;
// Increment the value of x for
// next iteration
x++;
}
System.out.println("Summation: " + sum);
}
}
输出
Hello World
Hello World
Hello World
Hello World
Hello World
时间复杂度: O(1)
辅助空间: O(1)
空运行示例 1:程序将以下列方式执行。
1. Program starts.
2. i is initialized with value 1.
3. Condition is checked. 1 < 6 yields true.
3.a) "Hello World" gets printed 1st time.
3.b) Updation is done. Now i = 2.
4. Condition is checked. 2 < 6 yields true.
4.a) "Hello World" gets printed 2nd time.
4.b) Updation is done. Now i = 3.
5. Condition is checked. 3 < 6 yields true.
5.a) "Hello World" gets printed 3rd time
5.b) Updation is done. Now i = 4.
6. Condition is checked. 4 < 6 yields true.
6.a) "Hello World" gets printed 4th time
6.b) Updation is done. Now i = 5.
7. Condition is checked. 5 < 6 yields true.
7.a) "Hello World" gets printed 5th time
7.b) Updation is done. Now i = 6.
8. Condition is checked. 6 < 6 yields false.
9. Flow goes outside the loop. Program terminates.
示例 2:该程序将求 1 到 10 的数字之和。
Java
// Java program to illustrate while loop
class whileLoopDemo {
public static void main(String args[])
{
int x = 1, sum = 0;
// Exit when x becomes greater than 4
while (x <= 10) {
// summing up x
sum = sum + x;
// Increment the value of x for
// next iteration
x++;
}
System.out.println("Summation: " + sum);
}
}
输出
Summation: 55
时间复杂度: O(1)
辅助空间: O(1)
相关文章:
- Java中的循环
- 带有示例的Java For 循环
- Java do-while 循环与示例
- C、C++、 Java中for和while循环的区别
- C、C++、 Java中while和do-while循环的区别