• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 07:14
CET 13:14
KST 21:14
  • 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
RSL Season 3 - RO16 Groups C & D Preview0RSL Season 3 - RO16 Groups A & B Preview2TL.net Map Contest #21: Winners12Intel X Team Liquid Seoul event: Showmatches and Meet the Pros10[ASL20] Finals Preview: Arrival13
Community News
[TLMC] Fall/Winter 2025 Ladder Map Rotation12Weekly Cups (Nov 3-9): Clem Conquers in Canada4SC: Evo Complete - Ranked Ladder OPEN ALPHA8StarCraft, SC2, HotS, WC3, Returning to Blizzcon!45$5,000+ WardiTV 2025 Championship7
StarCraft 2
General
Mech is the composition that needs teleportation t RotterdaM "Serral is the GOAT, and it's not close" RSL Season 3 - RO16 Groups C & D Preview [TLMC] Fall/Winter 2025 Ladder Map Rotation TL.net Map Contest #21: Winners
Tourneys
RSL Revival: Season 3 Sparkling Tuna Cup - Weekly Open Tournament Constellation Cup - Main Event - Stellar Fest Tenacious Turtle Tussle Master Swan Open (Global Bronze-Master 2)
Strategy
Custom Maps
Map Editor closed ?
External Content
Mutation # 499 Chilling Adaptation Mutation # 498 Wheel of Misfortune|Cradle of Death Mutation # 497 Battle Haredened Mutation # 496 Endless Infection
Brood War
General
FlaSh on: Biggest Problem With SnOw's Playstyle BW General Discussion What happened to TvZ on Retro? Brood War web app to calculate unit interactions [ASL20] Ask the mapmakers — Drop your questions
Tourneys
[Megathread] Daily Proleagues Small VOD Thread 2.0 [BSL21] RO32 Group D - Sunday 21:00 CET [BSL21] RO32 Group C - Saturday 21:00 CET
Strategy
PvZ map balance Current Meta Simple Questions, Simple Answers How to stay on top of macro?
Other Games
General Games
Path of Exile Stormgate/Frost Giant Megathread Nintendo Switch Thread Clair Obscur - Expedition 33 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
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread SPIRED by.ASL Mafia {211640}
Community
General
Things Aren’t Peaceful in Palestine US Politics Mega-thread Russo-Ukrainian War Thread Artificial Intelligence Thread Canadian Politics Mega-thread
Fan Clubs
White-Ra Fan Club The herO Fan Club!
Media & Entertainment
[Manga] One Piece Anime Discussion Thread Movie Discussion! Korean Music Discussion Series you have seen recently...
Sports
2024 - 2026 Football Thread Formula 1 Discussion NBA General Discussion MLB/Baseball 2023 TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
SC2 Client Relocalization [Change SC2 Language] Linksys AE2500 USB WIFI keeps disconnecting Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List
Blogs
Dyadica Gospel – a Pulp No…
Hildegard
Coffee x Performance in Espo…
TrAiDoS
Saturation point
Uldridge
DnB/metal remix FFO Mick Go…
ImbaTosS
Reality "theory" prov…
perfectspheres
Customize Sidebar...

Website Feedback

Closed Threads



Active: 2230 users

Stack vs Recursion

Blogs > EsX_Raptor
Post a Reply
EsX_Raptor
Profile Blog Joined February 2008
United States2802 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 States2802 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 States3702 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 States2802 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
Kung Fu Cup
12:00
2025 Monthly #3: Day 4
Cure vs Reynor
Classic vs herO
RotterdaM385
IntoTheiNu 46
SteadfastSC18
IndyStarCraft 0
Liquipedia
RSL Revival
10:00
Group C
SHIN vs ByuN
Crank 1212
Tasteless862
ComeBackTV 797
Rex125
3DClanTV 66
Liquipedia
CranKy Ducklings
10:00
Master Swan Open #98
CranKy Ducklings41
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
Crank 1212
Tasteless 862
RotterdaM 385
IndyStarCraft 179
Rex 125
Reynor 117
Railgan 37
SteadfastSC 18
StarCraft: Brood War
Britney 35036
Rain 3915
Horang2 1416
Hyuk 1361
firebathero 1294
Jaedong 836
Shuttle 589
Mini 431
Stork 338
BeSt 328
[ Show more ]
Last 223
PianO 177
Hm[arnc] 161
Leta 160
EffOrt 149
Shine 123
Pusan 120
Mong 92
Hyun 83
sorry 70
Shinee 67
Barracks 64
ggaemo 54
JYJ43
JulyZerg 32
soO 27
Movie 17
Bale 16
Noble 15
HiyA 12
ajuk12(nOOB) 8
Dota 2
Gorgc4605
singsing2226
XaKoH 424
XcaliburYe240
Dendi126
Counter-Strike
fl0m3292
zeus359
Other Games
FrodaN4576
B2W.Neo1686
KnowMe209
Fuzer 174
Lowko100
Mew2King57
MindelVK9
Organizations
Dota 2
PGL Dota 2 - Main Stream7428
PGL Dota 2 - Secondary Stream1548
Other Games
gamesdonequick592
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 14 non-featured ]
StarCraft 2
• Berry_CruncH141
• Adnapsc2 6
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• C_a_k_e 957
League of Legends
• Stunt1261
Upcoming Events
IPSL
4h 47m
ZZZero vs rasowy
Napoleon vs KameZerg
OSC
6h 47m
BSL 21
7h 47m
Tarson vs Julia
Doodle vs OldBoy
eOnzErG vs WolFix
StRyKeR vs Aeternum
Sparkling Tuna Cup
21h 47m
RSL Revival
21h 47m
Reynor vs sOs
Maru vs Ryung
Kung Fu Cup
23h 47m
WardiTV Korean Royale
23h 47m
BSL 21
1d 7h
JDConan vs Semih
Dragon vs Dienmax
Tech vs NewOcean
TerrOr vs Artosis
IPSL
1d 7h
Dewalt vs WolFix
eOnzErG vs Bonyth
Replay Cast
1d 10h
[ Show More ]
Wardi Open
1d 23h
Monday Night Weeklies
2 days
WardiTV Korean Royale
2 days
BSL: GosuLeague
3 days
The PondCast
3 days
Replay Cast
4 days
RSL Revival
4 days
BSL: GosuLeague
5 days
RSL Revival
5 days
WardiTV Korean Royale
5 days
RSL Revival
6 days
WardiTV Korean Royale
6 days
Liquipedia Results

Completed

Proleague 2025-11-07
Stellar Fest: Constellation Cup
Eternal Conflict S1

Ongoing

C-Race Season 1
IPSL Winter 2025-26
KCM Race Survival 2025 Season 4
SOOP Univ League 2025
YSL S2
BSL Season 21
CSCL: Masked Kings S3
SLON Tour Season 2
RSL Revival: Season 3
META Madness #9
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
CS Asia Championships 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025

Upcoming

BSL 21 Non-Korean Championship
Acropolis #4
IPSL Spring 2026
HSC XXVIII
RSL Offline Finals
WardiTV 2025
IEM Kraków 2026
BLAST Bounty Winter 2026
BLAST Bounty Winter 2026: Closed Qualifier
eXTREMESLAND 2025
ESL Impact League Season 8
SL Budapest Major 2025
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.