for循环:
for 循环提供了一种编写循环结构的简洁方法。与 while 循环不同,for 语句在一行中使用初始化、条件和递增/递减,从而提供更短、更易于调试的循环结构。
句法:
for (initialization condition; testing condition;
increment/decrement)
{
statement(s)
}
流程图:
例子:
C
#include
int main()
{
int i = 0;
for (i = 5; i < 10; i++) {
printf("GFG\n");
}
return 0;
}
C++
#include
using namespace std;
int main()
{
int i = 0;
for (i = 5; i < 10; i++) {
cout << "GFG\n";
}
return 0;
}
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 0;
for (i = 5; i < 10; i++) {
System.out.println("GfG");
}
}
}
C
#include
int main()
{
int i = 5;
while (i < 10) {
printf("GFG\n");
i++;
}
return 0;
}
C++
#include
using namespace std;
int main()
{
int i = 5;
while (i < 10) {
i++;
cout << "GFG\n";
}
return 0;
}
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 5;
while (i < 10) {
i++;
System.out.println("GfG");
}
}
}
输出:
GFG
GFG
GFG
GFG
GFG
while循环:
while 循环是一种控制流语句,它允许根据给定的布尔条件重复执行代码。 while 循环可以被认为是一个重复的 if 语句。
句法 :
while (boolean condition)
{
loop statements...
}
流程图:
例子:
C
#include
int main()
{
int i = 5;
while (i < 10) {
printf("GFG\n");
i++;
}
return 0;
}
C++
#include
using namespace std;
int main()
{
int i = 5;
while (i < 10) {
i++;
cout << "GFG\n";
}
return 0;
}
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 5;
while (i < 10) {
i++;
System.out.println("GfG");
}
}
}
输出:
GFG
GFG
GFG
GFG
GFG
这里有一些区别:
For loop | While loop |
---|---|
Initialization may be either in loop statement or outside the loop. | Initialization is always outside the loop. |
Once the statement(s) is executed then after increment is done. | Increment can be done before or after the execution of the statement(s). |
It is normally used when the number of iterations is known. | It is normally used when the number of iterations is unknown. |
Condition is a relational expression. | Condition may be expression or non-zero value. |
It is used when initialization and increment is simple. | It is used for complex initialization. |
For is entry controlled loop. | While is also entry controlled loop. |
for ( init ; condition ; iteration ) { statement(s); } |
while ( condition ) { statement(s); } |