[Knife Test 1] qingta, niudao test Tower

Source: Internet
Author: User

[Knife Test 1] qingta, niudao test Tower

[Knife Test 1] qingta

 

Knowledge:

1. Recursion

2. Functions

3. If-else

4. Static variables

 

// Linglong Tower

The tower is A game with three towers marked as A, B, and C respectively. There are n plates on A tower,

The game is arranged from bottom up from big to small. The purpose of the game is to move the plate of tower A to Tower C,

After each move, big dishes are not allowed to appear on small dishes.

Analysis:

To move the plate of tower A to Tower C, we must use Tower B (except when n = 1) and move it again.

To Tower C.

When n = 1, A-> C

When n = 2, A-> B, A-> C, B-> C

When n = 3, A-> C, A-> B, C-> B, A-> C, B-> A, B-> C, A-> C

When n = ....

Answer: Use recursive functions (self-called)

 

 

# Include <stdio. h> // tower function definition. Recursive (self-called) // The parameters are: number of layers, tower A, tower B, and tower Cvoid tower (int num, char a, char B, char c) {staticint count = 0; // static local variable. The lifecycle is the whole program if (num = 1) {count ++; // count = count + 1; printf ("Step % 3d: % c-> % c \ n", count, a, c); // % 3d is 3} else {count ++; tower (num-1, a, c, B); // call your own printf ("Step % 3d: % c-> % c \ n", count,, c); tower (num-1, B, a, c);} return;} int main (void) {intn; // n is the number of layers in tower A printf ("input A number of layers:"); scanf ("% d", & n); // call tower of function tower (n, 'A', 'B', 'C'); return0 ;}

Running result:

 

 

[Smile at your fingertips] errors are inevitable. I hope you can get your corrections ^-^

Reprinted when retaining the original link http://codingit.howbbs.com and http://blog.csdn.net/mirrorsbeyourself

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.