📜  C,C++, Javawhile和do-while循环之间的区别

📅  最后修改于: 2021-05-30 12:11:28             🧑  作者: Mango

while循环:

while循环是一个控制流语句,它允许根据给定的布尔条件重复执行代码。 while循环可被视为重复的if语句。
句法 :

while (boolean condition)
{
   loop statements...
}

流程图:
while循环

例子:

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循环相似,唯一的区别是执行语句后检查条件,因此是Exit Control循环的一个示例

句法:

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等的更多准备工作,请参阅“完整面试准备课程”