C Decision Making - Looping

The Do while statement

The do while loop is also a kind of loop, which is similar to the while loop in contrast to while loop, the do while loop tests at the bottom of the loop after executing the body of the loop.
Since the body of the loop is executed first and then the loop condition is checked we can be assured that the body of the loop is executed at least once.
The syntax of the do while loop is: 
	Do 
	{ 
		statement; 
	} while (expression); 				
        


Syntax description

Here the statement is executed, then expression is evaluated. If the condition expression is true then the body is executed again and this process continues till the conditional expression becomes false.
When the expression becomes false the loop terminates. To realize the usefulness of the do while construct consider the following problem.
The user must be prompted to press Y or N. In reality the user can press any key other than y or n. Also it has to be executed at least once. The following program illustrates the solution.


The Do while statement

/* Program to illustrate the do while loop*/ 
#include < stdio.h > //include stdio.h file to your program 
void main() // start of your program 
{ 
        char inchar; // declaration of the character 
		do // start of the do loop 
		{ 
		      printf(“Input Y or N”); //message for the user 
			  scanf(“%c”, &inchar); // read and store the character 
	    } while(inchar!=’y’ && inchar != ‘n’); //while loop ends 
		if(inchar==’y’) // checks whther entered character is y 
		     printf(“you pressed y\n”); // message for the user 
		else 
		     printf(“You pressed n\n”); } //end of for loop 
        


Make Comments..!!


Oops!! No posts from user.

Download Android App