+ 1
Please explain the while loop.
I could not properly understand the while loop.
2 Answers
+ 10
First let's define a loop. It repeats until a stopping condition is met.
e.g
⢠Let's play until sunset
⢠Let's keep dancing till the song ends
In these cases the stopping condition are the sunset and the music stopping.
We can rephrase those statements using the word while for your understanding
â˘While the sun is up, let's play
â˘While the song is playing, let dance
In Code:
â˘While(sun!=set)
{
play();
}
//Assuming the song is 1200s
â˘while(musicduration<1200)
{
dance();
musicduration++; /*Increase by 1s*/
}
And that's how the while loop works. It repeats statements until a stopping condition is met in the second case . If the condition is not met. It results in an infinite loop.
0
while loop is a loop which runs till the condition given to it doesn't get false or invalid.
while loop can be used to create infinite loop for embedded programing.
HoW it works
while loop just check its condition first
eg.
int number=8;
while(number<= 4)
{
statements;
--------;
---------;
}
now in above code
now in above code the while loop execute its statements under the curly braces and then it will again checking condition whether it is true or not if it is true then it will again and again execute it's loop until unless the condition written next to the while becomes false.
to terminate while loop you should have some changes in the condition of while under its own body.
otherwise it can lead to infinite loop.