📜  C、C++、 Javafor 和 do-while 循环的区别

📅  最后修改于: 2021-09-13 02:08:07             🧑  作者: Mango

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;
  
    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

这是差异表:

For loop Do-While loop
Statement(s) is executed once the condition is checked. Condition is checked after the statement(s) is executed.
It might be that statement(s) gets executed zero times. Statement(s) is executed at least once.
For the single statement, bracket is not compulsory. Brackets are always compulsory.
Initialization may be outside or in condition box. Initialization may be outside or within the loop.
for loop is entry controlled loop. do-while is exit controlled loop.
for ( init ; condition ; iteration )
{ statement (s); }
do { statement(s); }
while (condition);