Welcome to pickSourcecode.com Login | Register    
pickZy.com
 Home  | search  | games  | General  | C  | C++  | Java  | Php  | Networking  | Visual Basic  | VC++  | Win32  | MFC  | JavaScript  | Jobs  | JavaScript  | Post jobs
C - Loops - While and Do While       Share
2008-07-18 |  RatheeshTR  | Viewed: 457  |    2

This lesson will show you how to:

  • Use the while loop
  • Use the do-while loop


Loops -- While:
We have already encountered the While and for loops. In

While ( expression )
statements

while

The while loop is used to execute a block of code as long as some condition is true. If the condition is false from the start the block of code is not executed at al. The while loop tests the condition before it's executed so sometimes the loop may never be executed if initially the condition is not met. Its syntax is as follows.

while (tested condition is satisfied)
{
block of code
}

While Example

	x = 0;
while (x < 3)
{
x++;
}

Example program:

/* Sample program including the while loop */

#include

int main(void)
{

int loop = 0;

while (loop <=10)
{
printf(“%d”, loop);
++loop
}

return 0;

}

Sample program output

0
1

10



Do While:

The do-while loop is an exit-condition loop. This means that the body of the loop is always executed first. Then, the test condition is evaluated. If the test condition is TRUE, the program executes the body of the loop again. If the test condition is FALSE, the loop terminates and program execution continues with the statement following the while.

"do ....while" loops syntax is as follows

do
{
block of code
} while (condition is satisfied);


The do while statement

The do {} while statement allows a loop to continue whilst a condition evaluates as TRUE (non-zero). The loop is executed at least once

/* Demonstration of the do…..while loop */

#include

int main(void)
{

int value, r_digit;

printf(“Enter a number to be reversed.\n”);
scanf(“%d”, &value);

do
{
r_digit = value % 10;
printf(“%d”, r_digit);
value = value / 10;
} while (value != 0);

printf(“\n”);

return 0;


}


Latest topics
C - Arrays of structures  Viewed: 285
C - structures and functions  Viewed: 292
tcpdump by host name or ip  Viewed: 292
C - For loop statements  Viewed: 295
C - pointers and Arrays  Viewed: 295
C - File Access  Viewed: 295
C - pointers to pointers  Viewed: 296
C - Register variables  Viewed: 297
C - Pass-by-reference parameters  Viewed: 299
C - Static variables  Viewed: 299

Comments:





Submit comment's

Type:

User Comment's:

Submitted By:
Prof: Software Engineer
Tech: C ,Cpp
Send Mail: ratheesh



Related topics
C - Static variables
C - Local and global variables
C - Register variables

Related References
c - static variables
c - global and internal variables
c - global variables , static variables

Web site contents © Copyright 2007, All rights reserved.
Help | Terms and Conditions | Privacy Policy | About Us