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");
}
}
}
C
#include
int main()
{
int i = 5;
do {
printf("GFG\n");
i++;
} while (i < 10);
return 0;
}
C++
#include
using namespace std;
int main()
{
int i = 5;
do {
i++;
cout << "GFG\n";
} while (i < 10);
return 0;
}
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 5;
do {
i++;
System.out.println("GfG");
} while (i < 10);
}
}
输出:
GFG
GFG
GFG
GFG
GFG
do-while 循环:
do while 循环类似于while 循环,唯一的区别是它在执行语句后检查条件,因此是退出控制循环的一个示例。
句法:
do
{
statements..
}
while (condition);
流程图:
例子:
C
#include
int main()
{
int i = 5;
do {
printf("GFG\n");
i++;
} while (i < 10);
return 0;
}
C++
#include
using namespace std;
int main()
{
int i = 5;
do {
i++;
cout << "GFG\n";
} while (i < 10);
return 0;
}
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 5;
do {
i++;
System.out.println("GfG");
} while (i < 10);
}
}
输出:
GFG
GFG
GFG
GFG
GFG
这是差异表:
while | do-while |
---|---|
Condition is checked first then statement(s) is executed. | Statement(s) is executed atleast once, thereafter condition is checked. |
It might occur statement(s) is executed zero times, If condition is false. | At least once the statement(s) is executed. |
No semicolon at the end of while. while(condition) |
Semicolon at the end of while. while(condition); |
If there is a single statement, brackets are not required. | Brackets are always required. |
Variable in condition is initialized before the execution of loop. | variable may be initialized before or within the loop. |
while loop is entry controlled loop. | do-while loop is exit controlled loop. |
while(condition) { statement(s); } |
do { statement(s); } while(condition); |
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程。