473,586 Members | 2,682 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to write a nonrecursive program ?

The Towers of Hanoi is a famous problem about moving a certain number
of disks from one peg to another.I write a recursive program for it.If
you have known it ,you can skip the program.
#include <stdio.h>
void hanoi(int num,char initial,char terminal,char temporary);
void main (){
int num;/*num is the number of disks of the initial peg*/
char a='a',b='b',c=' c';
/*a is the initial peg ,c is the terminal peg,b is used as a temporary
peg*/
printf("enter the number of disks:");
scanf("%d",&num );
hanoi(num,a,c,b );
}
void hanoi(int num,char initial,char terminal,char temporary){
if (num==1)
printf("%c==>%c \n",initial,ter minal);
else{/*move the disks in a recrusive way*/
hanoi(num-1,initial,tempo rary,terminal);
printf("%c==>%c \n",initial,ter minal);
hanoi(num-1,temporary,ter minal,initial);
}
}
I can write a program with a recursive funcation easily.But many books
say that any program that can be implemented recursively can be
implemented iteratively.I don't know how to write a corresponding
iteratively.Cou ld you tell me how to write a nonrecursive program that
have the same funcation with a recursive program
There are many exercises in my book about recursive programs.For most
of them,I find it is hard to write a corresponding iterative
program.Could you tell me what kind of books I need to read?
I am grateful for your help!
Nov 15 '08 #1
11 4741
On Nov 14, 6:17*pm, 960392...@qq.co m wrote:
The Towers of Hanoi is a famous problem about moving a certain number
of disks from one peg to another.I write a recursive program for it.If
you have known it ,you can skip the program.
#include <stdio.h>
void hanoi(int num,char initial,char terminal,char temporary);
void main (){
From the C-FAQ:
1.25b: What's the right declaration for main()?
Is void main() correct?

A: See questions 11.12a through 11.15. (But no, it's not correct.)

* * * * int num;/*num is the number of disks of the initial peg*/
* * * * char a='a',b='b',c=' c';
/*a is the initial peg ,c is the terminal peg,b is used as a temporary
peg*/
* * * * printf("enter the number of disks:");
* * * * scanf("%d",&num );
* * * * hanoi(num,a,c,b );}

void hanoi(int num,char initial,char terminal,char temporary){
* * * * if (num==1)
* * * * * * * * printf("%c==>%c \n",initial,ter minal);
* * * * else{/*move the disks in a recrusive way*/
* * * * * * * * hanoi(num-1,initial,tempo rary,terminal);
* * * * * * * * printf("%c==>%c \n",initial,ter minal);
* * * * * * * * hanoi(num-1,temporary,ter minal,initial);
* * * * }}

I can write a program with a recursive funcation easily.But many books
say that any program that can be implemented recursively can be
implemented iteratively.I don't know how to write a corresponding
iteratively.Cou ld you tell me how to write a nonrecursive program that
have the same funcation with a recursive program
There are many exercises in my book about recursive programs.For most
of them,I find it is hard to write a corresponding iterative
program.Could you tell me what kind of books I need to read?
You can convert iteration to recursion by managing your own stack. I
did a non-recursive quicksort that way a long time ago.

If it is only tail recursion, don't worry about it because the
compiler will probably rewrite it as iterative for you anyway.

You can program it directly, or write an abstract stack and push and
pop items.
Nov 15 '08 #2
<96*******@qq.c omwrote in message
news:d7******** *************** ***********@v16 g2000prc.google groups.com...
The Towers of Hanoi is a famous problem about moving a certain number
of disks from one peg to another.I write a recursive program for it.If
you have known it ,you can skip the program.
(snipped)
I can write a program with a recursive funcation easily.But many books
say that any program that can be implemented recursively can be
implemented iteratively.I don't know how to write a corresponding
iteratively.Cou ld you tell me how to write a nonrecursive program that
have the same funcation with a recursive program
There are many exercises in my book about recursive programs.For most
of them,I find it is hard to write a corresponding iterative
program.Could you tell me what kind of books I need to read?
I am grateful for your help!
In this particular case, wikipedia knows all:
http://en.wikipedia.org/wiki/Tower_o...rsive_solution
As to other problems.. It often helps to try to think of a "bottom-up"
algorithm - often it won't be recursive anymore (but no guarantees here)
You could always cheat by emulating a stack in software, but it's cheating.

Nov 15 '08 #3
On 2008-11-15, 96*******@qq.co m <96*******@qq.c omwrote:
I can write a program with a recursive funcation easily.But many books
say that any program that can be implemented recursively can be
implemented iteratively.I don't know how to write a corresponding
iteratively.Cou ld you tell me how to write a nonrecursive program that
have the same funcation with a recursive program
Minor niggle - the program you wrote is not recursive in any case
(it does not invoke itself). It is the fucntion hanoi() that is
recursive.

--
Andrew Smallshaw
an*****@sdf.lon estar.org
Nov 15 '08 #4
user923005 wrote:
>
.... snip ...
>
You can convert iteration to recursion by managing your own stack.
I did a non-recursive quicksort that way a long time ago.

If it is only tail recursion, don't worry about it because the
compiler will probably rewrite it as iterative for you anyway.
You mean it MAY rewrite it as interactive, depending on the
compilers capability and the optimization level selected.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
Nov 15 '08 #5
On 15 Nov 2008 at 23:16, CBFalconer wrote:
user923005 wrote:
>If it is only tail recursion, don't worry about it because the
compiler will probably rewrite it as iterative for you anyway.

You mean it MAY rewrite it as interactive
You really don't have any idea what you're talking about, do you?

Interactive and iterative are completely different things.

Nov 15 '08 #6
"Antoninus Twink" wrote:
On 15 Nov 2008 at 23:16, CBFalconer wrote:
>user923005 wrote:
>>If it is only tail recursion, don't worry about it because the
compiler will probably rewrite it as iterative for you anyway.

You mean it MAY rewrite it as interactive

You really don't have any idea what you're talking about, do you?

Interactive and iterative are completely different things.
A spell checker sometimes causes nasty substitutions like that. But even if
it did, CBF should know that "will probably" and "may" mean quite similar
things. I think it's lonely in that basement.
Nov 16 '08 #7
On Nov 15, 4:33*pm, "osmium" <r124c4u...@com cast.netwrote:
"Antoninus Twink" wrote:
On 15 Nov 2008 at 23:16, CBFalconer wrote:
user923005 wrote:
If it is only tail recursion, don't worry about it because the
compiler will probably rewrite it as iterative for you anyway.
You mean it MAY rewrite it as interactive
You really don't have any idea what you're talking about, do you?
Interactive and iterative are completely different things.

A spell checker sometimes causes nasty substitutions like that. *But even if
it did, CBF should know that "will probably" and "may" mean quite similar
things. *I think it's lonely in that basement.
I wouldn't be too hard on him. I certainly suffered no offense. I
found quite an interesting dissertation on the towers of Hanoi in
Sedgewick. He shows that it is equivalent to many other problems
(including setting the markings on a ruler). Here is a fascinating
non-recursive version that I found:

#include <stdio.h>
#include <stdlib.h>

int main()
{
char string[25];
unsigned long long n,
one = 1,
x;
retry:
puts("How many disks?");
fflush(stdout);
if (fgets(string, sizeof string, stdin)) {
n = (unsigned long long) atof(string);
if (n == 0)
goto retry;
} else
goto retry;

for (x = 1; x < (one << n); x++)
printf("Move from pole %llu to pole %llu.\n", (x & x - 1) % 3,
(((x | x - 1) + 1) % 3));
return 0;
}

Nov 17 '08 #8
In article <d7************ *************** *******@v16g200 0prc.googlegrou ps.com>,
<96*******@qq.c omwrote:

Aaggh! My eyes! The goggles do nothing!

Seriously, dude. Spaces and blank lines are your friend. Why make the code
hard to read? See below. I'll refrain from nitpicking things like validating
your input or having main() return something useful.

But to answer your question, the usual way to "flatten out" a recursive
algorithm is to maintain a data stack. It can require a little creativity
to convert an algorithm from recursive to something else.

But why bother? Are you planning to implement an algorithm on a machine
or in a language that can't recurse? It's been a while since I last
programmed an IBM 370 or a PDP-8, and I can't imagine that's what you're
looking at.
>#include <stdio.h>

void hanoi(int num, char initial, char terminal, char temporary);

int main ()
{
int num; /*num is the number of disks of the initial peg*/
/*a is the initial peg , c is the terminal peg, b is used as a temporary peg*/
char a='a', b='b', c='c';

printf("enter the number of disks:");
scanf("%d", &num);
hanoi(num, a, c, b);
}

void hanoi(int num, char initial, char terminal, char temporary)
{
if (num==1)
printf("%c==>%c \n", initial, terminal);
else{
/*move the disks in a recrusive way*/
hanoi(num-1, initial, temporary, terminal);
printf("%c==>%c \n", initial, terminal);
hanoi(num-1, temporary, terminal, initial);
}
}
--
-Ed Falk, fa**@despams.r. us.com
http://thespamdiaries.blogspot.com/
Nov 19 '08 #9
"Edward A. Falk" wrote:
>
.... snip ...
>
Aaggh! My eyes! The goggles do nothing!

Seriously, dude. Spaces and blank lines are your friend. Why
make the code hard to read? See below. I'll refrain from
nitpicking things like validating your input or having main()
return something useful.
Please do not top-post. Your answer belongs after (or intermixed
with) the quoted material to which you reply, after snipping all
irrelevant material. See the following links:

<http://www.catb.org/~esr/faqs/smart-questions.html>
<http://www.caliburn.nl/topposting.html >
<http://www.netmeister. org/news/learn2quote.htm l>
<http://cfaj.freeshell. org/google/ (taming google)
<http://members.fortune city.com/nnqweb/ (newusers)

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
Nov 19 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

33
3469
by: Nick Evans | last post by:
Hello there, I have been on and off learning to code (with python being the second language I have worked on after a bit of BASIC). What I really want to know is, if you are going to actually write a program or a project of some sort, how do you actually start. Picture this, you know what you want the program to do (its features), you have...
8
2500
by: Zheng Da | last post by:
I don't know where should I ask the question, so send the email to this group. I choose this group, because I want to write the program with c++ :) I want to write a program which support multiprotocol, but do not want to write code for all protocols which I want to support. I plan I give a interface and others give a module which implements...
24
3228
by: gswork | last post by:
Let's write a c program, without knowing what it does... Some of you may recall Jim Roger's excellent series of posts (on comp.programming) exploring the implementation of common software activities in different languages by requesting small working programs as source. Well, having thought & read about the benefits of teamwork, oss,...
24
5839
by: Charles Ulrich | last post by:
Greetings, I hope my greenness isn't showing too bad by asking this, but I ran across this trivial program today that left me flabbergasted: #define MESSAGE "This account is currently not available.\n" int main(int argc, char *argv) {
18
3684
by: jacob navia | last post by:
In C, we have read-only memory (const), read/write memory (normal data), and write only memory. Let's look at the third one in more detail. Write only memory is a piece of RAM that can only be written to, since its contents are undefined. The program is allocating a new piece of data, and the previous contents aren't relevant. This...
1
1880
by: revhemphill | last post by:
I wrote this program to calculate factorials by recursion, how would I make it nonrecursive and iterative? Thank you to whom ever may be of assistance #include <iostream> using std::cout; using std::endl; #include <iomanip>
4
2380
by: Break2 | last post by:
I am trying to write a simple program which asks a user to enter 5 integers after which the average will be computed and written to the screen. That simple. However I want to do it according to a standard I used before to write a program which asked a user to enter the current year and his birthyear after which the current age of the user was...
1
3922
by: Sachin Garg | last post by:
I have a program which opens a fstream in binary input+output mode, creating the file if it doesn't exists. But writing doesn't works after reading, it must be something obvious that I am not aware of. f.open(filename,ios::in | ios::out | ios::binary | ios::trunc) The program flow is 1) write some data 2) read the data
5
3651
by: Jon Skeet [C# MVP] | last post by:
On Sep 9, 9:41 am, raylopez99 <raylope...@yahoo.comwrote: It's tricky in .NET for two reasons: 1) LINQ doesn't have any concept of "remove" 2) List<T>.RemoveAll doesn't pass in the index (which makes sense as it would then need to If List<Tsupported some sort of "view" which also exposed RemoveAll, it would be easy:
0
7839
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8202
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8338
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7959
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8216
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6614
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3865
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2345
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.