• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 23:02
CET 05:02
KST 13:02
  • 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 Revival - 2025 Season Finals Preview8RSL Season 3 - Playoffs Preview0RSL Season 3 - RO16 Groups C & D Preview0RSL Season 3 - RO16 Groups A & B Preview2TL.net Map Contest #21: Winners12
Community News
SC2 All-Star Invitational: Jan 17-1812Weekly Cups (Dec 22-28): Classic & MaxPax win, Percival surprises1Weekly Cups (Dec 15-21): Classic wins big, MaxPax & Clem take weeklies3ComeBackTV's documentary on Byun's Career !11Weekly Cups (Dec 8-14): MaxPax, Clem, Cure win4
StarCraft 2
General
SC2 All-Star Invitational: Jan 17-18 Chinese SC2 server to reopen; live all-star event in Hangzhou Weekly Cups (Dec 22-28): Classic & MaxPax win, Percival surprises Starcraft 2 Zerg Coach ComeBackTV's documentary on Byun's Career !
Tourneys
OSC Season 13 World Championship $5,000+ WardiTV 2025 Championship $100 Prize Pool - Winter Warp Gate Masters Showdow Sparkling Tuna Cup - Weekly Open Tournament Winter Warp Gate Amateur Showdown #1
Strategy
Custom Maps
Map Editor closed ?
External Content
Mutation # 506 Warp Zone Mutation # 505 Rise From Ashes Mutation # 504 Retribution Mutation # 503 Fowl Play
Brood War
General
BGH Auto Balance -> http://bghmmr.eu/ BW General Discussion What monitor do you use for playing Remastered? (UMS) SWITCHEROO *New* /Destination Edit/ What are former legends up to these days?
Tourneys
[Megathread] Daily Proleagues [BSL21] LB SemiFinals - Saturday 21:00 CET [BSL21] WB & LB Finals - Sunday 21:00 CET Small VOD Thread 2.0
Strategy
Fighting Spirit mining rates Simple Questions, Simple Answers Game Theory for Starcraft Current Meta
Other Games
General Games
Stormgate/Frost Giant Megathread Nintendo Switch Thread Mechabellum Beyond All Reason Path of Exile
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
Mafia Game Mode Feedback/Ideas Survivor II: The Amazon Sengoku Mafia TL Mafia Community Thread
Community
General
US Politics Mega-thread The Games Industry And ATVI Russo-Ukrainian War Thread 12 Days of Starcraft Things Aren’t Peaceful in Palestine
Fan Clubs
White-Ra Fan Club
Media & Entertainment
Anime Discussion Thread [Manga] One Piece
Sports
2024 - 2026 Football Thread Formula 1 Discussion
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List TL+ Announced Where to ask questions and add stream?
Blogs
National Diversity: A Challe…
TrAiDoS
I decided to write a webnov…
DjKniteX
James Bond movies ranking - pa…
Topin
StarCraft improvement
iopq
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1457 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
The PiG Daily
21:15
Best Games of SC
SHIN vs sOs
Reynor vs Zoun
herO vs Classic
Solar vs Reynor
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
RuFF_SC2 157
Ketroc 54
Nina 21
StarCraft: Brood War
Leta 190
NaDa 74
ZergMaN 53
Noble 39
Hm[arnc] 17
Icarus 5
Dota 2
monkeys_forever419
LuMiX0
League of Legends
JimRising 663
C9.Mang0521
Counter-Strike
summit1g9583
tarik_tv5751
minikerr36
Super Smash Bros
hungrybox2024
Organizations
Other Games
gamesdonequick1222
BasetradeTV25
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 13 non-featured ]
StarCraft 2
• Berry_CruncH238
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• Azhi_Dahaki7
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Other Games
• Scarra1511
Upcoming Events
OSC
2 days
Korean StarCraft League
2 days
OSC
3 days
IPSL
3 days
Dewalt vs Bonyth
OSC
3 days
OSC
4 days
uThermal 2v2 Circuit
4 days
Replay Cast
5 days
Patches Events
5 days
Liquipedia Results

Completed

Proleague 2025-12-29
WardiTV 2025
META Madness #9

Ongoing

C-Race Season 1
IPSL Winter 2025-26
BSL Season 21
Slon Tour Season 2
CSL 2025 WINTER (S19)
eXTREMESLAND 2025
SL Budapest Major 2025
ESL Impact League Season 8
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
CS Asia Championships 2025

Upcoming

Escore Tournament S1: W2
Escore Tournament S1: W3
BSL 21 Non-Korean Championship
Acropolis #4
IPSL Spring 2026
Bellum Gens Elite Stara Zagora 2026
HSC XXVIII
Thunderfire SC2 All-star 2025
Big Gabe Cup #3
OSC Championship Season 13
Nations Cup 2026
Underdog Cup #3
NA Kuram Kup
ESL Pro League Season 23
ESL Pro League Season 23
PGL Cluj-Napoca 2026
IEM Kraków 2026
BLAST Bounty Winter 2026
BLAST Bounty Winter Qual
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.