# GATE2002-11

16 votes
1.4k views

The following recursive function in C is a solution to the Towers of Hanoi problem.

void move(int n, char A, char B, char C)  {
if (......................) {
move (.............................);
printf("Move disk %d from pole %c to pole %c\n", n, A,C);
move (.....................);
}
}

Fill in the dotted parts of the solution.

recategorized
2
If(n==1) { Printf("\n %s %c %s %c","move disk1 from pole",A,"to pole",B); Return; } Towers(n-1,A,C,B); Printf.... Towers(n-1,C,B,A);

## 2 Answers

20 votes

Best answer
void move(int n, char A, char B, char C) {
if (n > 0) {
move (n-1, A, C, B);
printf("Move disk %d from pole %c to pole %c\n", n, A, C);
move (n-1, B, A, C);
}
}

edited by
12

The snippet tells that A must be a source and C the destination.That means function would be move(src,spare,dest).

Firstcall(A,B,C) A to C using B intermediate

If we go by this defination, first move(n-1,A,C,B) will move n-1 disks to B using C as spare.

Now the 1 that remains is moved from A(src) to C(dest).

Shouldn't the last call then be move(n-1,B,A,C) ,that is moving the n-1 disk that were previously moved to intermediate node B over C(the destination) ?

3
correct now?
1
yes
1
Yes it is correct !!
7 votes
If(n==1) { Printf("\n %s %c %s %c","move disk1 from pole",A,"to pole",B); Return; } Towers(n-1,A,C,B); Printf.... Towers(n-1,C,B,A);

## Related questions

26 votes
2 answers
1
3.7k views
In the C language: At most one activation record exists between the current activation record and the activation record for the main The number of activation records between the current activation record and the activation records from the main depends on the actual ... the activation record for the recursive function to be saved in a different stack before the recursive function can be called.
20 votes
3 answers
2
3.7k views
The C language is: A context free language A context sensitive language A regular language Parsable fully only by a Turing machine
10 votes
2 answers
3
3.1k views
The results returned by function under value-result and reference parameter passing conventions Do not differ Differ in the presence of loops Differ in all cases May differ in the presence of exception
21 votes
2 answers
4
2.8k views
Consider the following C program: void abc(char*s) { if(s[0]=='\0')return; abc(s+1); abc(s+1); printf("%c",s[0]); } main() { abc("123"); } What will be the output of the program? If $abc(s)$ is called with a null-terminated string $s$ of length $n$ characters (not counting the null ('\0') character), how many characters will be printed by $abc(s)$?