Thursday, August 28, 2014

The do-while Loop Structure

The do-while repetition structure is similar to the while structure. In the while structure, the program tests the loop-continuation condition at the beginning of the loop, before performing the body of the loop. The do-while structure tests the loop-continuation condition after performing the body of the loop; therefore, the loop body always executes at least once. When a do-while structure terminates, execution continues with the statement after the while clause. Note that it is necessary to use braces in the do-while structure if there is only one statement in the body. However, most programmers include the braces, to avoid confusion between the while and do-while structure. For example,

while ( condition )

normally is the first line of a while structure. A do-while structure with no braces around a single-statement body appears as

do
      statement
while ( condition );

which can be confusing. Reader may misinterpret the last line- while (condition ); - as a while structure containing an empty statement (the semicolon by itself). Thus, to avoid confusion, the do-while structure with one statement often is written as follows:

do{
  statement
} while ( condition );


Example:

int i = 1;
do{
   cout << (i++) << endl;
}while (i <= 10);

will display the following pattern:
1
2
3
4
5
6
7
8
9
10

Do it yourself:

Problem #1:
Write a program to display the following pattern using do-while loop structure:
0 3 6 9 12 15 18 21

Answer:
int i = 0;
do{
  cout << i << " ";
  i+=3;
}while ( i <= 21);


Problem #2:
Translate the following code snippet using a do-while structure:

int i=1;
while ( i <= 5){
   cout << i << " ";
   i++;
}

Answer:
int i=1;
do{
  cout << i << " ";
  i++;
}while (i <=5);

*************************************************

Lab Activity No. 2
Midterm

Problem:
Write a program to display a multiplication table using do-while loop.

Expected output:
12345678910
2468101214161820
36912151721242730
481216202428323640

Note: I will check your program on Tuesday next week.


Check some Viral Stuff and Trending News.

No comments:

Post a Comment