|Lessons||Lesson 6: Repetition Structures 1 (while Loops)|
while ( Logical Expression )
The logical expression contains a logical or relational operator. While this logical expression is true, the statements will be executed repeatedly. When this logical expression becomes false, the statements within the while block, will not be executed. Rather the next statement in the program after while block, will be executed.
/* This program calculate the
sum of first 1000 integers */
//Initialization of the variables
We can change the condition in the above code to 10000 or even more. Just try some more numbers. How far can you go with the limit? We know that integers are allocated a fixed space in memory (i.e. 32 bits in most PCs) and we can not store a number which requires more bits than integer, into a variable of data type, int. If the sum of integers becomes larger than this limit (i.e. sum of integers becomes larger than 32 bits can store), two things can happen here. The program will give an error during execution, compiler can not detect such errors. These errors are known as run time errors. The second thing is that 32 bits of the result will be stored and extra bits will be wasted, so our result will not be correct as we have wasted the information. This is called overflow. When we try to store larger information in, than a data type can store, overflow condition occurs. When overflow condition occurs either a run-time error is generated or wrong value is stored.
Consider the condition in the while structure that is (number <= 1000) and in the while block the value of number is changing (number = number + 1) to ensure that the condition is tested again next time. If it is true, the while block is executed and so on. So in the while block statements, the variable used in condition must change its value so that we have some definite number of repetitions. What will happen if we do not write the statement number = number + 1; in our program? The value of number will not change, so the condition in the while loop will be true always and the loop will be executed forever. Such loops in which the condition is always true are known as infinite loops as there are infinite repetitions in it.
Property of while loop:
The property of while loop is that it may execute zero or more time. The while loop is terminated, when the condition is tested as false.
NEXT>>>>>Lesson 7. Repetition Structures 2 (do-while Loops)