• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 09:32
CEST 15:32
KST 22:32
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
[ASL19] Finals Recap: Standing Tall9HomeStory Cup 27 - Info & Preview18Classic wins Code S Season 2 (2025)16Code S RO4 & Finals Preview: herO, Rogue, Classic, GuMiho0TL Team Map Contest #5: Presented by Monster Energy6
Community News
Weekly Cups (June 30 - July 6): Classic Doubles1[BSL20] Non-Korean Championship 4x BSL + 4x China7Flash Announces Hiatus From ASL64Weekly Cups (June 23-29): Reynor in world title form?13FEL Cracov 2025 (July 27) - $8000 live event22
StarCraft 2
General
Weekly Cups (June 30 - July 6): Classic Doubles Program: SC2 / XSplit / OBS Scene Switcher The SCII GOAT: A statistical Evaluation Statistics for vetoed/disliked maps Weekly Cups (June 23-29): Reynor in world title form?
Tourneys
RSL: Revival, a new crowdfunded tournament series FEL Cracov 2025 (July 27) - $8000 live event Sparkling Tuna Cup - Weekly Open Tournament WardiTV Mondays Korean Starcraft League Week 77
Strategy
How did i lose this ZvP, whats the proper response Simple Questions Simple Answers
Custom Maps
[UMS] Zillion Zerglings
External Content
Mutation # 481 Fear and Lava Mutation # 480 Moths to the Flame Mutation # 479 Worn Out Welcome Mutation # 478 Instant Karma
Brood War
General
SC uni coach streams logging into betting site BGH Auto Balance -> http://bghmmr.eu/ ASL20 Preliminary Maps Flash Announces Hiatus From ASL Player “Jedi” cheat on CSL
Tourneys
[BSL20] Grand Finals - Sunday 20:00 CET [BSL20] Non-Korean Championship 4x BSL + 4x China CSL Xiamen International Invitational The Casual Games of the Week Thread
Strategy
Simple Questions, Simple Answers I am doing this better than progamers do.
Other Games
General Games
Stormgate/Frost Giant Megathread Path of Exile Nintendo Switch Thread What do you want from future RTS games? Beyond All Reason
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
US Politics Mega-thread Russo-Ukrainian War Thread Stop Killing Games - European Citizens Initiative Summer Games Done Quick 2024! Summer Games Done Quick 2025!
Fan Clubs
SKT1 Classic Fan Club! Maru Fan Club
Media & Entertainment
Anime Discussion Thread [Manga] One Piece [\m/] Heavy Metal Thread
Sports
Formula 1 Discussion 2024 - 2025 Football Thread NBA General Discussion TeamLiquid Health and Fitness Initiative For 2023 NHL Playoffs 2024
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List
Blogs
Culture Clash in Video Games…
TrAiDoS
from making sc maps to makin…
Husyelt
Blog #2
tankgirl
StarCraft improvement
iopq
Trip to the Zoo
micronesia
Customize Sidebar...

Website Feedback

Closed Threads



Active: 721 users

Stack vs Recursion

Blogs > EsX_Raptor
Post a Reply
EsX_Raptor
Profile Blog Joined February 2008
United States2801 Posts
April 24 2009 06:15 GMT
#1
Alright, we all know what a recursive function is (C++ example):

[image loading]


But I heard that it is also possible to implement that same thing, but using a stack.

I just want to hear what you guys think would be the way to do it, or how to approach it, 'cause I spent the entire day today trying to figure out how.

*
Divinek
Profile Blog Joined November 2006
Canada4045 Posts
April 24 2009 06:17 GMT
#2
Well if you understand what a stackframe is in java and how recursion works there,it's the same idea
Never attribute to malice that which can be adequately explained by stupidity.
Oh goodness me, FOX tv where do you get your sight? Can't you keep track, the puck is black. That's why the ice is white.
BottleAbuser
Profile Blog Joined December 2007
Korea (South)1888 Posts
Last Edited: 2009-04-24 06:22:52
April 24 2009 06:19 GMT
#3
Recursion is implemented with a stack in most computers, actually.

Here's an explicit stack example (Java noob here, sorry):

int factorial(int n){
Stack s = new Stack();
for(int i=1; i<=n;i++){
s.push(i);
}
int result = 1;
while(!s.isEmpty()){
result*=s.pop();
}
return result;
}
Compilers are like boyfriends, you miss a period and they go crazy on you.
cgrinker
Profile Blog Joined December 2007
United States3824 Posts
April 24 2009 06:20 GMT
#4
Do you have direct control of the stack in C++? We do it when we code in assembly (Jasmin) put the idea of recursion is that when your function calls itself every call is pushed onto the stack so that once you reach your base case you start popping values down the stack.

