ProgrammingModerateCompetitive coding (CP)
How many moves does this recursive Towers of Hanoi program make for 4 disks? Compute with the program.
How many moves does this recursive Towers of Hanoi program make for 4 disks? Compute with the program.
#include <stdio.h>
int moves = 0;
void hanoi(int n, char a, char b, char c) {
if (n == 0) return;
hanoi(n - 1, a, c, b);
moves++;
hanoi(n - 1, c, b, a);
}
int main(void) {
hanoi(4, 'A', 'B', 'C');
printf("%d", moves);
}- A. 15
- B. 16
- C. 14
- D. 8
Correct answer: A. 15
Towers of Hanoi with n disks takes 2^n - 1 moves, so 4 disks take 15 moves.
More C Programming questions
- What is printed? c #include <stdint.h> #include <stdio.h> int main(void) { uint8t x = 0x96; uint8t r = (uint8t)((x << 3) | (x >> 5))…
- What is printed? Assume signed char is 8 bits, two's complement. c #include <stdio.h> #include <stdlib.h> int cmp(const void a, const void…
- What is printed? c #include <stdio.h> #include <stdlib.h> int cmp(const void a, const void b) { long long x = (const long long )a, y =…
- What is printed? c #include <stdio.h> int calls = 0; int g(int a, int b) { calls++; return b ? g(b, a % b) : a; } int main(void) { int r =…
- How many ways are there to climb 20 steps taking 1 or 2 at a time? Compute with this exponential recursion. c #include <stdio.h> long long…
- What is printed? c #include <stdio.h> int calls = 0; int bs(int a, int lo, int hi, int k) { calls++; if (lo > hi) return -1; int m = lo +…