Está en la página 1de 3

C Programming

THE DO WHILE STATEMENT


Thedo { } whilestatementallowsalooptocontinuewhilstaconditionevaluatesasTRUE(non-zero).Theloopis
executedasleastonce.
/*DemonstrationofDO...WHILE*/
#include<stdio.h>
main()
{
intvalue,r_digit
printf("Enterthenumbertobereversed.\n")
scanf("%d",&value)
do{
r_digit=value%10
printf("%d",r_digit)
value=value/10
}while(value!=0)
printf("\n")
}

Theaboveprogramreversesanumberthatisenteredbytheuser.Itdoesthisbyusingthemodulus%operatorto
extracttherightmostdigitintothevariabler_digit.Theoriginalnumberisthendividedby10,andtheoperation
repeatedwhilstthenumberisnotequalto0.
Itisourcontentionthatthisprogrammingconstructisimproperandshouldbeavoided.Ithaspotentialproblems,and
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

youshouldbeawareofthese.
Onesuchproblemisdeemedtobelack of control.Consideringtheaboveprogramcodeportion,
do{
r_digit=value%10
printf("%d",r_digit)
value=value/10
}while(value!=0)

thereisNOchoicewhethertoexecutetheloop.Entrytotheloopisautomatic,asyouonlygetachoicetocontinue.
Anotherproblemisthattheloopisalwaysexecutedatleastonce.Thisisaby-productofthelackofcontrol.This
meansitspossibletoenterado { } whileloopwithinvaliddata.
Beginnerprogrammerscaneasilygetintoawholeheapoftrouble,soouradviceistoavoiditsuse.Thisistheonly
timethatyouwillencounteritinthiscourse.Itseasytoavoidtheuseofthisconstructbyreplacingitwiththefollowing
algorithms,
initialise loop control variable
while( loop control variable is valid ) {
process data
adjust control variable if necessary
}

Okay,letsnowrewritetheaboveexampletoremovethedo { } whileconstruct.
/*rewrittencodetoremoveconstruct*/

#include<stdio.h>

main()
{
intvalue,r_digit
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

value=0

while(value<=0){
printf("Enterthenumbertobereversed.\n")
scanf("%d",&value)

if(value<=0)

printf("Thenumbermustbepositive\n")

while(value!=0)
{
r_digit=value%10
printf("%d",r_digit)
value=value/10
}
printf("\n")
}

SampleProgramOutput
Enter the number to be reversed.
43
The number must be positive
Enter the number to be reversed.
423
324

CopyrightBBrown.1984-1999.Allrightsreserved.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

También podría gustarte