Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Theaboveprogramreversesanumberthatisenteredbytheuser.Itdoesthisbyusingthemodulus%operatorto
extracttherightmostdigitintothevariabler_digit.Theoriginalnumberisthendividedby10,andtheoperation
repeatedwhilstthenumberisnotequalto0.
Itisourcontentionthatthisprogrammingconstructisimproperandshouldbeavoided.Ithaspotentialproblems,and
open in browser PRO version
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
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.
pdfcrowd.com