NIOS Computer Science: Chapter 9 – Control Statements Part 7

Download PDF of This Page (Size: 240K)

Image of while loops

Image of While Loops

Image of while loops

while loop

Syntax of while loop

while (condition)

{

statement(s);

}

Image of while loop

Image of While Loop

Image of while loop

The flow diagram indicates that a condition is first evaluated. If the condition is true, the loop body is executed and the condition is re-evaluated.

Hence, the loop body is executed repeatedly as long as the condition remains true. As soon as the condition becomes false, it comes out of the loop and goes to the statement next to the ‘while’ loop.

To make it more clearly, we take the following example.

Example

To find the sum of first ten natural numbers i.e.

# include <iostream.h>

void main ( )

{

int n, total = 0 ;

n = 1 ;

while (n < = 10)

{

total + = n ;

n + + ;

}

cout << “sum of first ten natural number” << total :

}

The variable n is called a loop control variable since its value is used to control loop repetition. Normally, the three operations listed below must be performed on the loop control variable.

(1) Initialize the loop control variable

(2) Test the loop control variable

(3) Update the loop control variable

Operation:

(i) Must be performed before the loop is entered. Operation.

(ii) Must be performed before each execution of the loop body; depending on the result of this test, the loop will either be repeated or make an exit. Operation

(iii) Must be included as part of the loop body. Unless the loop control variable is updated in the loop body, its value cannot change and loop exit will never occur.