Você está na página 1de 7

4/4/2015

Bucles(ciclos)VisualBasic:ForNextStep,DoWhileLoop,Until.Ejemplosyejerciciosresueltos(CU00326A)

Inicio

Cmoempezar

Concenos

Cursos

Foros

Libros
Freelancers

Cursos

Empleo

Humor!!!

Divulgacin

Centrosformativos

CursoAprenderaprogramarenVisualBasicdesdecero

Bucles(ciclos)VisualBasic:ForNextStep,DoWhileLoop,Unt
Ejemplosyejerciciosresueltos(CU00326A)
EscritoporMarioR.Rancel

Resumen:Entregan25delcursoAprenderaprogramarenVisualBasicdesdecero.
Codificacinaprenderaprogramar.com:CU00326A

ESTRUCTURASDEREPETICIN(BUCLES)CONVISUALBASIC

Vamos a ver cmo materializar con Visual Basic estructuras de repeticin que permitirn que en nuestros programas se
proceso n veces. En concreto veremos las instrucciones Desde Siguiente (For Next) con su clusula Paso (Step), la
MientrasHacer(DoWhileLoop)ylainstruccinHacerRepetirMientras(DoLoopWhile).

Muchasvecespodremosoptarindistintamenteporusarunainstruccinuotra.Enotroscasos,esrecomendabledecantarse
ellasporhacerelprogramamslegibleosencilloqueusandootrasopciones.

http://aprenderaprogramar.com/index.php?option=com_content&view=article&id=263:buclesciclosvisualbasicfornextstepdowhileloopuntilejempl

1/7

4/4/2015

Bucles(ciclos)VisualBasic:ForNextStep,DoWhileLoop,Until.Ejemplosyejerciciosresueltos(CU00326A)

INSTRUCCINDESDE...SIGUIENTE(FOR...NEXT)YCLUSULAPASO(STEP)
LasintaxisaemplearconVisualBasiceslasiguiente:

ForVAR=ViToVf
Instruccin1
Instruccin2

Instruccinn
NextVAR

Elincrementoquesufreelcontadores,pordefecto,unitario.Esdecir,elprimervalorquetomaVARenelbucleserVi,el

+1,eltercero(Vi+1)+1,etc.LamodificacindedichovalordeincrementolarealizaremosatravsdelaclusulaStep
valorVf.Step2implicarqueencadarepeticindelbucleelcontadorseincrementeendosunidades,Step5implicarq

repeticindelbucleelcontadorseincrementeencincounidades.UnpasonegativodeltipoStep1suponequeelconta
envezdeincrementarse.Sielpasoesnegativo,VinecesariamentehabrdesermayorqueVf,yaqueencasocontrariono
laentradaenelbucle.
Conestecdigosenosmuestraenpantalla3veceshola(sehainvertidoelsentidodelbucle):

Cdigo(versionesVBmenos
recientes)

RemCursoVisualBasic
aprenderaprogramar.com
OptionExplicit
DimVARAsInteger
DimViAsInteger
DimVfAsInteger

PrivateSubForm_Load()
Vi=1
Vf=3
ForVAR=VfToViStep1
'[Tambinsupondratresrepeticiones
ForVAR=VitoVf]
MsgBox("hola")
NextVAR
EndSub

Cdigo(versionesVBmsrecientes)

REMCursoVisualBasicaprenderaprogramar.com
OptionExplicitOn

PublicClassForm1
PrivateSubForm1_Load(ByValsenderAsSystem.Object,ByValeAs
System.EventArgs)HandlesMyBase.Load
DimVARAsInteger
DimViAsInteger
DimVfAsInteger
Vi=1
Vf=3
ForVAR=VfToViStep1
'[TambinsupondratresrepeticionesForVAR=VitoVf]
MsgBox("hola")
NextVAR
EndSub
EndClass

ConVisualBasicresultaadmisibleusarNextsinindicarlavariablequeestsirviendodeguadelbucle,puestodobucleha
cierre.Sinembargo,nolocreemosrecomendablepuespuededificultarlalecturaydepuracindelosprogramas.
http://aprenderaprogramar.com/index.php?option=com_content&view=article&id=263:buclesciclosvisualbasicfornextstepdowhileloopuntilejempl

