Programming languages like Javascript, C++, C#, Python provides while loops
in order to iterate over the given list, array, set etc. while loop
is a very important part of the programming language because of its functionality. In this tutorial, we will examine and compare a while loop for programming languages like Javascript, C++, C#, and Python.
Javascript while loop
Javascript provides different syntax of while
loops. The general syntax is like below.
Only Condition
We just need to provide condition after the while
keyword.
while (CONDITION) {
CODE
}
In this example, we will increase the i
variable and check whether it is lower than 5.
while (i < 5){
text += "Value is " + i;
i++;
}
Condition After While Block
We can also define condition checks after the while block. This will ensure that the whole block will be executed at least one time and checked after execution.
do {
CODE
}
while (CONDITION);
In this example we will first increase the i
variable and then check whether its lower than 5
do{
text += "Value is " + i;
i++;
}while (i < 5);
C and C++ while loop
C and C++ programming languages are using very similar syntax. Their while
loop is very similar to the Javascript because Javascript derived some syntax from these languages.
Only Condition
We just need to provide condition after the while
keyword.
while (CONDITION) {
CODE
}
In this example, we will increase the i
variable and check whether it is lower than 5.
while (i < 5){
printf("Value is %d", i);
i++;
}
Condition After While Block
We can also define condition check after the while block. This will ensure that the while block will be executed at least one time and checked after execution.
do {
CODE
}
while (CONDITION);
In this example we will first increase the i
variable and then check whether its lower than 5
do{
printf("Value is %d", i);
i++;
}while (i < 5);
C# while loop
C# programming language uses very similar concepts of the C and C++ programming languages. We can use the following code in order to loop with a while. In this example, we will write i
variable value to the console and check whether it is lower than 5.
using System;
class Program
{
static void Main()
{
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
}
}
Do While
We can also implement the same logic with do while
operations.
using System;
class Program
{
static void Main()
{
int i = 0;
do
{
Console.WriteLine(i);
i++;
} while (i<= 5);
}
}
Python while loop
Python is a bit different language from other counterparts like Javascript, C, C++, and C#. Python uses indents as block specifiers so we will start while block with 3 spaces. In this example, we will check the variable i
if it is lower than 5 and then print it.
i = 1
while i < 5:
print(i)
i += 1