The syntax of while construct is as under:

                  while ( Logical Expression ) {

                             statement1;

                              statement2;

                              ………….

                   }

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.

Let’s discuss again the same problem i.e. calculation of the sum of first 1000 integers starting from 1. For this purpose, we need a variable to store the sum of integers and declare a variable named sum. Always use the self explanatory variable names. The declaration of the variable sum in this case is:

                         int sum = 0;

The above statement has performed two tasks i.e. it declared the variable sum of type int and also initialized it with zero. As it is good programming practice to initialize all the variables when declared, the above statement can be written as:

                  int sum;

                  sum = 0;

Here we need a variable to store numbers. So we declare a variable number of type int. This variable will be used to store integers.

                  int number;

 

 

Previous

 

TOC

 

Next