2/7

4/4/2015

Bucles(ciclos)VisualBasic:ForNextStep,DoWhileLoop,Until.Ejemplosyejerciciosresueltos(CU00326A)

LainstruccinFor...Nextesanidabledentrodesmismaodentrodeotrostiposdebuclesoestructuras,debiendosegu
queyahemoscomentado.

EJERCICIO

Transformar en cdigo el siguiente planteamiento: queremos generar un programa que pida un nmero del 1 al 10 y nos
tablademultiplicarcorrespondiente.

SOLUCIN

Hemos realizado la pregunta relativa al nmero cuya tabla se desea conocer utilizando un InputBox. Igualmente vlido h

hacerloconunLabelcontenedordelapreguntayunTextBoxdondeelusuariointroducelainformacin.Latablalamost
unLabeldenominadoLabelTabla.

Cdigo(versionesVBmenosrecientes)

RemCursoVisualBasic
aprenderaprogramar.com
OptionExplicit
DimTAsInteger
DimiAsInteger

PrivateSubForm_Load()
Form1.Caption="Tabla"
T=Val(InputBox("Qutablaquiere
conocer?"&vbCrLf&_
"(Introduzcaunnmerode1a10)",
"Nmero?"))
LabelTabla.FontBold=True
LabelTabla.Alignment=2
LabelTabla="TABLADEL"&T&vbCrLf&
vbCrLf
Fori=1To10
LabelTabla=LabelTabla&T&"*"&i&
"="&T*i&vbCrLf
Nexti
EndSub

Cdigo(versionesVBmsrecientes)

REMCursoVisualBasicaprenderaprogramar.com
OptionExplicitOn
PublicClassForm1
DimTAsInteger
DimiAsInteger

PrivateSubForm1_Load(ByValsenderAsSystem.Object,ByVale
System.EventArgs)HandlesMyBase.Load
Me.Text="Tabla"
T=Val(InputBox("Qutablaquiereconocer?"&vbCrLf&_
"(Introduzcaunnmerode1a10)","Nmero?"))
LabelTabla.Font=NewFont("Arial",10,FontStyle.Bold)
LabelTabla.TextAlign=ContentAlignment.MiddleCenter
LabelTabla.Text="TABLADEL"&T&vbCrLf&vbCrLf
Fori=1To10
LabelTabla.Text=LabelTabla.Text&T&"*"&i&"="&T*
vbCrLf
Nexti
EndSub
EndClass

Aspectogrfico:

http://aprenderaprogramar.com/index.php?option=com_content&view=article&id=263:buclesciclosvisualbasicfornextstepdowhileloopuntilejempl

3/7

4/4/2015

Bucles(ciclos)VisualBasic:ForNextStep,DoWhileLoop,Until.Ejemplosyejerciciosresueltos(CU00326A)

EJERCICIO

Transformarencdigoelsiguienteplanteamiento:queremosgenerarunprogramaquemuestretodoslosenteroscompren
unnmerodefinidoporelusuarioy100.

SOLUCIN

Cdigo(versionesVBmenosrecientes)

