+ 1
plz explain the while loop.
I do not know about while loop. Plz explain the use and its difference with other loops.
3 odpowiedzi
+ 7
Since tag contains C++ , I am going to use examples in C++, but the while loop can be applied to Javascript I believe.
While loop works this way :
while (condition)
{
//CodeA
}
//CodeB
If the condition is true, CodeA will be executed. Once CodeA reaches it's end, it will go back and test it's condition again. If true, it will execute CodeA again. Once condition becomes false or fails, it will then 'remove' the while code and continue on from CodeB.
For example , I want to make a code that prints out the value of 1-5.
int a = 1;
while ( a != 6 )
{
cout << a << endl;
a++;
}
Try copying and pasting this into the code playground for C++, it will output the values of 1-5.
From that example, you can see that everytime 'a' is not equals to 6, the current value of 'a' will be printed onto the console and afterwards added by 1. This process will stop when 'a' is equals to 6, where it fails the condition inside the while loop of "When 'a' is not equals to 6".
From this example, you can also observe one important factor :
You need to remember to create something to exit to loop, if not, an infinite loop will occur.
+ 3
While loop is much related to if block with a loop. In if block you check the condition and if condition is true it excute code in if block. So as while loop it check condition at every time. if a condition is true in while loop then it excute code in it. Because it is a loop you have to define a range in which it should be true and apart from that it return false. If you not do that it will be an infinite loop. And in some compiler if stack memory in ram is full. it give you an error. You can define while loop as for loop with one condition. like
int x=0;
for(;x<5;)
{
x++;
}
it is same as while loop. It only have the condition statement. if you not show an increment or decrement or some change in variable given in condition, like x is given as a condition in for loop. And if you not change value of x in every or any loop run than it will be an infinite loop.
You can create a while loop like loop using goto and if condition. Like I am showing you above example
int x=0;
state:
x++;
if(x<5)
{
goto state;
}
above will show you a loop. without a loop.
+ 1
thank-you for your answer aditya and k2 shape