Is it a trick question? the recursive function is computed on the stack (just like everything else) when its compiled down to x86. Are you sure you aren't supposed to be doing your assingment in 8086 op codes?
EsX_Raptor
Profile Blog Joined February 2008
United States2801 Posts
Last Edited: 2009-04-24 06:33:55
April 24 2009 06:32 GMT
#5
its not an assignment, I just want to know how to program recursive functions using stacks instead.
(edit: for example, what would I do when I need to implement a naturally recursive function in FORTRAN which doesn't allow recursion)

In C++, I actually made the stack myself and I just push, pop and top stuff from it.

I'll do what you said cgrinker, brb.
haduken
Profile Blog Joined April 2003
Australia8267 Posts
April 24 2009 06:39 GMT
#6
??? weird question.

Recursive functions make implied use of the stack by storing auto variables, function heads and other infos.

If you are talking about computing models then stack is recursive by its own defination (I could be wrong here).
Rillanon.au
cgrinker
Profile Blog Joined December 2007
United States3824 Posts
April 24 2009 06:50 GMT
#7
in x86!

;Factorial using recursion
;x is the input

ADD AX, x
ADD BX, x
fact; begin
MUL BX, AX
SUB AX, 1
CMP AX, 1
JNZ fact
NOP
HLT
cgrinker
Profile Blog Joined December 2007
United States3824 Posts
April 24 2009 06:52 GMT
#8
If you can't do function calls then you are going to have to use a pointer function like JMP (jump) or, god forbid some kind of goto thing. Then you need to compare the value to see if you have reached your base case. Its kinda backwards in assembly.
prOxi.swAMi
Profile Blog Joined November 2004
Australia3091 Posts
April 24 2009 06:53 GMT
#9
Recursive functions, a function calling itself, IS using a stack...
Oh no
imDerek
Profile Blog Joined August 2007
United States1944 Posts
April 24 2009 06:57 GMT
#10
all procedure calls are using a stack to keep track of frames
Least favorite progamers: Leta, Zero, Mind, Shine, free, really <-- newly added
evanthebouncy!
Profile Blog Joined June 2006
United States12796 Posts
April 24 2009 07:00 GMT
#11
If you want to do it with stack consider this code in MIPS:
It's the tower of Hannoi:

#$s1 saves n number
#$s2 saves source
#$s3 saves dest
#$s4 saves help
#$ra saves return_address via JAL

.data
n: .word 30
source: .asciiz "A"
destination: .asciiz "B"
helper: .asciiz "C"
newline: .asciiz "\n"

.text
main:
lw $s1, n
la $s2, source
la $s3, destination
la $s4, helper
la $s5, newline
jal loop
j done

loop:
addi $sp, $sp, -20 #pull down stack and save junks
sw $ra, 0($sp) #save return address first
sw $s1, 4($sp) #push n to stack
sw $s2, 8($sp) #push source to stack
sw $s3, 12($sp) #push dest to stack
sw $s4, 16($sp) #push helper stack

jal test #see if we reached 0, if no, continue, if yes, go to end_loop

addi $s1, $s1, -1 #decrease n by 1
move $t0, $s3 #swap dest with help
move $s3, $s4
move $s4, $t0
jal loop #loop again, send it downward to the tree

li $v0, 4 #print stuff
lw $a0, 8($sp)
syscall
lw $a0, 12($sp)
syscall
addi $a0, $s5, 0
syscall

lw $s2, 8($sp) #load up the source/helper, swap them
lw $s3, 12($sp)
lw $s4, 16($sp)
move $t0, $s2
move $s2, $s4
move $s4, $t0
jal loop #going down again.

end_loop: #get the register return address, and return it
lw $ra, 0($sp) #reload register
lw $s1, 4($sp) #reload n to return to upper level
addi $sp, $sp, 20 #pop stacks
jr $ra #return to what called it

test:
beq $s1, $zero, is_zero #if it is 0, go to is_zero option
jr $ra #if it's not 0, simply return to deepen the tree
is_zero:
j end_loop #jump to end of the loop

done:
li $v0, 10
syscall
Life is run, it is dance, it is fast, passionate and BAM!, you dance and sing and booze while you can for now is the time and time is mine. Smile and laugh when still can for now is the time and soon you die!
tec27
Profile Blog Joined June 2004
United States3696 Posts
April 24 2009 07:28 GMT
#12
On April 24 2009 15:20 cgrinker wrote:
Do you have direct control of the stack in C++? We do it when we code in assembly (Jasmin) put the idea of recursion is that when your function calls itself every call is pushed onto the stack so that once you reach your base case you start popping values down the stack.

Is it a trick question? the recursive function is computed on the stack (just like everything else) when its compiled down to x86. Are you sure you aren't supposed to be doing your assingment in 8086 op codes?

You're confusing "the stack" with "a stack". A stack, as I'm sure you probably realize is just a type of data structure with a LIFO interface. "The stack" that you speak of is a specific usage of that data structure for storing info such as function parameters/return addresses. So while when you implement this algorithm using a lower level language like assembly, it may be easier to use "the stack" as the stack in question, higher level languages would typically create a new object of a stack class and use that.
Can you jam with the console cowboys in cyberspace?
Cambium
Profile Blog Joined June 2004
United States16368 Posts
Last Edited: 2009-04-24 07:53:19
April 24 2009 07:52 GMT
#13
int factorial( int n ) {
Stack stach = new Stack();
for( int i = 0; i < n; i ++ )
stach.push( i );

int result = 1;
while( !stach.empty() ){
result * = (int) stach.pop();
}
return result;
}
When you want something, all the universe conspires in helping you to achieve it.
Cambium
Profile Blog Joined June 2004
United States16368 Posts
April 24 2009 07:54 GMT
#14
The stack is completely unnecessary -_-;;
When you want something, all the universe conspires in helping you to achieve it.
EsX_Raptor
Profile Blog Joined February 2008
United States2801 Posts
April 24 2009 14:33 GMT
#15
yes exactly, sorry for the ambiguity, i meant using A stack with a LIFO interface.

trying to control THE stack would be something really complex actually, and im not yet into that level of programming >.<

i'll try to implement a quicksort using a stack.
Please log in or register to reply.
Live Events Refresh
Wardi Open
11:00
#43
WardiTV1293
OGKoka 550
Harstem428
IndyStarCraft 169
Rex167
CranKy Ducklings122
Liquipedia
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
OGKoka 550
Harstem 428
Hui .177
IndyStarCraft 169
Rex 167
StarCraft: Brood War
Bisu 2963
Flash 2112
Jaedong 1818
Hyuk 1166
firebathero 688
EffOrt 645
ZerO 538
Larva 508
actioN 436
Soulkey 387
[ Show more ]
Stork 378
Snow 308
Soma 275
GuemChi 168
Mind 132
sSak 113
Pusan 111
Light 98
PianO 80
hero 77
Sharp 74
JulyZerg 72
TY 55
Barracks 46
Yoon 38
Aegong 35
sorry 32
Free 30
GoRush 26
soO 24
zelot 23
Movie 22
HiyA 20
JYJ20
yabsab 19
IntoTheRainbow 11
Terrorterran 10
Shine 8
ivOry 4
Dota 2
qojqva3148
Gorgc2334
XaKoH 621
XcaliburYe314
syndereN307
League of Legends
singsing2548
Counter-Strike
byalli263
markeloff128
Super Smash Bros
Mew2King192
Other Games
hiko1144
B2W.Neo1138
crisheroes383
Lowko310
Beastyqt293
ArmadaUGS128
Liquid`VortiX84
ZerO(Twitch)24
Organizations
Other Games
gamesdonequick37693
StarCraft: Brood War
UltimateBattle 889
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 13 non-featured ]
StarCraft 2
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• C_a_k_e 2899
• WagamamaTV318
League of Legends
• Nemesis6070
Upcoming Events
RotterdaM Event
2h 28m
Replay Cast
10h 28m
Sparkling Tuna Cup
20h 28m
WardiTV European League
1d 2h
MaNa vs sebesdes
Mixu vs Fjant
ByuN vs HeRoMaRinE
ShoWTimE vs goblin
Gerald vs Babymarine
Krystianer vs YoungYakov
PiGosaur Monday
1d 10h
The PondCast
1d 20h
WardiTV European League
1d 22h
Jumy vs NightPhoenix
Percival vs Nicoract
ArT vs HiGhDrA
MaxPax vs Harstem
Scarlett vs Shameless
SKillous vs uThermal
uThermal 2v2 Circuit
2 days
Replay Cast
2 days
RSL Revival
2 days
ByuN vs SHIN
Clem vs Reynor
[ Show More ]
Replay Cast
3 days
RSL Revival
3 days
Classic vs Cure
FEL
4 days
RSL Revival
4 days
FEL
4 days
FEL
5 days
BSL20 Non-Korean Champi…
5 days
Bonyth vs QiaoGege
Dewalt vs Fengzi
Hawk vs Zhanhun
Sziky vs Mihu
Mihu vs QiaoGege
Zhanhun vs Sziky
Fengzi vs Hawk
Sparkling Tuna Cup
5 days
RSL Revival
5 days
FEL
6 days
BSL20 Non-Korean Champi…
6 days
Bonyth vs Dewalt
QiaoGege vs Dewalt
Hawk vs Bonyth
Sziky vs Fengzi
Mihu vs Zhanhun
QiaoGege vs Zhanhun
Fengzi vs Mihu
Liquipedia Results

Completed

BSL Season 20
HSC XXVII
Heroes 10 EU

Ongoing

JPL Season 2
BSL 2v2 Season 3
Acropolis #3
KCM Race Survival 2025 Season 2
CSL 17: 2025 SUMMER
Copa Latinoamericana 4
Jiahua Invitational
Championship of Russia 2025
RSL Revival: Season 1
Murky Cup #2
BLAST.tv Austin Major 2025
ESL Impact League Season 7
IEM Dallas 2025
PGL Astana 2025
Asian Champions League '25
BLAST Rivals Spring 2025
MESA Nomadic Masters
CCT Season 2 Global Finals
IEM Melbourne 2025

Upcoming

2025 ACS Season 2: Qualifier
CSLPRO Last Chance 2025
CSL Xiamen Invitational
2025 ACS Season 2
CSLPRO Chat StarLAN 3
K-Championship
uThermal 2v2 Main Event
SEL Season 2 Championship
FEL Cracov 2025
Esports World Cup 2025
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025
FISSURE Playground #1
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.