by Dinesh Thakur Category: Control Structures

As a good programming practice, we display a message to prompt the user before accepting data from the keyboard. This enables the user to enter the required data correctly. However, the user may still enter incorrect data. Such data may cause the programs to print incorrect results.

One way to handle this problem is to print an error message and stop the program execution when incorrect data is encountered. However, the user will usually expect the program to discard incorrect data and allow him/her to reenter correct data. We can implement code to achieve this using a do...while loop. Consider the program segment given below.

do

printf ("Enter marks (0..100): ");

scanf("%d", &marks);

while (marks< 0 || marks> 100);

This loop prints a message and accepts marks from the keyboard as long as the marks entered are incorrect (either less than zero or greater than l 00). The control leaves the loop only when the user enters valid marks (in the range 0 to 100). The output is shown below, where the user has entered two incorrect values (120 and -20) before entering the correct value (90).

Example:

#include <stdio.h>

void main()

{

    int marks;

    clrscr();

    do

    {

         printf ("Enter marks (0..100): ");

         scanf("%d", &marks);

     }  while (marks< 0 || marks> 100);

   

    printf ("The Marks = %d \n",marks);

    getch();

}



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content







Popular Article