In: Computer Science
how to ensure the while loop will end correctly
To answer this we will look into how while loop works.
-While-Loop is also called as Condition-Controlled (i.e they
conitnue to loop until some condition is met).
- It is used normally when we want to repeat a secition of code for
unspecified number of times until the condition is met.
- One interesting thing is that while loop checks for the condition
first (i.e stopping condition) and if the condition is initially
false it may not even exceute the body at all.
Syntax:
while(condition)
{
body;
}
Now how to ensure the while loop will end correclty.
-So to ensure that it ends correctly we have to make sure that it meets the stopping condition. If it doesn't met the stopping condition that it will result into infinite loop which we don't want.
- So to meet the stopping condition we have to do either addition , subtraction , mulitplication or divison for the variable used in the condition until the stopping condition is met. (i.e condition becomes false)
For example let's take an example and understand it further.
int j = 0;
// Here checking the while-loop condition before entering the
loop
while( j < 5 )
//if it's true we will enter
{
printf( "j = %d\n",j++);
// Now how to meet the stopping condition for that we
have increment the value of j
}
printf( "After loop, j = %d\n", j );
#Note If need any help then ping me in the comments I will be glad to help you out ^_^ and If you liked the answer and explanation then please give a thumbs up I really need a +ve feedback at the moment.