Computer Science, asked by pavneet96, 11 months ago

write a note on while loop​

Answers

Answered by anirudhdalal16
1

In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

Answered by Hacket
0
A while is a conditional -- just like an if -- except that a while keeps executing its internal code as long as the condition remains true.

Given a variable of x with a value of 1, consider the following conditional:

if ( x < 5 ) { x = x + 1; }

Since x is less than 5, the if condition is true and so the gate is passed and the expression within the conditional will execute, therefore adding 1 to the variable value of x to make it equal to 2.

However, with one small difference, something else happens:

while ( x < 5 ) { x = x + 1; }

Since x is less than 5, the while condition is true and so the gate is passed and the expression within the conditional will execute... and then execute again... and again and again, until such a time that x becomes equal to 5 (which is no longer less than 5).

A while loop like this is a convenient way to execute some code for a certain number of times, for instance to create the 64 squares of a chess board.

However, it is very important for the while condition to contain something that is being affected by the expressions within. Otherwise, the while could continue on forever. This is a common mistake, and usually the reason why a for condition is used instead of a while.

A for loop is essentially the same as a while loop except that it includes all the ingredients that should make is safe from running on forever: the conditional variable, the while condition, and then the increment of the conditional variable (in the following example, x++ is the same as x = x + 1):

for ( x = 1; x < 5; x++ ) { /* do something 4 times */ }

In programming, you will find the for loop almost everywhere. It is very common, and very safe.

Thanks for asking
Similar questions