RemCursoVisualBasicaprenderaprogramar.com
OptionExplicit
DimNumAsInteger
DimiAsInteger
PrivateSubForm_Load()
Form1.Caption="Enteros"
Num=Val(InputBox("Introduzcaunnmeroentero
comprendidoentre1y99","Nmero?"))
LabelTabla.Alignment=2
LabelTabla.FontBold=True
LabelTabla="ENTEROSENTRE"&Num&"y100"&
vbCrLf&vbCrLf
Fori=NumTo100
LabelTabla=LabelTabla&i&""
Nexti

Cdigo(versionesVBmsrecientes)
REMCursoVisualBasicaprenderaprogramar.com
OptionExplicitOn
PublicClassForm1

PrivateSubForm1_Load(ByValsenderAsSystem.Obje
ByValeAsSystem.EventArgs)HandlesMyBase.Load
DimNumAsInteger
DimiAsInteger
Me.Text="Enteros"
Num=Val(InputBox("Introduzcaunnmeroentero
comprendidoentre1y99","Nmero?"))
LabelTabla.TextAlign=ContentAlignment.MiddleCente
LabelTabla.Font=NewFont("Arial",10,FontStyle.Bol
LabelTabla.Text="ENTEROSENTRE"&Num&"y10
vbCrLf&vbCrLf
Fori=NumTo100
LabelTabla.Text=LabelTabla.Text&i&""
Nexti

http://aprenderaprogramar.com/index.php?option=com_content&view=article&id=263:buclesciclosvisualbasicfornextstepdowhileloopuntilejempl

4/7

4/4/2015

Bucles(ciclos)VisualBasic:ForNextStep,DoWhileLoop,Until.Ejemplosyejerciciosresueltos(CU00326A)

EndSub

EndSub
EndClass

Aspectogrfico:

INSTRUCCINMIENTRAS...HACER(DOWHILE...LOOP)
Lasintaxisquehemosdeseguireslasiguiente:

DoWhile[condicin]
Instruccin1
Instruccin2
.
.
.
Instruccinn
Loop

http://aprenderaprogramar.com/index.php?option=com_content&view=article&id=263:buclesciclosvisualbasicfornextstepdowhileloopuntilejempl

5/7

4/4/2015

Bucles(ciclos)VisualBasic:ForNextStep,DoWhileLoop,Until.Ejemplosyejerciciosresueltos(CU00326A)

LasinstruccionestipoDoWhilesonanidablesdentrodesmismasodentrodeotrasestructuras.Esimportanteverificarqu
diseadosconestainstruccindispongandeunacondicindesalidavlida.
Ejemplo:k=0:Dowhilek<5.Dentrodelbucletendremosqueincrementarelvalordek,k=k+1.

INSTRUCCINHACER...REPETIRMIENTRAS(DO...LOOPWHILE)
Lasintaxisautilizares:

Do
Instruccin1
Instruccin2
.
.
.
Instruccinn
LoopWhile[condicin]

Un Do ... Loop While es anidable dentro de s mismo o dentro de otras estructuras. Es importante verificar que los bucle
conestainstruccindispongandeunacondicindesalidavlida.
Ejemplo:
Do
LabelTabla.Text=LabelTabla.Text&"Iteracin"&k&vbCrLf
k=k+1
LoopWhilek<=5

VisualBasicadmiteademsdelaclusulaWhile,usareltrminoUntil,comoequivalente
a"hastaquesecumplaque".AsLoopUntili>=3significara"Repetirhastaqueiseamayor
oigualque3".EnunbucleenelqueipartedeunvalorceroyseincrementaunitariamenteDoWhilei<
3seraequivalenteaDoUntili>=3,yLoopUntili>=3seraequivalenteaLoopWhilei<3.Dadoque
podemos valernos de equivalencias, puede evitar confundirnos el usar preferentemente un mismo tipo de
expresin,sabiendoquedisponemosdeotraequivalente.

http://aprenderaprogramar.com/index.php?option=com_content&view=article&id=263:buclesciclosvisualbasicfornextstepdowhileloopuntilejempl

6/7

4/4/2015

Bucles(ciclos)VisualBasic:ForNextStep,DoWhileLoop,Until.Ejemplosyejerciciosresueltos(CU00326A)

Paraaccederalainformacingeneralsobreestecursoyallistadocompletodeentregaspulsaenestelink:Vercursocomp

Parahaceruncomentariooconsultautilizalosforosaprenderaprogramar.com,abiertosacualquierpersonaindependientem
niveldeconocimiento.

Bajararchivo...
Archivo
CU00326ABuclesfornextstepdowhilelooploopwhileVisualBasic
ejemplo.pdf

<Anterior

Informacin
adicional:

Tamaodearchivo

Formatopdf

124Kb

Prximo>

Copyright20062015aprenderaprogramar.comLawebabiertaacualquierpersona

http://aprenderaprogramar.com/index.php?option=com_content&view=article&id=263:buclesciclosvisualbasicfornextstepdowhileloopuntilejempl

7/7

Você também pode gostar