By Reference and by Value
Sorts three numbers by swapping them in subprocesses.
- Level
- Intermediate
- Topic:
- Subprocesses & functions
- Concepts:
- Input & output
- SubProcesos
- Por Referencia
- Si
Run, change and debug this example in your browser.
What you'll learn
With Por Referencia a SubProceso changes the original variables; with Por Valor it only changes a copy. One SubProceso can call another, as OrdenarTres calls Intercambiar.
Code
SubProceso Intercambiar(a Por Referencia, b Por Referencia) Definir temporal Como Real temporal <- a a <- b b <- temporalFinSubProcesoSubProceso OrdenarTres(n1 Por Referencia, n2 Por Referencia, n3 Por Referencia) Si n1 > n2 Entonces Intercambiar(n1, n2) FinSi Si n2 > n3 Entonces Intercambiar(n2, n3) FinSi Si n1 > n2 Entonces Intercambiar(n1, n2) FinSiFinSubProcesoSubProceso IntentarCambiar(n Por Valor) // Solo cambia la copia local n <- 0FinSubProcesoAlgoritmo PorReferencia Definir a, b, c Como Real Escribir "Escribe tres números:" Leer a, b, c OrdenarTres(a, b, c) Escribir "Ordenados: ", a, " ", b, " ", c IntentarCambiar(a) Escribir "Por valor, a sigue valiendo ", aFinAlgoritmoFlowchart
Each block in the flowchart matches one instruction in the code.
Sample run
This is what the program shows when it runs. The answers typed by the user are highlighted.
Escribe tres números:User answer: 9User answer: 2User answer: 5Ordenados: 2 5 9Por valor, a sigue valiendo 2
Challenge
Add a SubProceso Duplicar(n Por Referencia) and use it to double the largest of the three.
Show hint
After OrdenarTres, the largest number is always in c.
Related examples
Towers of Hanoi
Solves the classic tower puzzle step by step.
AdvancedBubble Sort
Sorts random numbers by swapping neighbors, and stops as soon as they're in order.
IntermediateSelection Sort
Finds the smallest of the remaining numbers and puts it in its place.
Intermediate